bevy-settings 0.19.0

User settings framework for Bevy Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
//! Framework for saving and loading user settings files in Bevy
//! applications.
//!
//! Refer to [`SettingsPlugin`] for detailed usage information.

use core::any::TypeId;
use core::time::Duration;
use std::collections::HashMap;

use bevy_app::{App, Plugin, PostUpdate};
use bevy_ecs::{
    change_detection::Tick,
    reflect::{AppTypeRegistry, ReflectComponent, ReflectResource},
    resource::Resource,
    system::{Command, Commands, Res, ResMut},
    world::World,
};
pub use bevy_ecs_macros::SettingsGroup;
use bevy_log::warn;
use bevy_reflect::{
    prelude::ReflectDefault,
    serde::{TypedReflectDeserializer, TypedReflectSerializer},
    FromReflect, FromType, PartialReflect, ReflectMut, TypeInfo, TypePath, TypeRegistration,
    TypeRegistry,
};

#[cfg(not(target_arch = "wasm32"))]
mod store_fs;

#[cfg(target_arch = "wasm32")]
mod store_wasm;

use bevy_time::{Time, Timer, TimerMode};
use serde::de::DeserializeSeed;
#[cfg(not(target_arch = "wasm32"))]
use store_fs::SettingsStore;

#[cfg(target_arch = "wasm32")]
use store_wasm::SettingsStore;

/// Plugin to orchestrate loading and saving settings.
///
/// You are required to provide a unique application name, so that your settings don't overwrite
/// those of other apps. To ensure global uniqueness, it is recommended to use a
/// [reverse domain name](https://en.wikipedia.org/wiki/Reverse_domain_name_notation),
/// e.g. "com.example.myapp". The plugin will create a directory with that name in the
/// appropriate filesystem location (depending on platform) for app settings. For platforms
/// without filesystems, other storage mechanisms will be used.
///
/// If you are do not have a domain name and cannot
/// afford one, use a reverse domain based on the URL of your repo (GitHub, GitLab, Codeberg
/// and so on).
///
/// Adding this plugin causes an immediate load of settings (from either the filesystem or
/// browser local storage, depending on platform).
///
/// When using this plugin, care must be taken to ensure that plugins execute in the proper order.
/// Loading settings causes registered settings to be inserted into the world as bevy resources.
/// You cannot access these values before they are loaded, but you may want to use the loaded values
/// when configuring other plugins. For this reason, it's generally a good idea to initialize and
/// load settings before other plugins. The settings plugin does not depend on any other
/// plugins.
///
/// In many cases, you may want to introduce additional "glue" plugins that copy setting
/// properties after they are loaded. For example, the
/// [`WindowPlugin`](https://docs.rs/bevy/latest/bevy/prelude/struct.WindowPlugin.html) plugin knows
/// nothing about settings, but if you want the window size and position to persist between runs
/// you can add an additional plugin which copies the window settings from the resource to the
/// actual window entity.
///
/// Saving of settings is not automatic; the recommended practice is to issue a
/// [`SaveSettingsDeferred`] command after modifying a settings resource. This will wait for
/// a short interval and then spawn an i/o task to write out the changed settings file. You can
/// also issue a [`SaveSettingsSync::IfChanged`] command immediately before exiting the app.
/// Note that on some platforms, depending on how the user exits (such as invoking Command-Q on
/// ``MacOS``) there may be no opportunity to intercept the app exit event, so the most reliable
/// approach is to use both techniques: deferred save and save-on-exit.
///
/// Saving is crash-resistant: if the app crashes in the middle of a save, the settings file
/// will not be corrupted (it writes to a temporary file first, then uses atomic operations to
/// replace the previous file).
pub struct SettingsPlugin {
    /// The unique name of the application.
    pub app_name: String,
}

impl SettingsPlugin {
    /// Construct a new `SettingsPlugin` for the given application name.
    pub fn new(app_name: &str) -> Self {
        Self {
            app_name: app_name.to_string(),
        }
    }
}

impl Plugin for SettingsPlugin {
    fn build(&self, app: &mut App) {
        let app_name = self.app_name.clone();
        let world = app.world();
        let last_save = world.read_change_tick();

        // Get the type registry and clone the Arc so we don't have to worry about borrowing.
        let Some(app_types) = world.get_resource::<AppTypeRegistry>() else {
            return;
        };
        let app_types = app_types.clone();
        let types = app_types.read();

        let world = app.world_mut();
        let file_index = build_settings_registry(&app_name, &types, last_save);

        // Now load each of the toml files we discovered, and apply their properties to
        // the resources in the world.
        for (filename, manifest) in file_index.files.iter() {
            load_settings_file(world, &app_name, filename, manifest, &types);
        }

        // Cache the index so that we don't have to do it again when saving (and also makes
        // saving more deterministic).
        drop(types);
        world.insert_resource::<SettingsFileRegistry>(file_index);

        app.add_systems(PostUpdate, handle_delayed_save);
    }
}

/// Trait which identifies a type as corresponding to a section with a settings file.
///
/// You can override the name of the section with `settings_group(group = "<name>")`.
/// For enum `SettingGroup`s, you can also override the name of its key with `settings_group(key = "<name>")`
/// The name should be in ``snake_case`` to be consistent with TOML style.
/// If there is a collision between names (multiple resources have the same name) then
/// the resulting properties will be merged into a single section.
///
/// You can also control which file the type gets saved to via
/// `settings_group(file = "<filename>")`. This should be the base name of the file without the
/// extension. The default name is `settings`, which will cause the settings to be written out
/// to `settings.toml` in the app's settings directory.
pub trait SettingsGroup: Resource {
    /// The name of the logical section within the settings file.
    fn settings_group_name() -> &'static str;

    /// The key name within the settings file.
    /// For structs, this should be set to `None`; The struct’s field names will be used as keys.
    /// For enums, the `SettingsGroup` will use this key name within the settings file for its sole key-value pair.
    /// This is typically the same as the group name, but can be customized.
    fn settings_key_name() -> Option<&'static str>;

    /// The name of the configuration file that contains this settings group.
    // TODO: Eventually convert this into an enum which represents various configuration sources.
    fn settings_source() -> Option<&'static str>;
}

/// Reflected data from a [`SettingsGroup`].
#[derive(Clone)]
pub struct ReflectSettingsGroup {
    /// The name of the logical section within the settings file.
    settings_group_name: &'static str,
    /// The key name within the settings file. Should only be `Some` for enums.
    settings_key_name: Option<&'static str>,
    /// The name of the settings file, defaults to "settings".
    settings_source: Option<&'static str>,
}

impl<T: SettingsGroup + FromReflect + TypePath> FromType<T> for ReflectSettingsGroup {
    fn from_type() -> Self {
        ReflectSettingsGroup {
            settings_group_name: T::settings_group_name(),
            settings_key_name: T::settings_key_name(),
            settings_source: T::settings_source(),
        }
    }

    fn insert_dependencies(type_registration: &mut TypeRegistration) {
        type_registration.register_type_data::<ReflectResource, T>();
    }
}

/// List of resource types that will be associated with a specific settings file.
/// Also tracks when that file was last written or read.
#[derive(Default)]
struct SettingsFileManifest {
    last_save: Tick,
    resource_types: Vec<TypeId>,
}

/// Records the game tick when settings were last loaded or saved. This is used to determine
/// which settings files have changed and need to be saved. Also tracks which settings files
/// are associated with which resource types.
#[derive(Resource)]
struct SettingsFileRegistry {
    /// App name (from plugin)
    app_name: String,

    /// List of known settings files, determined by scanning reflection registry.
    files: HashMap<&'static str, SettingsFileManifest>,

    /// Timer used for batched saving.
    save_timer: Timer,
}

/// A Command which saves settings to disk. This blocks the command queue until saving
/// is complete.
#[derive(Default, PartialEq)]
pub enum SaveSettingsSync {
    /// Save settings only if they have changed since the most recent load or save.
    #[default]
    IfChanged,
    /// Save settings unconditionally.
    Always,
}

impl Command for SaveSettingsSync {
    type Out = ();

    fn apply(self, world: &mut World) {
        save_settings(world, false, self == SaveSettingsSync::Always);
    }
}

/// A [`Command`] which saves settings to disk. Actual file system operations happen in another thread.
#[derive(Default, PartialEq)]
pub enum SaveSettings {
    /// Save settings only if they have changed since the most recent load or save.
    #[default]
    IfChanged,
    /// Save settings unconditionally.
    Always,
}

impl Command for SaveSettings {
    type Out = ();

    fn apply(self, world: &mut World) {
        save_settings(world, true, self == SaveSettings::Always);
    }
}

/// A Command which saves changed settings after a delay. This is debounced: issuing this
/// command multiple times resets the delay timer each time. This is meant to be used for settings
/// which change at a high frequency, such as dragging a slider which controls the game's audio
/// volume. The default delay is 1.0 seconds.
pub struct SaveSettingsDeferred(pub Duration);

impl Default for SaveSettingsDeferred {
    fn default() -> Self {
        Self(Duration::from_secs(1))
    }
}

impl Command for SaveSettingsDeferred {
    type Out = ();

    fn apply(self, world: &mut World) {
        let Some(mut registry) = world.get_resource_mut::<SettingsFileRegistry>() else {
            return;
        };

        registry.save_timer.set_duration(self.0);
        registry.save_timer.reset();
        registry.save_timer.unpause();
    }
}

fn save_settings(world: &mut World, use_async: bool, force: bool) {
    let this_run = world.change_tick();
    let Some(registry) = world.get_resource::<SettingsFileRegistry>() else {
        warn!("Settings registry not found - did you forget to install the SettingsPlugin?");
        return;
    };
    let Some(app_types) = world.get_resource::<AppTypeRegistry>() else {
        return;
    };
    let app_types = app_types.clone();
    let types = app_types.read();

    for (filename, manifest) in registry.files.iter() {
        if force || has_settings_changed(world, manifest) {
            let table = resources_to_toml(world, &types, manifest);
            let store = SettingsStore::new(&registry.app_name);
            if use_async {
                store.save_async(filename, table);
            } else {
                store.save(filename, table);
            }
        }
    }

    // Update timestamps
    let mut registry = world.get_resource_mut::<SettingsFileRegistry>().unwrap();
    for manifest in registry.files.values_mut() {
        manifest.last_save = this_run;
    }
}

fn has_settings_changed(world: &World, manifest: &SettingsFileManifest) -> bool {
    let this_run = world.read_change_tick();
    manifest.resource_types.iter().any(|r| {
        let Some(component_id) = world.components().get_id(*r) else {
            return false;
        };
        if let Some(resource_change) = world.get_resource_change_ticks_by_id(component_id) {
            return resource_change.is_changed(manifest.last_save, this_run);
        }
        false
    })
}

fn resources_to_toml(
    world: &World,
    types: &TypeRegistry,
    manifest: &SettingsFileManifest,
) -> toml::map::Map<String, toml::Value> {
    let mut table = toml::Table::new();

    for tid in manifest.resource_types.iter() {
        let ty = types.get(*tid).unwrap();

        let Some(cmp) = ty.data::<ReflectComponent>() else {
            continue;
        };

        let Some(reflect_settings_group) = ty.data::<ReflectSettingsGroup>() else {
            continue;
        };

        let settings_group = reflect_settings_group.settings_group_name;
        let settings_key = reflect_settings_group.settings_key_name;

        let Some(component_id) = world.components().get_id(*tid) else {
            continue;
        };

        let Some(res_entity) = world.resource_entities().get(component_id) else {
            continue;
        };
        let res_entity_ref = world.entity(res_entity);
        let Some(reflect) = cmp.reflect(res_entity_ref) else {
            continue;
        };

        let serializer = TypedReflectSerializer::new(reflect.as_partial_reflect(), types);

        let toml_value = if let Some(settings_key) = settings_key {
            // convert toml value into a key value pair if settings_key is set. settings_key is only set for enums
            toml::Value::Table(toml::Table::from_iter([(
                settings_key.to_string(),
                toml::Value::try_from(serializer).unwrap(),
            )]))
        } else {
            // Otherwise, the whole struct is serialized into toml
            toml::Value::try_from(serializer).unwrap()
        };

        match (
            toml_value.as_table(),
            table
                .get_mut(settings_group)
                .and_then(|value| value.as_table_mut()),
        ) {
            (Some(from), Some(to)) => {
                // Merge the tables
                for (key, value) in from.iter() {
                    to.insert(key.clone(), value.clone());
                }
            }
            _ => {
                table.insert(settings_group.to_string(), toml_value);
            }
        };
    }

    table
}

/// Builds the settings file registry by scanning the type registry for settings resources.
/// This is separated from loading to enable testing without file I/O.
///
/// Returns the [`SettingsFileRegistry`] that tracks which resources are associated with
/// which settings files.
fn build_settings_registry(
    app_name: &str,
    types: &TypeRegistry,
    last_save: Tick,
) -> SettingsFileRegistry {
    // Build an index that remembers all of the resource types that are to be saved to
    // each individual settings file.
    let mut file_index = SettingsFileRegistry {
        app_name: app_name.to_string(),
        files: HashMap::new(),
        save_timer: Timer::new(Duration::from_secs(1), TimerMode::Once),
    };
    file_index.save_timer.pause(); // Ensure timer is initially paused

    // Scan through types looking for resources that have the necessary traits and
    // annotations.
    for ty in types.iter() {
        if !ty.contains::<ReflectDefault>() {
            continue;
        };

        let Some(reflect_group) = ty.data::<ReflectSettingsGroup>() else {
            continue;
        };

        // If no filename is specified, use "settings"
        let filename = reflect_group.settings_source.unwrap_or("settings");
        let pending_file = file_index
            .files
            .entry(filename)
            .or_insert(SettingsFileManifest {
                last_save,
                resource_types: Vec::new(),
            });
        pending_file.last_save = last_save;
        pending_file.resource_types.push(ty.type_id());
    }

    file_index
}

/// Loads a single settings file and applies its values to the world's resources.
fn load_settings_file(
    world: &mut World,
    app_name: &str,
    filename: &str,
    manifest: &SettingsFileManifest,
    types: &TypeRegistry,
) {
    // Load the TOML file
    let store = SettingsStore::new(app_name);
    let toml = store.load(filename);
    if toml.is_none() {
        warn!("Filename {filename}.toml not found");
    }

    apply_settings_to_world(world, toml.as_ref(), manifest, types);
}

/// Applies settings from a TOML table to the world's resources.
/// This is separated from file loading to enable testing without filesystem access.
///
/// For each resource type in the manifest, this function either:
/// - Updates an existing resource with values from the TOML, or
/// - Creates a new resource with default values merged with TOML values
fn apply_settings_to_world(
    world: &mut World,
    toml: Option<&toml::Table>,
    manifest: &SettingsFileManifest,
    types: &TypeRegistry,
) {
    for tid in manifest.resource_types.iter() {
        let ty = types.get(*tid).unwrap();
        let Some(reflect_settings_group) = ty.data::<ReflectSettingsGroup>() else {
            continue;
        };

        let settings_group = reflect_settings_group.settings_group_name;
        let settings_key = reflect_settings_group.settings_key_name;

        let reflect_component = ty.data::<ReflectComponent>().unwrap();
        let component_id = world.components().get_id(*tid);
        let res_entity = component_id.and_then(|cid| world.resource_entities().get(cid));

        if let Some(res_entity) = res_entity {
            // Resource already exists, so apply toml properties to it.
            let res_entity_mut = world.entity_mut(res_entity);
            let Some(mut reflect) = reflect_component.reflect_mut(res_entity_mut) else {
                continue;
            };

            if let Some(toml) = toml
                && let Some(value) = toml.get(settings_group)
            {
                let value = if let Some(settings_key) = settings_key {
                    // If there is a settings key, then we need to look one level deeper in the TOML
                    // to find the actual properties to apply to the resource.
                    value.get(settings_key).unwrap_or(value)
                } else {
                    // No settings key, so we can apply the whole section to the resource
                    value
                };

                load_properties(value, &mut *reflect, types);
            }
        } else {
            // The resource does not exist, so create a default.
            let reflect_default = ty.data::<ReflectDefault>().unwrap();
            let mut default_value = reflect_default.default();
            let mut res_entity = world.spawn_empty();

            if let Some(toml) = toml
                && let Some(value) = toml.get(settings_group)
            {
                let value = if let Some(settings_key) = settings_key {
                    // If there is a settings key, then we need to look one level deeper in the TOML
                    // to find the actual properties to apply to the resource.
                    value.get(settings_key).unwrap_or(value)
                } else {
                    // No settings key, so we can apply the whole section to the resource
                    value
                };

                load_properties(value, &mut *default_value, types);
            }

            // Now add the new resource to the world.
            reflect_component.insert(&mut res_entity, default_value.as_partial_reflect(), types);
        }
    }
}

fn load_properties(value: &toml::Value, resource: &mut dyn PartialReflect, types: &TypeRegistry) {
    let Some(tinfo) = resource.get_represented_type_info() else {
        return;
    };

    match tinfo {
        TypeInfo::Struct(stinfo) => {
            if let Some(table) = value.as_table()
                && let ReflectMut::Struct(st_reflect) = resource.reflect_mut()
            {
                // Deserialize matching field names, ignore ones that don't match.
                for (idx, field) in stinfo.field_names().iter().enumerate() {
                    if let Some(toml_field_value) = table.get(*field)
                        && let Some(field_info) = stinfo.field_at(idx)
                        && let Some(field_type) = types.get(field_info.type_id())
                    {
                        let deserializer = TypedReflectDeserializer::new(field_type, types);
                        if let Ok(field_value) = deserializer.deserialize(toml_field_value.clone())
                        {
                            // Should be safe to unwrap here since we know the field exists (above).
                            st_reflect.field_at_mut(idx).unwrap().apply(&*field_value);
                        }
                    }
                }
            }
        }
        TypeInfo::TupleStruct(tstinfo) => {
            if let ReflectMut::TupleStruct(tst_reflect) = resource.reflect_mut() {
                // tuple structs with length > 1 are always serialized as arrays
                if tst_reflect.field_len() > 1
                    && let Some(array) = value.as_array()
                {
                    for (idx, toml_field_value) in array.iter().enumerate() {
                        if let Some(field_info) = tstinfo.field_at(idx)
                            && let Some(field_type) = types.get(field_info.type_id())
                        {
                            let deserializer = TypedReflectDeserializer::new(field_type, types);
                            if let Ok(field_value) =
                                deserializer.deserialize(toml_field_value.clone())
                            {
                                // Should be safe to unwrap here since we know the field exists (above).
                                tst_reflect.field_mut(idx).unwrap().apply(&*field_value);
                            }
                        }
                    }
                } else if tst_reflect.field_len() == 1
                    && let Some(field_info) = tstinfo.field_at(0)
                    && let Some(field_type) = types.get(field_info.type_id())
                {
                    let deserializer = TypedReflectDeserializer::new(field_type, types);
                    if let Ok(field_value) = deserializer.deserialize(value.clone()) {
                        // Should be safe to unwrap here since we know the field exists (above).
                        tst_reflect.field_mut(0).unwrap().apply(&*field_value);
                    }
                }
            }
        }
        TypeInfo::Enum(einfo) => {
            if let ReflectMut::Enum(en_reflect) = resource.reflect_mut()
                && let Some(variant_type) = types.get(einfo.type_id())
            {
                let deserializer = TypedReflectDeserializer::new(variant_type, types);

                if let Ok(variant_value) = deserializer.deserialize(value.clone()) {
                    en_reflect.apply(&*variant_value);
                }
            }
        }
        _ => {}
    }
}

fn handle_delayed_save(
    mut settings: ResMut<SettingsFileRegistry>,
    time: Res<Time>,
    mut commands: Commands,
) {
    settings.save_timer.tick(time.delta());
    if settings.save_timer.just_finished() {
        commands.queue(SaveSettings::IfChanged);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bevy_ecs::change_detection::Tick;
    use bevy_reflect::Reflect;
    // Required to make proc macros work in bevy itself.
    extern crate self as bevy_settings;

    /// Test resource that uses default settings group name (derived from type name)
    #[derive(Resource, SettingsGroup, Reflect, Default)]
    #[reflect(Resource, SettingsGroup, Default)]
    struct CounterSettings {
        count: i32,
    }

    /// Test resource that shares the same settings group name as another resource
    #[derive(Resource, SettingsGroup, Reflect, Default)]
    #[reflect(Resource, SettingsGroup, Default)]
    #[settings_group(group = "counter_settings")]
    struct ExtraCounterSettings {
        enabled: bool,
    }

    #[derive(Resource, SettingsGroup, Reflect, Debug, Default, PartialEq)]
    #[reflect(Resource, SettingsGroup, Default)]
    #[settings_group(group = "counter_settings", key = "refresh_rate")]
    enum CounterRefreshRateSettings {
        #[default]
        Slow,
        Fast,
    }

    /// Test resource that uses a different settings file
    #[derive(Resource, SettingsGroup, Reflect, Default)]
    #[reflect(Resource, SettingsGroup, Default)]
    #[settings_group(file = "audio")]
    struct AudioSettings {
        volume: f32,
    }

    #[test]
    fn test_build_registry_single_struct_resource() {
        let mut types = TypeRegistry::default();
        types.register::<CounterSettings>();

        let registry = build_settings_registry("test_app", &types, Tick::new(0));

        assert_eq!(registry.app_name, "test_app");
        assert_eq!(registry.files.len(), 1);
        assert!(registry.files.contains_key("settings"));

        let manifest = registry.files.get("settings").unwrap();
        assert_eq!(manifest.resource_types.len(), 1);
    }

    #[test]
    fn test_build_registry_single_enum_resource() {
        let mut types = TypeRegistry::default();
        types.register::<CounterRefreshRateSettings>();

        let registry = build_settings_registry("test_app", &types, Tick::new(0));

        assert_eq!(registry.app_name, "test_app");
        assert_eq!(registry.files.len(), 1);
        assert!(registry.files.contains_key("settings"));

        let manifest = registry.files.get("settings").unwrap();
        assert_eq!(manifest.resource_types.len(), 1);
    }

    #[test]
    fn test_build_registry_merged_groups() {
        let mut types = TypeRegistry::default();
        types.register::<CounterSettings>();
        types.register::<ExtraCounterSettings>();

        let registry = build_settings_registry("test_app", &types, Tick::new(0));

        // Both resources should be in the same file
        assert_eq!(registry.files.len(), 1);
        assert!(registry.files.contains_key("settings"));

        let manifest = registry.files.get("settings").unwrap();
        // Both resources should be tracked
        assert_eq!(manifest.resource_types.len(), 2);
    }

    #[test]
    fn test_build_registry_separate_files() {
        let mut types = TypeRegistry::default();
        types.register::<CounterSettings>();
        types.register::<AudioSettings>();

        let registry = build_settings_registry("test_app", &types, Tick::new(0));

        // Resources should be in different files
        assert_eq!(registry.files.len(), 2);
        assert!(registry.files.contains_key("settings"));
        assert!(registry.files.contains_key("audio"));

        let settings_manifest = registry.files.get("settings").unwrap();
        assert_eq!(settings_manifest.resource_types.len(), 1);

        let audio_manifest = registry.files.get("audio").unwrap();
        assert_eq!(audio_manifest.resource_types.len(), 1);
    }

    #[test]
    fn test_resources_to_toml_merges_same_group() {
        let mut world = World::new();
        let mut types = TypeRegistry::default();
        types.register::<CounterSettings>();
        types.register::<ExtraCounterSettings>();
        types.register::<CounterRefreshRateSettings>();

        // Insert both resources
        world.insert_resource(CounterSettings { count: 42 });
        world.insert_resource(ExtraCounterSettings { enabled: true });
        world.insert_resource(CounterRefreshRateSettings::Fast);

        // Build a manifest with both resource types
        let manifest = SettingsFileManifest {
            last_save: Tick::new(0),
            resource_types: vec![
                TypeId::of::<CounterSettings>(),
                TypeId::of::<ExtraCounterSettings>(),
                TypeId::of::<CounterRefreshRateSettings>(),
            ],
        };

        let table = resources_to_toml(&world, &types, &manifest);

        // Both resources should be merged into the same "counter_settings" section
        assert!(table.contains_key("counter_settings"));
        let counter_section = table.get("counter_settings").unwrap().as_table().unwrap();

        // Check that fields are present in the merged section
        assert_eq!(
            counter_section.get("count").unwrap().as_integer().unwrap(),
            42
        );
        assert!(counter_section.get("enabled").unwrap().as_bool().unwrap());
        assert_eq!(
            counter_section
                .get("refresh_rate")
                .unwrap()
                .as_str()
                .unwrap(),
            "Fast"
        );
    }

    #[test]
    fn test_round_trip_serialization() {
        #[derive(Resource, SettingsGroup, Reflect, PartialEq, Debug, Default)]
        #[reflect(Resource, SettingsGroup, Default)]
        struct SingleFieldTupleStruct(u8);

        #[derive(Reflect, PartialEq, Debug, Default)]
        #[reflect(Default)]
        struct NestedStruct {
            a: u8,
            b: u16,
        }

        #[derive(Resource, SettingsGroup, Reflect, PartialEq, Debug, Default)]
        #[reflect(Resource, SettingsGroup, Default)]
        struct MultiFieldTupleStruct(u8, NestedStruct);

        #[derive(Resource, SettingsGroup, Reflect, Default)]
        #[reflect(Resource, SettingsGroup, Default)]
        struct NewTypeSingleTupleStruct(SingleFieldTupleStruct);

        #[derive(Resource, SettingsGroup, Reflect, Default)]
        #[reflect(Resource, SettingsGroup, Default)]
        struct NewTypeMultiTupleStruct(SingleFieldTupleStruct, MultiFieldTupleStruct);

        #[derive(Resource, SettingsGroup, Reflect, PartialEq, Debug, Default)]
        #[reflect(Resource, SettingsGroup, Default)]
        enum EnumUnitVariant {
            #[default]
            A,
        }

        #[derive(Resource, SettingsGroup, Reflect, PartialEq, Debug)]
        #[reflect(Resource, SettingsGroup, Default)]
        enum EnumSingleTupleVariant {
            A(u8),
        }

        impl Default for EnumSingleTupleVariant {
            fn default() -> Self {
                EnumSingleTupleVariant::A(0)
            }
        }

        #[derive(Resource, SettingsGroup, Reflect, PartialEq, Debug)]
        #[reflect(Resource, SettingsGroup, Default)]
        enum EnumMultiTupleVariant {
            A(u16, u32),
        }

        impl Default for EnumMultiTupleVariant {
            fn default() -> Self {
                EnumMultiTupleVariant::A(0, 0)
            }
        }

        #[derive(Resource, SettingsGroup, Reflect, PartialEq, Debug)]
        #[reflect(Resource, SettingsGroup, Default)]
        enum EnumStructVariant {
            A { x: u8, y: u16 },
        }

        impl Default for EnumStructVariant {
            fn default() -> Self {
                EnumStructVariant::A { x: 0, y: 0 }
            }
        }

        #[derive(Resource, SettingsGroup, Reflect, PartialEq, Debug)]
        #[reflect(Resource, SettingsGroup, Default)]
        enum EnumSingleNewTypeVariant {
            A(SingleFieldTupleStruct),
        }

        impl Default for EnumSingleNewTypeVariant {
            fn default() -> Self {
                EnumSingleNewTypeVariant::A(SingleFieldTupleStruct(0))
            }
        }

        #[derive(Resource, SettingsGroup, Reflect, PartialEq, Debug)]
        #[reflect(Resource, SettingsGroup, Default)]
        enum EnumMultiNewTypeVariant {
            A(SingleFieldTupleStruct, MultiFieldTupleStruct),
        }

        impl Default for EnumMultiNewTypeVariant {
            fn default() -> Self {
                EnumMultiNewTypeVariant::A(
                    SingleFieldTupleStruct(0),
                    MultiFieldTupleStruct(0, NestedStruct { a: 0, b: 0 }),
                )
            }
        }

        let mut world = World::new();
        let mut types = TypeRegistry::default();

        types.register::<CounterSettings>();
        types.register::<ExtraCounterSettings>();
        types.register::<CounterRefreshRateSettings>();
        types.register::<SingleFieldTupleStruct>();
        types.register::<MultiFieldTupleStruct>();
        types.register::<NewTypeSingleTupleStruct>();
        types.register::<NewTypeMultiTupleStruct>();
        types.register::<EnumUnitVariant>();
        types.register::<EnumSingleTupleVariant>();
        types.register::<EnumMultiTupleVariant>();
        types.register::<EnumStructVariant>();
        types.register::<EnumSingleNewTypeVariant>();
        types.register::<EnumMultiNewTypeVariant>();

        // Insert resources with specific values
        world.insert_resource(CounterSettings { count: 123 });
        world.insert_resource(ExtraCounterSettings { enabled: false });
        world.insert_resource(CounterRefreshRateSettings::Fast);
        world.insert_resource(SingleFieldTupleStruct(1));
        world.insert_resource(MultiFieldTupleStruct(2, NestedStruct { a: 1, b: 2 }));
        world.insert_resource(NewTypeSingleTupleStruct(SingleFieldTupleStruct(1)));
        world.insert_resource(NewTypeMultiTupleStruct(
            SingleFieldTupleStruct(1),
            MultiFieldTupleStruct(2, NestedStruct { a: 1, b: 2 }),
        ));
        world.insert_resource(EnumUnitVariant::A);
        world.insert_resource(EnumSingleTupleVariant::A(1));
        world.insert_resource(EnumMultiTupleVariant::A(1, 2));
        world.insert_resource(EnumStructVariant::A { x: 1, y: 2 });
        world.insert_resource(EnumSingleNewTypeVariant::A(SingleFieldTupleStruct(1)));
        world.insert_resource(EnumMultiNewTypeVariant::A(
            SingleFieldTupleStruct(1),
            MultiFieldTupleStruct(2, NestedStruct { a: 1, b: 2 }),
        ));

        // Build a manifest with both resource types
        let manifest = SettingsFileManifest {
            last_save: Tick::new(0),
            resource_types: vec![
                TypeId::of::<CounterSettings>(),
                TypeId::of::<ExtraCounterSettings>(),
                TypeId::of::<CounterRefreshRateSettings>(),
                TypeId::of::<SingleFieldTupleStruct>(),
                TypeId::of::<MultiFieldTupleStruct>(),
                TypeId::of::<NewTypeSingleTupleStruct>(),
                TypeId::of::<NewTypeMultiTupleStruct>(),
                TypeId::of::<EnumUnitVariant>(),
                TypeId::of::<EnumSingleTupleVariant>(),
                TypeId::of::<EnumMultiTupleVariant>(),
                TypeId::of::<EnumStructVariant>(),
                TypeId::of::<EnumSingleNewTypeVariant>(),
                TypeId::of::<EnumMultiNewTypeVariant>(),
            ],
        };

        // Serialize to TOML
        let table = resources_to_toml(&world, &types, &manifest);

        // Create a new world and apply the TOML
        let mut new_world = World::new();
        apply_settings_to_world(&mut new_world, Some(&table), &manifest, &types);

        // Verify resources were created with correct values
        let counter = new_world.get_resource::<CounterSettings>().unwrap();
        assert_eq!(counter.count, 123);

        let extra = new_world.get_resource::<ExtraCounterSettings>().unwrap();
        assert!(!extra.enabled);

        let refresh_rate = new_world
            .get_resource::<CounterRefreshRateSettings>()
            .unwrap();
        assert_eq!(*refresh_rate, CounterRefreshRateSettings::Fast);

        let single_field_tuple_struct = new_world.get_resource::<SingleFieldTupleStruct>().unwrap();
        assert_eq!(single_field_tuple_struct.0, 1);

        let multi_field_tuple_struct = new_world.get_resource::<MultiFieldTupleStruct>().unwrap();
        assert_eq!(multi_field_tuple_struct.0, 2);
        assert_eq!(multi_field_tuple_struct.1.a, 1);
        assert_eq!(multi_field_tuple_struct.1.b, 2);

        let new_type_single_tuple_struct = new_world
            .get_resource::<NewTypeSingleTupleStruct>()
            .unwrap();
        assert_eq!(new_type_single_tuple_struct.0 .0, 1);

        let new_type_multi_tuple_struct =
            new_world.get_resource::<NewTypeMultiTupleStruct>().unwrap();
        assert_eq!(new_type_multi_tuple_struct.0 .0, 1);
        assert_eq!(new_type_multi_tuple_struct.1 .0, 2);
        assert_eq!(new_type_multi_tuple_struct.1 .1.a, 1);
        assert_eq!(new_type_multi_tuple_struct.1 .1.b, 2);

        let enum_unit_variant = new_world.get_resource::<EnumUnitVariant>().unwrap();
        assert_eq!(*enum_unit_variant, EnumUnitVariant::A);

        let enum_single_tuple_variant = new_world.get_resource::<EnumSingleTupleVariant>().unwrap();
        assert_eq!(*enum_single_tuple_variant, EnumSingleTupleVariant::A(1));

        let enum_multi_tuple_variant = new_world.get_resource::<EnumMultiTupleVariant>().unwrap();
        assert_eq!(*enum_multi_tuple_variant, EnumMultiTupleVariant::A(1, 2));

        let enum_struct_variant = new_world.get_resource::<EnumStructVariant>().unwrap();
        assert_eq!(*enum_struct_variant, EnumStructVariant::A { x: 1, y: 2 });

        let enum_single_new_type_variant = new_world
            .get_resource::<EnumSingleNewTypeVariant>()
            .unwrap();
        assert_eq!(
            *enum_single_new_type_variant,
            EnumSingleNewTypeVariant::A(SingleFieldTupleStruct(1))
        );

        let enum_multi_new_type_variant =
            new_world.get_resource::<EnumMultiNewTypeVariant>().unwrap();
        assert_eq!(
            *enum_multi_new_type_variant,
            EnumMultiNewTypeVariant::A(
                SingleFieldTupleStruct(1),
                MultiFieldTupleStruct(2, NestedStruct { a: 1, b: 2 })
            )
        );
    }

    #[test]
    fn test_round_trip_with_existing_resources() {
        let mut world = World::new();
        let mut types = TypeRegistry::default();
        types.register::<CounterSettings>();
        types.register::<CounterRefreshRateSettings>();

        // Insert resource with initial values
        world.insert_resource(CounterSettings { count: 100 });
        world.insert_resource(CounterRefreshRateSettings::Fast);

        let manifest = SettingsFileManifest {
            last_save: Tick::new(0),
            resource_types: vec![
                TypeId::of::<CounterSettings>(),
                TypeId::of::<CounterRefreshRateSettings>(),
            ],
        };

        // Serialize
        let table = resources_to_toml(&world, &types, &manifest);

        // Modify the resource
        world.resource_mut::<CounterSettings>().count = 999;
        *world.resource_mut::<CounterRefreshRateSettings>() = CounterRefreshRateSettings::Slow;

        // Apply TOML (should restore the original value)
        apply_settings_to_world(&mut world, Some(&table), &manifest, &types);

        let counter = world.get_resource::<CounterSettings>().unwrap();
        assert_eq!(counter.count, 100);
        let refresh_rate = world.get_resource::<CounterRefreshRateSettings>().unwrap();
        assert_eq!(*refresh_rate, CounterRefreshRateSettings::Fast);
    }

    #[test]
    fn test_partial_toml_preserves_missing_fields() {
        let mut world = World::new();
        let mut types = TypeRegistry::default();
        types.register::<CounterSettings>();
        types.register::<ExtraCounterSettings>();
        types.register::<CounterRefreshRateSettings>();

        // Insert resources with specific values
        world.insert_resource(CounterSettings { count: 50 });
        world.insert_resource(ExtraCounterSettings { enabled: true });
        world.insert_resource(CounterRefreshRateSettings::Fast);

        // Create a TOML table that only contains one field from one resource
        let mut table = toml::Table::new();
        let mut counter_section = toml::Table::new();
        counter_section.insert("count".to_string(), toml::Value::Integer(999));
        table.insert(
            "counter_settings".to_string(),
            toml::Value::Table(counter_section),
        );
        // Note: "enabled" field is missing from the TOML

        let manifest = SettingsFileManifest {
            last_save: Tick::new(0),
            resource_types: vec![
                TypeId::of::<CounterSettings>(),
                TypeId::of::<ExtraCounterSettings>(),
                TypeId::of::<CounterRefreshRateSettings>(),
            ],
        };

        // Apply the partial TOML
        apply_settings_to_world(&mut world, Some(&table), &manifest, &types);

        // Verify count was updated
        let counter = world.get_resource::<CounterSettings>().unwrap();
        assert_eq!(counter.count, 999);

        // Verify enabled was preserved (not overwritten with default false)
        let extra = world.get_resource::<ExtraCounterSettings>().unwrap();
        assert!(extra.enabled);

        // Verify refresh_rate was preserved
        let refresh_rate = world.get_resource::<CounterRefreshRateSettings>().unwrap();
        assert_eq!(*refresh_rate, CounterRefreshRateSettings::Fast);
    }
}