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
extern crate directories;

use std::{fmt::Debug, marker::PhantomData, path::PathBuf};

use directories::ProjectDirs;

use bevy_app::{App, Plugin, Update};
use bevy_ecs::{
    prelude::{Event, EventReader, Resource},
    system::Res,
};
use bevy_log::prelude::debug;

pub extern crate serde;
pub use serde::{Deserialize, Serialize};

/// this is a blanked trait
pub trait Settingable: Resource + Clone + Serialize + Default + for<'a> Deserialize<'a> {}

/// this is a blanked implementation of [`Settingable`]
impl<S> Settingable for S where S: Resource + Clone + Serialize + Default + for<'a> Deserialize<'a> {}

/// This will persist all structs that
/// are added via the Plugin [`SettingsPlugin`]
#[derive(Event)]
pub struct PersistSettings;

/// This will persist structs S that
/// was added via the Plugin [`SettingsPlugin`]
#[derive(Event, Default)]
pub struct PersistSetting<S: Settingable>(PhantomData<S>);

pub struct SettingsPlugin<S: Settingable> {
    domain: String,
    company: String,
    project: String,
    settings: PhantomData<S>,
}

#[derive(Resource, Debug)]
pub struct SettingsConfig<S: Settingable> {
    directory: PathBuf,
    path: PathBuf,
    settings: PhantomData<S>,
}

impl<S: Settingable> SettingsPlugin<S> {
    pub fn new(company: impl Into<String>, project: impl Into<String>) -> Self {
        Self {
            domain: "com".into(),
            company: company.into(),
            project: project.into(),
            settings: PhantomData::<S>,
        }
    }

    pub fn resource(&self) -> S {
        self.load().unwrap_or_default()
    }

    fn load(&self) -> Option<S> {
        let path = self.path();
        if !path.exists() {
            return None;
        }
        let settings_string = std::fs::read_to_string(path).ok()?;
        toml::from_str(&settings_string).ok()
    }

    fn path(&self) -> PathBuf {
        ProjectDirs::from(&self.domain, &self.company, &self.project)
            .expect("Couldn't build settings path")
            .config_dir()
            .join(format!("{}.toml", self.project))
    }

    fn settings_directory(&self) -> PathBuf {
        ProjectDirs::from(&self.domain, &self.company, &self.project)
            .expect("Couldn't find a folder to store the settings")
            .config_dir()
            .to_path_buf()
    }

    fn persist(
        settings: Res<S>,
        config: Res<SettingsConfig<S>>,
        reader_single: EventReader<PersistSetting<S>>,
        reader_all: EventReader<PersistSettings>,
    ) {
        debug!("System persist called");
        if !reader_single.is_empty() || !reader_all.is_empty() {
            std::fs::create_dir_all(config.directory.clone())
                .expect("Couldn't create the folders for the settings file");
            std::fs::write(
                config.path.clone(),
                toml::to_string(&*settings).expect("Couldn't serialize the settings to toml"),
            )
            .expect("couldn't persist the settings while trying to write the string to disk");
        }
    }
}

impl<S: Settingable> Plugin for SettingsPlugin<S> {
    fn build(&self, app: &mut App) {
        app.insert_resource(self.resource())
            .insert_resource(SettingsConfig {
                directory: self.settings_directory(),
                path: self.path(),
                settings: PhantomData::<S>,
            })
            .add_event::<PersistSettings>()
            .add_event::<PersistSetting<S>>()
            .add_systems(Update, SettingsPlugin::<S>::persist);
    }
}

#[cfg(test)]
mod tests {
    use super::{PersistSettings, SettingsPlugin};
    use bevy::prelude::*;
    use pretty_assertions::{assert_eq, assert_ne};

    use crate::PersistSetting;
    pub use crate::{Deserialize, Serialize};

    #[derive(Resource, Default, Serialize, Deserialize, Clone)]
    struct TestSetting1 {
        test: u32,
    }

    #[derive(Resource, Default, Serialize, Deserialize, Clone)]
    struct TestSetting2 {
        test: u32,
    }

    #[test]
    fn it_should_store_multiple_settings() {
        let mut app1 = App::new();
        let u32_1: u32 = rand::random::<u32>();
        let u32_2: u32 = rand::random::<u32>();
        app1.add_plugins(SettingsPlugin::<TestSetting1>::new(
            "Bevy Settings Test Corp",
            "Some Game File 1",
        ));
        app1.add_plugins(SettingsPlugin::<TestSetting2>::new(
            "Bevy Settings Test Corp",
            "Some Game File 2",
        ));
        app1.add_systems(
            Update,
            move |mut writer: EventWriter<PersistSettings>,
                  mut test_setting_1: ResMut<TestSetting1>,
                  mut test_setting_2: ResMut<TestSetting2>| {
                *test_setting_1 = TestSetting1 { test: u32_1 };
                *test_setting_2 = TestSetting2 { test: u32_2 };
                writer.send(PersistSettings);
            },
        );
        app1.update(); // send event
        app1.update(); // react to persist

        let mut app2 = App::new();
        app2.add_plugins(SettingsPlugin::<TestSetting1>::new(
            "Bevy Settings Test Corp",
            "Some Game File 1",
        ));
        app2.add_plugins(SettingsPlugin::<TestSetting2>::new(
            "Bevy Settings Test Corp",
            "Some Game File 2",
        ));
        app2.update();
        let test_setting_1 = app2.world.resource::<TestSetting1>();
        assert_eq!(test_setting_1.test, u32_1);
        let test_setting_2 = app2.world.resource::<TestSetting2>();
        assert_eq!(test_setting_2.test, u32_2);
    }

    #[test]
    fn it_should_store_singular_settings() {
        let mut app1 = App::new();
        let u32_1: u32 = rand::random::<u32>();
        let u32_2: u32 = rand::random::<u32>();
        app1.add_plugins(SettingsPlugin::<TestSetting1>::new(
            "Bevy Settings Test Corp",
            "Some Game File 1",
        ));
        app1.add_plugins(SettingsPlugin::<TestSetting2>::new(
            "Bevy Settings Test Corp",
            "Some Game File 2",
        ));
        app1.add_systems(
            Update,
            move |mut writer: EventWriter<PersistSetting<TestSetting1>>,
                  mut test_setting_1: ResMut<TestSetting1>,
                  mut test_setting_2: ResMut<TestSetting2>| {
                *test_setting_1 = TestSetting1 { test: u32_1 };
                *test_setting_2 = TestSetting2 { test: u32_2 };
                writer.send(PersistSetting::default());
            },
        );
        app1.update(); // send event
        app1.update(); // react to persist

        let mut app2 = App::new();
        app2.add_plugins(SettingsPlugin::<TestSetting1>::new(
            "Bevy Settings Test Corp",
            "Some Game File 1",
        ));
        app2.add_plugins(SettingsPlugin::<TestSetting2>::new(
            "Bevy Settings Test Corp",
            "Some Game File 2",
        ));
        app2.update();
        let test_setting_1 = app2.world.resource::<TestSetting1>();
        assert_eq!(test_setting_1.test, u32_1);
        let test_setting_2 = app2.world.resource::<TestSetting2>();
        assert_ne!(test_setting_2.test, u32_2);
    }
}