Skip to main content

base/
settings.rs

1// settings -- typed settings: a schema of keys (type, default, limits, label) over a settings
2// file (Ini) with a format version and migrations
3//
4//   const DARK: Key<bool> = Key::bool("view.dark", false).label("Dunkles Design");
5//   const ZOOM: Key<i64> = Key::int("view.zoom", 100, 10, 800).label("Zoom (%)").step(10);
6//   static SCHEMA: Schema = Schema::new(2, &[DARK.d, ZOOM.d]).sections(&[("view", "Ansicht")])
7//       .migrate(migrate);
8//   let mut s = Settings::open("config://settings.ini", &SCHEMA);
9//   let zoom: i64 = s.get(&ZOOM);   s.set(&ZOOM, 120);   s.save();
10//
11// Key types: Key<bool> (Key::bool), Key<i64> (Key::int: min..max, step), Key<f64> (Key::num:
12// min..max, decimals), Key<String> (Key::text: at most max bytes of UTF-8), Key<usize>
13// (Key::choice: an index into (stored word, label) items; the file keeps the word),
14// Key<u32> (Key::color: 0xRRGGBB; the file "#RRGGBB").  Builders: label(s), help(s),
15// hidden() (not on the settings page), restart() (takes effect after a restart: the page
16// says so), step(n) (int: the number box's step).
17//
18//   Settings::open(path, &schema)   load, migrate, read (a missing file: the defaults)
19//   Settings::new(&schema)          only in memory (save does nothing)
20//   Settings::from_ini(ini, &schema)  in memory, from an Ini (tests)
21//   s.get(&key) -> T   s.text(&key) -> &str   s.set(&key, v) -> changed   s.reset(&key)
22//   s.reset_all()   s.is_default(&key)   s.save() -> ok   s.dirty()   s.revision()
23//   s.ini() / s.ini_mut()   the file for free-form data the schema does not describe (a
24//                           list of recent files); ini_mut marks the settings dirty
25//   s.file_version()        the version the file had (0: none or older than versions)
26//   s.schema(), s.at(i), s.set_at(i, val), s.default_at(i)   by schema index (the page)
27//   rename(&mut ini, "old.key", "new.key")   for migrations
28//
29// Names are "section.key" (no '.': the top of the file).  The file keeps only values that
30// differ from the default (setting the default or a reset removes every line of the key, also
31// one that already read as the default), so a new default reaches users who never changed it;
32// comments, unknown keys and other sections survive (Ini).  set / reset report whether the
33// value or the file changed.  A text is kept as the file can hold it: CR, LF and NUL become
34// blanks, blanks around it go, then it is cut to its maximum (what a restart reads back); a
35// value whose line would be too long for the file is not set (false, a WARN).
36// The format version is "version=N" at the top: a file of an older version (no line: 0)
37// runs migrate(from, &mut ini) once before its values are read (rename keys, convert units)
38// and is saved with the new version by the next save; a missing file needs no migration; a
39// file of a newer version is read as far as the schema goes and keeps its number.  A value
40// the schema cannot use (not a number, an unknown choice, a bad colour) reads as the default
41// and a WARN goes to the log; numbers out of range are clamped, texts cut to their maximum.
42// Keys that are not in the schema still work through get / set (read from the file each
43// time) but are not on the page.
44
45use alloc::string::String;
46use alloc::vec::Vec;
47use core::marker::PhantomData;
48
49use crate::ini::Ini;
50use crate::num::{f64_format, f64_parse, parse_i64};
51
52/// Desc::flags: not on the settings page
53pub const KF_HIDDEN: u32 = 1;
54/// Desc::flags: takes effect after a restart (the page says so)
55pub const KF_RESTART: u32 = 2;
56
57/// what a key holds, with its default and limits
58#[derive(Clone, Copy, Debug)]
59#[non_exhaustive]
60pub enum Kind {
61    Bool(bool),
62    Int { def: i64, min: i64, max: i64, step: i64 },
63    Num { def: f64, min: f64, max: f64, dec: u32 },
64    Text { def: &'static str, max: usize },
65    Choice { def: usize, items: &'static [(&'static str, &'static str)] },
66    Color(u32),
67}
68
69/// a key of a schema (Key::d)
70#[derive(Clone, Copy, Debug)]
71pub struct Desc {
72    pub name: &'static str,
73    pub label: &'static str,
74    pub help: &'static str,
75    pub flags: u32,
76    pub kind: Kind,
77}
78
79impl Desc {
80    /// (section, key) of the name
81    pub fn split(&self) -> (&'static str, &'static str) {
82        split(self.name)
83    }
84
85    /// the default value
86    pub fn default_val(&self) -> Val {
87        match self.kind {
88            Kind::Bool(d) => Val::Bool(d),
89            Kind::Int { def, .. } => Val::Int(def),
90            Kind::Num { def, .. } => Val::Num(def),
91            Kind::Text { def, max } => Val::Text(canon(def, max)),
92            Kind::Choice { def, .. } => Val::Choice(def),
93            Kind::Color(d) => Val::Color(d & 0xFF_FFFF),
94        }
95    }
96
97    /// v made valid for this key (clamped, cut, the default when it is of another type)
98    pub fn fit(&self, v: Val) -> Val {
99        match (self.kind, v) {
100            (Kind::Bool(_), Val::Bool(b)) => Val::Bool(b),
101            (Kind::Int { min, max, .. }, Val::Int(x)) => Val::Int(x.clamp(min, max.max(min))),
102            (Kind::Num { min, max, .. }, Val::Num(x)) if !x.is_nan() && !min.is_nan() && !max.is_nan() => Val::Num(x.clamp(min, max.max(min))),
103            (Kind::Text { max, .. }, Val::Text(s)) => Val::Text(canon(&s, max)),
104            (Kind::Choice { items, .. }, Val::Choice(i)) if i < items.len() => Val::Choice(i),
105            (Kind::Color(_), Val::Color(c)) => Val::Color(c & 0xFF_FFFF),
106            _ => self.default_val(),
107        }
108    }
109
110    /// the value written into the file for v
111    pub fn format(&self, v: &Val) -> String {
112        match v {
113            Val::Bool(b) => String::from(if *b { "true" } else { "false" }),
114            Val::Int(x) => alloc::format!("{}", x),
115            Val::Num(x) => f64_format(*x),
116            Val::Text(s) => s.clone(),
117            Val::Choice(i) => match self.kind {
118                Kind::Choice { items, .. } => String::from(items.get(*i).map_or("", |it| it.0)),
119                _ => String::new(),
120            },
121            Val::Color(c) => alloc::format!("#{:06X}", c & 0xFF_FFFF),
122        }
123    }
124
125    /// the text of the file read as this key: Some(valid value) (clamped / cut) or None
126    pub fn parse(&self, s: &str) -> Option<Val> {
127        let t = s.trim();
128        let v = match self.kind {
129            Kind::Bool(_) => Val::Bool(parse_i64(t.as_bytes())? != 0),
130            Kind::Int { .. } => Val::Int(parse_i64(t.as_bytes())?),
131            Kind::Num { .. } => {
132                let (x, used) = f64_parse(t.as_bytes());
133                if used == 0 || used != t.len() || x.is_nan() {
134                    return None;
135                }
136                Val::Num(x)
137            }
138            Kind::Text { .. } => Val::Text(String::from(s)),
139            Kind::Choice { items, .. } => Val::Choice(items.iter().position(|it| it.0.eq_ignore_ascii_case(t))?),
140            Kind::Color(_) => {
141                let h = t.strip_prefix('#').unwrap_or(t);
142                if h.len() != 6 || !h.bytes().all(|b| b.is_ascii_hexdigit()) {
143                    return None;
144                }
145                Val::Color(u32::from_str_radix(h, 16).ok()?)
146            }
147        };
148        Some(self.fit(v))
149    }
150}
151
152/// a value of a key
153#[derive(Clone, Debug, PartialEq)]
154#[non_exhaustive]
155pub enum Val {
156    Bool(bool),
157    Int(i64),
158    Num(f64),
159    Text(String),
160    Choice(usize),
161    Color(u32),
162}
163
164/// the Rust types a key can have: bool, i64, f64, String, usize (choice), u32 (colour)
165pub trait Value: Sized {
166    #[doc(hidden)]
167    fn from_val(v: &Val) -> Option<Self>;
168    #[doc(hidden)]
169    fn into_val(self) -> Val;
170}
171
172impl Value for bool {
173    fn from_val(v: &Val) -> Option<bool> {
174        if let Val::Bool(b) = v { Some(*b) } else { None }
175    }
176    fn into_val(self) -> Val {
177        Val::Bool(self)
178    }
179}
180
181impl Value for i64 {
182    fn from_val(v: &Val) -> Option<i64> {
183        if let Val::Int(x) = v { Some(*x) } else { None }
184    }
185    fn into_val(self) -> Val {
186        Val::Int(self)
187    }
188}
189
190impl Value for f64 {
191    fn from_val(v: &Val) -> Option<f64> {
192        if let Val::Num(x) = v { Some(*x) } else { None }
193    }
194    fn into_val(self) -> Val {
195        Val::Num(self)
196    }
197}
198
199impl Value for String {
200    fn from_val(v: &Val) -> Option<String> {
201        if let Val::Text(s) = v { Some(s.clone()) } else { None }
202    }
203    fn into_val(self) -> Val {
204        Val::Text(self)
205    }
206}
207
208impl Value for usize {
209    fn from_val(v: &Val) -> Option<usize> {
210        if let Val::Choice(i) = v { Some(*i) } else { None }
211    }
212    fn into_val(self) -> Val {
213        Val::Choice(self)
214    }
215}
216
217impl Value for u32 {
218    fn from_val(v: &Val) -> Option<u32> {
219        if let Val::Color(c) = v { Some(*c) } else { None }
220    }
221    fn into_val(self) -> Val {
222        Val::Color(self)
223    }
224}
225
226/// a typed key: its description (d) and the Rust type of its value
227pub struct Key<T> {
228    pub d: Desc,
229    t: PhantomData<fn() -> T>,
230}
231
232impl<T> Clone for Key<T> {
233    fn clone(&self) -> Key<T> {
234        *self
235    }
236}
237impl<T> Copy for Key<T> {}
238
239const fn key<T>(name: &'static str, kind: Kind) -> Key<T> {
240    Key { d: Desc { name, label: name, help: "", flags: 0, kind }, t: PhantomData }
241}
242
243impl Key<bool> {
244    pub const fn bool(name: &'static str, def: bool) -> Key<bool> {
245        key(name, Kind::Bool(def))
246    }
247}
248
249impl Key<i64> {
250    /// a whole number in min..=max (step 1)
251    pub const fn int(name: &'static str, def: i64, min: i64, max: i64) -> Key<i64> {
252        key(name, Kind::Int { def, min, max, step: 1 })
253    }
254
255    /// the step of the number box's arrows and arrow keys
256    pub const fn step(self, step: i64) -> Key<i64> {
257        let mut k = self;
258        if let Kind::Int { def, min, max, .. } = k.d.kind {
259            k.d.kind = Kind::Int { def, min, max, step };
260        }
261        k
262    }
263}
264
265impl Key<f64> {
266    /// a number in min..=max, shown with dec decimals
267    pub const fn num(name: &'static str, def: f64, min: f64, max: f64, dec: u32) -> Key<f64> {
268        key(name, Kind::Num { def, min, max, dec })
269    }
270}
271
272impl Key<String> {
273    /// a text of at most max bytes (UTF-8)
274    pub const fn text(name: &'static str, def: &'static str, max: usize) -> Key<String> {
275        key(name, Kind::Text { def, max })
276    }
277}
278
279impl Key<usize> {
280    /// one of items (stored word, label); the value is its index
281    pub const fn choice(name: &'static str, def: usize, items: &'static [(&'static str, &'static str)]) -> Key<usize> {
282        key(name, Kind::Choice { def, items })
283    }
284}
285
286impl Key<u32> {
287    /// a colour 0xRRGGBB
288    pub const fn color(name: &'static str, def: u32) -> Key<u32> {
289        key(name, Kind::Color(def))
290    }
291}
292
293impl<T> Key<T> {
294    /// the text of the settings page (default: the name)
295    pub const fn label(self, label: &'static str) -> Key<T> {
296        let mut k = self;
297        k.d.label = label;
298        k
299    }
300
301    /// a line of explanation below the label
302    pub const fn help(self, help: &'static str) -> Key<T> {
303        let mut k = self;
304        k.d.help = help;
305        k
306    }
307
308    /// not on the settings page (state the app keeps)
309    pub const fn hidden(self) -> Key<T> {
310        let mut k = self;
311        k.d.flags |= KF_HIDDEN;
312        k
313    }
314
315    /// takes effect after a restart
316    pub const fn restart(self) -> Key<T> {
317        let mut k = self;
318        k.d.flags |= KF_RESTART;
319        k
320    }
321}
322
323/// the keys of a settings file, its format version, the page's section titles and the
324/// migration of older files
325pub struct Schema {
326    pub version: u32,
327    pub keys: &'static [Desc],
328    /// (section, title) for the settings page, in this order (sections without a title come
329    /// after them, titled by their name)
330    pub sections: &'static [(&'static str, &'static str)],
331    /// migrate(from, &mut ini): bring a file of version `from` up to `version`
332    pub migrate: Option<fn(u32, &mut Ini)>,
333}
334
335impl Schema {
336    pub const fn new(version: u32, keys: &'static [Desc]) -> Schema {
337        Schema { version, keys, sections: &[], migrate: None }
338    }
339
340    pub const fn sections(self, sections: &'static [(&'static str, &'static str)]) -> Schema {
341        Schema { sections, ..self }
342    }
343
344    pub const fn migrate(self, f: fn(u32, &mut Ini)) -> Schema {
345        Schema { migrate: Some(f), ..self }
346    }
347
348    /// the index of a key name
349    pub fn index(&self, name: &str) -> Option<usize> {
350        self.keys.iter().position(|d| d.name == name)
351    }
352}
353
354/// "section.key" -> (section, key); no '.': ("", name)
355pub fn split(name: &str) -> (&str, &str) {
356    name.split_once('.').unwrap_or(("", name))
357}
358
359/// for migrations: move a value from one name to another ("section.key"); false: not there
360pub fn rename(ini: &mut Ini, old: &str, new: &str) -> bool {
361    let (os, ok) = split(old);
362    let Some(v) = ini.get(os, ok).map(String::from) else { return false };
363    let (ns, nk) = split(new);
364    if !ini.set(ns, nk, &v) {
365        return false;
366    }
367    if (os, ok) != (ns, nk) {
368        ini.remove(os, ok);
369    }
370    true
371}
372
373// s cut to at most max bytes at a character boundary, without blanks at its end
374fn cut(s: &str, max: usize) -> &str {
375    let mut n = max.min(s.len());
376    while !s.is_char_boundary(n) {
377        n -= 1;
378    }
379    s[..n].trim_end_matches([' ', '\t'])
380}
381
382// a text as the file keeps it -- CR, LF and NUL as blanks, no blanks around it, at most max
383// bytes -- so the value a program sets is the value it reads after a restart
384fn canon(s: &str, max: usize) -> String {
385    let t: String = s.chars().map(|c| if matches!(c, '\r' | '\n' | '\0') { ' ' } else { c }).collect();
386    String::from(cut(t.trim_matches([' ', '\t']), max))
387}
388
389/// typed settings over a file (see the module header)
390pub struct Settings {
391    schema: &'static Schema,
392    path: String,
393    ini: Ini,
394    vals: Vec<Val>,
395    dirty: bool,
396    rev: u32,
397    file_version: u32,
398    unreadable: bool, // the file exists but could not be read: save must not overwrite it
399}
400
401impl Settings {
402    /// the settings of a file (a missing or unreadable file: the defaults)
403    pub fn open(path: &str, schema: &'static Schema) -> Settings {
404        let exists = plat::file_exists(path) == 1;
405        let loaded = Ini::load_checked(path);
406        let unreadable = loaded.is_none();
407        let mut s = Settings::from_ini_ex(loaded.unwrap_or_else(Ini::new), schema, exists && !unreadable);
408        s.path = String::from(path);
409        s.unreadable = unreadable;
410        if unreadable {
411            plat::log_warn("settings", &alloc::format!("could not read {}, it is not overwritten", path));
412        }
413        s
414    }
415
416    /// settings only in memory (save does nothing)
417    pub fn new(schema: &'static Schema) -> Settings {
418        Settings::from_ini_ex(Ini::new(), schema, false)
419    }
420
421    /// settings in memory, read from an Ini (migrated like a file)
422    pub fn from_ini(ini: Ini, schema: &'static Schema) -> Settings {
423        Settings::from_ini_ex(ini, schema, true)
424    }
425
426    fn from_ini_ex(mut ini: Ini, schema: &'static Schema, existed: bool) -> Settings {
427        let mut dirty = false;
428        let file_version = ini.get_int("", "version", 0).clamp(0, u32::MAX as i64) as u32;
429        if existed && file_version < schema.version {
430            if let Some(m) = schema.migrate {
431                m(file_version, &mut ini);
432            }
433            ini.set_int("", "version", schema.version as i64);
434            dirty = true;
435            plat::log_info("settings", &alloc::format!("migrated from version {} to {}", file_version, schema.version));
436        } else if file_version > schema.version {
437            plat::log_warn("settings", &alloc::format!("the file has version {}, the program knows {}", file_version, schema.version));
438        }
439        let vals = schema.keys.iter().map(|d| read(&ini, d)).collect();
440        Settings { schema, path: String::new(), ini, vals, dirty, rev: 0, file_version, unreadable: false }
441    }
442
443    pub fn schema(&self) -> &'static Schema {
444        self.schema
445    }
446
447    /// the file's path ("" in memory)
448    pub fn path(&self) -> &str {
449        &self.path
450    }
451
452    /// the format version the file had before a migration (0: none / no version line)
453    pub fn file_version(&self) -> u32 {
454        self.file_version
455    }
456
457    /// a value (the key's default when the key is not in the schema and not in the file)
458    pub fn get<T: Value>(&self, k: &Key<T>) -> T {
459        let v = match self.schema.index(k.d.name) {
460            Some(i) => T::from_val(&self.vals[i]),
461            None => T::from_val(&read(&self.ini, &k.d)),
462        };
463        v.or_else(|| T::from_val(&k.d.default_val())).unwrap_or_else(|| {
464            plat::log_warn("settings", &alloc::format!("{}: the key has another type than the schema's", k.d.name));
465            T::from_val(&Val::Bool(false)).or_else(|| T::from_val(&Val::Int(0))).or_else(|| T::from_val(&Val::Num(0.0))).or_else(|| T::from_val(&Val::Text(String::new()))).or_else(|| T::from_val(&Val::Choice(0))).or_else(|| T::from_val(&Val::Color(0))).expect("settings: the type of a key")
466        })
467    }
468
469    /// a text without copying it
470    pub fn text(&self, k: &Key<String>) -> &str {
471        match self.schema.index(k.d.name).map(|i| &self.vals[i]) {
472            Some(Val::Text(s)) => s,
473            // a key outside the schema: the file's text, at most the key's max bytes (as get)
474            _ => {
475                let (s, n) = k.d.split();
476                let max = match k.d.kind {
477                    Kind::Text { max, .. } => max,
478                    _ => usize::MAX,
479                };
480                match self.ini.get(s, n) {
481                    Some(t) => cut(t, max),
482                    None => match k.d.kind {
483                        Kind::Text { def, .. } => cut(def.trim_matches([' ', '\t']), max),
484                        _ => "",
485                    },
486                }
487            }
488        }
489    }
490
491    /// set a value (made valid for the key) -> the value or the file changed (the default
492    /// removes every line of the key, also one that held it already)
493    pub fn set<T: Value>(&mut self, k: &Key<T>, v: T) -> bool {
494        match self.schema.index(k.d.name) {
495            Some(i) => self.set_at(i, v.into_val()),
496            None => {
497                let v = k.d.fit(v.into_val());
498                let old = read(&self.ini, &k.d);
499                let Some(file) = write(&mut self.ini, &k.d, &v) else { return false };
500                if old == v && !file {
501                    return false;
502                }
503                self.changed();
504                true
505            }
506        }
507    }
508
509    /// back to the default: every line of the key leaves the file (also an explicit default,
510    /// a value that read as the default, a second line of the same key)
511    pub fn reset<T>(&mut self, k: &Key<T>) -> bool {
512        match self.schema.index(k.d.name) {
513            Some(i) => self.set_at(i, k.d.default_val()),
514            None => {
515                let gone = write(&mut self.ini, &k.d, &k.d.default_val()) == Some(true);
516                if gone {
517                    self.changed();
518                }
519                gone
520            }
521        }
522    }
523
524    /// every key of the schema back to its default
525    pub fn reset_all(&mut self) -> bool {
526        let mut any = false;
527        for i in 0..self.schema.keys.len() {
528            any |= self.set_at(i, self.schema.keys[i].default_val());
529        }
530        any
531    }
532
533    /// the key has its default value
534    pub fn is_default<T>(&self, k: &Key<T>) -> bool {
535        match self.schema.index(k.d.name) {
536            Some(i) => self.vals[i] == self.default_at(i),
537            None => read(&self.ini, &k.d) == k.d.default_val(),
538        }
539    }
540
541    /// the value of schema key i
542    pub fn at(&self, i: usize) -> &Val {
543        &self.vals[i]
544    }
545
546    /// the default of schema key i
547    pub fn default_at(&self, i: usize) -> Val {
548        self.schema.keys[i].default_val()
549    }
550
551    /// set schema key i (made valid) -> the value or the file changed (as set)
552    pub fn set_at(&mut self, i: usize, v: Val) -> bool {
553        let d = &self.schema.keys[i];
554        let v = d.fit(v);
555        // the file first: at the default its lines go even when the value read as the default
556        let Some(file) = write(&mut self.ini, d, &v) else { return false };
557        if self.vals[i] == v && !file {
558            return false;
559        }
560        self.vals[i] = v;
561        self.changed();
562        true
563    }
564
565    fn changed(&mut self) {
566        self.dirty = true;
567        self.rev = self.rev.wrapping_add(1);
568    }
569
570    /// unsaved changes
571    pub fn dirty(&self) -> bool {
572        self.dirty
573    }
574
575    /// counts every change (redraw or apply what depends on the settings when it moved)
576    pub fn revision(&self) -> u32 {
577        self.rev
578    }
579
580    /// the file's data (free-form sections the schema does not describe)
581    pub fn ini(&self) -> &Ini {
582        &self.ini
583    }
584
585    /// change free-form data (marks the settings dirty; keys of the schema: use set)
586    pub fn ini_mut(&mut self) -> &mut Ini {
587        self.changed();
588        &mut self.ini
589    }
590
591    /// write the file when something changed (atomic; in memory: nothing) -> ok
592    pub fn save(&mut self) -> bool {
593        if !self.dirty {
594            return true;
595        }
596        if self.path.is_empty() {
597            self.dirty = false;
598            return true;
599        }
600        if self.unreadable {
601            return false;
602        }
603        if self.ini.get("", "version").is_none() || self.file_version < self.schema.version {
604            self.ini.set_int("", "version", self.schema.version.max(self.file_version) as i64);
605        }
606        let ok = self.ini.save(&self.path);
607        if ok {
608            self.dirty = false;
609        } else {
610            plat::log_warn("settings", &alloc::format!("could not write {}", self.path));
611        }
612        ok
613    }
614}
615
616// the key's value in the file (invalid: the default and a WARN)
617fn read(ini: &Ini, d: &Desc) -> Val {
618    let (s, n) = d.split();
619    match ini.get(s, n) {
620        None => d.default_val(),
621        Some(t) => match d.parse(t) {
622            Some(v) => v,
623            None => {
624                plat::log_warn("settings", &alloc::format!("{}: \"{}\" is not a valid value, the default is used", d.name, t));
625                d.default_val()
626            }
627        },
628    }
629}
630
631// the key's lines for v: at the default every one of them goes (a second line of the key would
632// be read after a restart), else its line holds v -> whether the file changed; None: the file
633// cannot hold the value (a line longer than Ini's maximum), nothing changed
634fn write(ini: &mut Ini, d: &Desc, v: &Val) -> Option<bool> {
635    let (s, n) = d.split();
636    if *v == d.default_val() {
637        let mut gone = false;
638        while ini.remove(s, n) {
639            gone = true;
640        }
641        return Some(gone);
642    }
643    let text = d.format(v);
644    if ini.get(s, n) == Some(text.as_str()) {
645        return Some(false);
646    }
647    if !ini.set(s, n, &text) {
648        plat::log_warn("settings", &alloc::format!("{}: the value is too long for the file and is not set", d.name));
649        return None;
650    }
651    Some(true)
652}