Skip to main content

sim_app/
settings.rs

1//! What the window remembers between starts: the language, the theme, the unit switches, the speed, and the config
2//! or machine file last opened with the machine picked. A small TOML file in the user's config folder, or where
3//! `SIM_APP_SETTINGS` points. Nothing here reads the environment or the disk of its own accord, so that the tests
4//! and the developer hooks can keep clear of the user's file (`path`).
5
6use crate::model::Message;
7use std::path::{Path, PathBuf};
8
9/// The file's layout; a file of another one is ignored, not guessed at.
10const VERSION: i64 = 1;
11
12/// The values kept; `None` where the file has none (a first start), so that the default shows.
13#[derive(Debug, Clone, Default, PartialEq)]
14pub struct Settings {
15    pub lang: Option<String>,
16    pub light: Option<bool>,
17    pub rpm: Option<bool>,
18    pub mm: Option<bool>,
19    pub speed: Option<f64>,
20    /// The config or machine file last opened or saved, and the id of the machine that was shown.
21    pub config_file: Option<String>,
22    pub machine: Option<String>,
23}
24
25impl Settings {
26    /// The settings in `text`; a text that is no TOML, or of another version of the file, is refused.
27    pub fn parse(text: &str) -> Result<Self, Message> {
28        let table = text.parse::<toml::Table>().map_err(|e| ("ui-settings-ignored", e.message().to_string()))?;
29        if table.get("version").and_then(toml::Value::as_integer) != Some(VERSION) {
30            return Err(("ui-settings-outdated", String::new()));
31        }
32        let text = |key: &str| table.get(key).and_then(toml::Value::as_str).map(str::to_string);
33        let flag = |key: &str| table.get(key).and_then(toml::Value::as_bool);
34        Ok(Self {
35            lang: text("language"),
36            light: flag("light"),
37            rpm: flag("rpm"),
38            mm: flag("mm"),
39            speed: table.get("speed").and_then(toml::Value::as_float).filter(|s| s.is_finite() && *s > 0.0),
40            config_file: text("config_file").filter(|f| !f.is_empty()),
41            machine: text("machine"),
42        })
43    }
44
45    pub fn to_text(&self) -> String {
46        let mut table = toml::Table::new();
47        table.insert("version".into(), VERSION.into());
48        let strings = [("language", &self.lang), ("config_file", &self.config_file), ("machine", &self.machine)];
49        for (key, value) in strings {
50            if let Some(value) = value {
51                table.insert(key.into(), value.clone().into());
52            }
53        }
54        for (key, value) in [("light", self.light), ("rpm", self.rpm), ("mm", self.mm)] {
55            if let Some(value) = value {
56                table.insert(key.into(), value.into());
57            }
58        }
59        if let Some(speed) = self.speed {
60            table.insert("speed".into(), speed.into());
61        }
62        table.to_string()
63    }
64}
65
66/// The file the settings are kept in, from the environment `env` (a lookup by name): `SIM_APP_SETTINGS` where set;
67/// else none while the screenshot hook runs or in a test, which must not read or write the user's file; else the app's
68/// folder in the user's config folder (`APPDATA` on Windows, `XDG_CONFIG_HOME` or `~/.config` elsewhere,
69/// `~/Library/Application Support` on macOS). `None` where the environment names no such folder.
70pub fn path(env: impl Fn(&str) -> Option<String>) -> Option<PathBuf> {
71    if let Some(file) = env("SIM_APP_SETTINGS").filter(|f| !f.is_empty()) {
72        return Some(file.into());
73    }
74    if cfg!(test) || env("SIM_APP_SCREENSHOT").is_some() {
75        return None;
76    }
77    let home = || env("HOME").filter(|h| !h.is_empty()).map(PathBuf::from);
78    let folder = if cfg!(windows) {
79        env("APPDATA").filter(|a| !a.is_empty()).map(PathBuf::from)
80    } else if cfg!(target_os = "macos") {
81        home().map(|h| h.join("Library").join("Application Support"))
82    } else {
83        env("XDG_CONFIG_HOME")
84            .filter(|x| !x.is_empty())
85            .map(PathBuf::from)
86            .or_else(|| home().map(|h| h.join(".config")))
87    };
88    folder.map(|f| f.join("KinematicsSimulation").join("settings.toml"))
89}
90
91/// The settings stored in `path`: none where there is no file yet; where it cannot be read, is no TOML or is of
92/// another version, none either, and the message that says so.
93pub fn load(path: &Path) -> (Settings, Option<Message>) {
94    let text = match std::fs::read_to_string(path) {
95        Ok(text) => text,
96        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (Settings::default(), None),
97        Err(e) => return (Settings::default(), Some(("ui-settings-ignored", format!("{}: {e}", path.display())))),
98    };
99    match Settings::parse(&text) {
100        Ok(settings) => (settings, None),
101        Err((key, detail)) => {
102            let detail =
103                if detail.is_empty() { path.display().to_string() } else { format!("{}: {detail}", path.display()) };
104            (Settings::default(), Some((key, detail)))
105        }
106    }
107}
108
109pub fn save(path: &Path, settings: &Settings) -> Result<(), Message> {
110    let written = path
111        .parent()
112        .filter(|folder| !folder.as_os_str().is_empty())
113        .map_or(Ok(()), std::fs::create_dir_all)
114        .and_then(|()| std::fs::write(path, settings.to_text()));
115    written.map_err(|e| ("ui-settings-unsaved", format!("{}: {e}", path.display())))
116}
117
118/// The language to start in: the environment's `SIM_APP_LANG` first, then the stored one, then the system's, then
119/// the first of `languages`; one of them that the app does not have is passed over.
120pub fn language(
121    languages: &'static [&'static str],
122    asked: Option<&str>,
123    stored: Option<&str>,
124    system: Option<&str>,
125) -> &'static str {
126    [asked, stored, system]
127        .into_iter()
128        .flatten()
129        .find_map(|wanted| languages.iter().copied().find(|l| *l == wanted))
130        .unwrap_or(languages[0])
131}
132
133/// The system's language code from the locale variables (`LC_ALL`, `LC_MESSAGES`, `LANG`; "de_DE.UTF-8" is "de"),
134/// where there are any. Windows has none of them: the app stays English there.
135pub fn system_language(env: impl Fn(&str) -> Option<String>) -> Option<String> {
136    ["LC_ALL", "LC_MESSAGES", "LANG"].into_iter().find_map(|name| {
137        let locale = env(name).filter(|l| !l.is_empty() && l != "C" && l != "POSIX")?;
138        Some(locale.split(['_', '.', '@']).next()?.to_ascii_lowercase())
139    })
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    fn temp(name: &str) -> PathBuf {
147        let folder = std::env::temp_dir().join(format!("sim-app-settings-{}-{name}", std::process::id()));
148        let _ = std::fs::remove_dir_all(&folder);
149        folder.join("settings.toml")
150    }
151
152    fn stored() -> Settings {
153        Settings {
154            lang: Some("de".into()),
155            light: Some(true),
156            rpm: Some(true),
157            mm: Some(false),
158            speed: Some(0.25),
159            config_file: Some("my machine.toml".into()),
160            machine: Some("some-machine".into()),
161        }
162    }
163
164    /// What is stored comes back, from a folder that did not exist; the language and the theme with it.
165    #[test]
166    fn what_is_saved_is_loaded_again() {
167        let file = temp("roundtrip");
168        save(&file, &stored()).unwrap();
169        assert_eq!(load(&file), (stored(), None));
170        assert_eq!(load(&temp("none")), (Settings::default(), None), "no file yet is no message");
171    }
172
173    /// The environment's language beats the stored one, which beats the system's; a language the app lacks is passed
174    /// over; with none of them, English.
175    #[test]
176    fn the_language_comes_from_the_environment_then_the_file_then_the_system() {
177        let langs = &["en", "de"];
178        assert_eq!(language(langs, Some("en"), Some("de"), Some("de")), "en");
179        assert_eq!(language(langs, None, Some("de"), None), "de");
180        assert_eq!(language(langs, None, None, Some("de")), "de");
181        assert_eq!(language(langs, Some("xx"), Some("yy"), Some("fr")), "en");
182        let env = |name: &str| (name == "LANG").then(|| "de_DE.UTF-8".to_string());
183        assert_eq!(system_language(env).as_deref(), Some("de"));
184        assert_eq!(system_language(|_| Some("C".into())), None);
185        assert_eq!(system_language(|_| None), None);
186    }
187
188    /// A file that is no TOML, or is of another version, is ignored with a message, and so is one that cannot be read
189    /// as a file (a folder).
190    #[test]
191    fn a_broken_or_outdated_file_is_ignored_with_a_message() {
192        let file = temp("broken");
193        std::fs::create_dir_all(file.parent().unwrap()).unwrap();
194        std::fs::write(&file, "language = [oops").unwrap();
195        let (settings, message) = load(&file);
196        assert_eq!((settings, message.map(|m| m.0)), (Settings::default(), Some("ui-settings-ignored")));
197        std::fs::write(&file, "version = 99\nlanguage = \"de\"\n").unwrap();
198        let (settings, message) = load(&file);
199        assert_eq!((settings, message.map(|m| m.0)), (Settings::default(), Some("ui-settings-outdated")));
200        std::fs::write(&file, "language = \"de\"\n").unwrap();
201        assert_eq!(load(&file).1.map(|m| m.0), Some("ui-settings-outdated"), "a file without a version");
202        assert_eq!(load(file.parent().unwrap()).1.map(|m| m.0), Some("ui-settings-ignored"));
203    }
204
205    /// Tests and the screenshot hook have no file of their own unless one is named; the user's is never theirs.
206    #[test]
207    fn the_file_is_where_the_environment_says_and_never_the_users_in_a_test() {
208        let with = |pairs: &'static [(&str, &str)]| {
209            move |name: &str| pairs.iter().find(|(k, _)| *k == name).map(|(_, v)| v.to_string())
210        };
211        assert_eq!(path(with(&[("SIM_APP_SETTINGS", "x.toml")])), Some(PathBuf::from("x.toml")));
212        assert_eq!(path(with(&[("APPDATA", "a"), ("HOME", "h"), ("XDG_CONFIG_HOME", "x")])), None, "under test");
213    }
214}