Skip to main content

egui_pop_api/admin/
store.rs

1//! Where the settings' values are kept: a contract the host provides
2//! ([`SettingsStore`]), which the Settings app calls. egui-pop holds no
3//! storage location and no default store: without one
4//! ([`super::Admin::attach_store`]), the values live in memory for the
5//! session and the Settings window says so.
6//!
7//! - **Load**: each scope the store holds is read when the store is
8//!   attached (`app`, and a host scope when it is offered, or reloaded
9//!   with [`super::Admin::reload`]); the values it gives become the
10//!   layer's, or the user's own for `app`.
11//! - **Save**: what changes in a scope the store holds is sent as the
12//!   values changed, away from the UI thread (a worker thread; on the web,
13//!   at once). A failing save is shown in the Settings window until a
14//!   save of that scope succeeds.
15//! - **Watch**: a store tells the app of changes made elsewhere (another
16//!   client, another process); they are applied at the next pass, and
17//!   nothing is written back.
18//! - **Claims**: a store holds the settings it claims, the others stay
19//!   with the app. [`CompositeStore`] routes each setting to the first
20//!   handler claiming it, the rest to a default store.
21//!
22//! [`FileStore`] keeps a scope in a JSON file whose path the host gives;
23//! [`MemoryStore`] keeps them in memory (tests, demos, a handler for the
24//! settings that must not outlive the session).
25
26use std::collections::{BTreeMap, BTreeSet};
27use std::path::PathBuf;
28use std::sync::{Arc, Mutex};
29
30use egui_pop_core::lock;
31use egui_pop_model::admin::ValueScope;
32use serde_json::Value as Json;
33
34/// A scope's values, by setting id (`appearance.theme`, not its store
35/// path).
36pub type Values = BTreeMap<String, Json>;
37
38/// Values changed in a scope, by setting id: `Some` its new value, `None`
39/// taken back (back to the default, or to the layer under it).
40pub type Changes = BTreeMap<String, Option<Json>>;
41
42/// Called by a store when values change elsewhere: the scope and what
43/// changed. May be called from any thread.
44pub type OnChange = Arc<dyn Fn(ValueScope, Changes) + Send + Sync>;
45
46/// Where the settings are kept, as the host provides it. Every method
47/// may be called from a thread other than the UI's: `save` always is,
48/// except on the web.
49pub trait SettingsStore: Send + Sync {
50    /// The scopes it keeps (`app`, and host scopes such as a library).
51    fn scopes(&self) -> Vec<ValueScope>;
52
53    /// Whether it keeps this setting (by id). Everything by default.
54    fn claims(&self, _setting: &str) -> bool {
55        true
56    }
57
58    /// A scope's values as kept now.
59    fn load(&self, scope: ValueScope) -> Result<Values, String>;
60
61    /// Keeps the values that changed in a scope. Never called on the UI
62    /// thread (but on the web).
63    fn save(&self, scope: ValueScope, changes: &Changes) -> Result<(), String>;
64
65    /// Follows the changes made elsewhere to a scope: `on_change` is
66    /// called with them. Stores that see none keep the default.
67    fn watch(&self, _scope: ValueScope, _on_change: OnChange) -> Result<(), String> {
68        Ok(())
69    }
70
71    /// Problems worth showing in the Settings window that are not a
72    /// failed load or save (a setting two handlers claim).
73    fn problems(&self) -> Vec<String> {
74        Vec::new()
75    }
76}
77
78/// Applies changes to values.
79pub fn apply(values: &mut Values, changes: &Changes) {
80    for (k, v) in changes {
81        match v {
82            Some(v) => values.insert(k.clone(), v.clone()),
83            None => values.remove(k),
84        };
85    }
86}
87
88/// What changed from `before` to `after`.
89pub fn diff(before: &Values, after: &Values) -> Changes {
90    let mut out = Changes::new();
91    for (k, v) in after {
92        if before.get(k) != Some(v) {
93            out.insert(k.clone(), Some(v.clone()));
94        }
95    }
96    for k in before.keys() {
97        if !after.contains_key(k) {
98            out.insert(k.clone(), None);
99        }
100    }
101    out
102}
103
104/// An ordered list of handlers and a default store. Each setting
105/// belongs to the first handler claiming it, else to the default; loads
106/// merge what each one owns, saves are split by owner, and every
107/// handler's changes are followed. A setting claimed by two handlers is
108/// reported once ([`SettingsStore::problems`]); the first wins.
109pub struct CompositeStore {
110    handlers: Vec<Arc<dyn SettingsStore>>,
111    default: Arc<dyn SettingsStore>,
112    overlaps: Mutex<BTreeSet<String>>,
113}
114
115impl std::fmt::Debug for CompositeStore {
116    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        f.debug_struct("CompositeStore")
118            .field("handlers", &self.handlers.len())
119            .field("overlaps", &self.overlaps)
120            .finish_non_exhaustive()
121    }
122}
123
124impl CompositeStore {
125    /// A composite whose unclaimed settings go to `default`.
126    pub fn new(default: impl SettingsStore + 'static) -> CompositeStore {
127        CompositeStore {
128            handlers: Vec::new(),
129            default: Arc::new(default),
130            overlaps: Mutex::new(BTreeSet::new()),
131        }
132    }
133
134    /// Adds a handler after those added before (an earlier one wins).
135    #[must_use]
136    pub fn handler(mut self, handler: impl SettingsStore + 'static) -> CompositeStore {
137        self.handlers.push(Arc::new(handler));
138        self
139    }
140
141    /// The index of the handler owning a setting, `None` for the default.
142    /// A second handler claiming it is reported, once.
143    pub fn owner(&self, setting: &str) -> Option<usize> {
144        let mut claiming = self
145            .handlers
146            .iter()
147            .enumerate()
148            .filter(|(_, h)| h.claims(setting))
149            .map(|(i, _)| i);
150        let first = claiming.next()?;
151        if let Some(second) = claiming.next()
152            && lock(&self.overlaps).insert(setting.to_string())
153        {
154            log::warn!(
155                target: "egui_pop",
156                "settings: `{setting}` is claimed by handlers {first} and {second}: the first keeps it"
157            );
158        }
159        Some(first)
160    }
161
162    /// The settings two handlers claimed, as seen so far.
163    pub fn overlaps(&self) -> Vec<String> {
164        lock(&self.overlaps).iter().cloned().collect()
165    }
166
167    /// Every store: the handlers, then the default.
168    fn stores(&self) -> impl Iterator<Item = (Option<usize>, &Arc<dyn SettingsStore>)> {
169        self.handlers
170            .iter()
171            .enumerate()
172            .map(|(i, h)| (Some(i), h))
173            .chain(std::iter::once((None, &self.default)))
174    }
175
176    /// Whether `store` owns `setting`.
177    fn owns(&self, store: Option<usize>, setting: &str) -> bool {
178        match self.owner(setting) {
179            Some(i) => store == Some(i),
180            None => store.is_none() && self.default.claims(setting),
181        }
182    }
183}
184
185impl SettingsStore for CompositeStore {
186    fn scopes(&self) -> Vec<ValueScope> {
187        let mut out = Vec::new();
188        for (_, s) in self.stores() {
189            for scope in s.scopes() {
190                if !out.contains(&scope) {
191                    out.push(scope);
192                }
193            }
194        }
195        out
196    }
197
198    fn claims(&self, setting: &str) -> bool {
199        self.owner(setting).is_some() || self.default.claims(setting)
200    }
201
202    fn load(&self, scope: ValueScope) -> Result<Values, String> {
203        let mut out = Values::new();
204        let mut errors = Vec::new();
205        for (i, s) in self.stores() {
206            if !s.scopes().contains(&scope) {
207                continue;
208            }
209            match s.load(scope) {
210                Ok(values) => out.extend(values.into_iter().filter(|(k, _)| self.owns(i, k))),
211                Err(e) => errors.push(e),
212            }
213        }
214        if errors.is_empty() {
215            Ok(out)
216        } else {
217            Err(errors.join("; "))
218        }
219    }
220
221    fn save(&self, scope: ValueScope, changes: &Changes) -> Result<(), String> {
222        let mut errors = Vec::new();
223        for (i, s) in self.stores() {
224            let mine: Changes = changes
225                .iter()
226                .filter(|(k, _)| self.owns(i, k))
227                .map(|(k, v)| (k.clone(), v.clone()))
228                .collect();
229            if mine.is_empty() {
230                continue;
231            }
232            if !s.scopes().contains(&scope) {
233                errors.push(format!(
234                    "{} setting(s) have no store for the {} scope",
235                    mine.len(),
236                    scope.name()
237                ));
238                continue;
239            }
240            if let Err(e) = s.save(scope, &mine) {
241                errors.push(e);
242            }
243        }
244        if errors.is_empty() {
245            Ok(())
246        } else {
247            Err(errors.join("; "))
248        }
249    }
250
251    fn watch(&self, scope: ValueScope, on_change: OnChange) -> Result<(), String> {
252        // Each store's changes, less the settings it does not own: the
253        // composite is shared through the callback, so it holds the
254        // routing itself.
255        let routes: Arc<Vec<Arc<dyn SettingsStore>>> = Arc::new(self.handlers.clone());
256        let default = self.default.clone();
257        let mut errors = Vec::new();
258        for (i, s) in self.stores() {
259            if !s.scopes().contains(&scope) {
260                continue;
261            }
262            let routes = routes.clone();
263            let default = default.clone();
264            let on_change = on_change.clone();
265            let filtered: OnChange = Arc::new(move |scope, changes: Changes| {
266                let owner = |k: &str| routes.iter().position(|h| h.claims(k));
267                let mine: Changes = changes
268                    .into_iter()
269                    .filter(|(k, _)| match owner(k) {
270                        Some(o) => i == Some(o),
271                        None => i.is_none() && default.claims(k),
272                    })
273                    .collect();
274                if !mine.is_empty() {
275                    on_change(scope, mine);
276                }
277            });
278            if let Err(e) = s.watch(scope, filtered) {
279                errors.push(e);
280            }
281        }
282        if errors.is_empty() {
283            Ok(())
284        } else {
285            Err(errors.join("; "))
286        }
287    }
288
289    fn problems(&self) -> Vec<String> {
290        let mut out: Vec<String> = self
291            .overlaps()
292            .into_iter()
293            .map(|s| format!("`{s}` is claimed by two handlers: the first keeps it"))
294            .collect();
295        for (_, s) in self.stores() {
296            out.extend(s.problems());
297        }
298        out
299    }
300}
301
302/// A store keeping each scope in a JSON file (an object of setting ids
303/// to values) at the path the host gives. It knows no folder of its own:
304/// a scope without a path is not kept. Saving reads the file, applies the
305/// changes and replaces it whole (written beside it, then renamed). It
306/// sees no change made elsewhere.
307#[derive(Debug, Default)]
308pub struct FileStore {
309    files: BTreeMap<ValueScope, PathBuf>,
310    /// One save at a time: each reads, then writes the file.
311    writing: Mutex<()>,
312}
313
314impl FileStore {
315    pub fn new() -> FileStore {
316        FileStore::default()
317    }
318
319    /// Keeps a scope in a file.
320    #[must_use]
321    pub fn file(mut self, scope: ValueScope, path: impl Into<PathBuf>) -> FileStore {
322        self.files.insert(scope, path.into());
323        self
324    }
325
326    /// The file a scope is kept in.
327    pub fn path(&self, scope: ValueScope) -> Option<&std::path::Path> {
328        self.files.get(&scope).map(PathBuf::as_path)
329    }
330
331    fn read(&self, scope: ValueScope) -> Result<Values, String> {
332        let path = self
333            .path(scope)
334            .ok_or_else(|| format!("no file for the {} scope", scope.name()))?;
335        match std::fs::read_to_string(path) {
336            Ok(text) if text.trim().is_empty() => Ok(Values::new()),
337            Ok(text) => serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display())),
338            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Values::new()),
339            Err(e) => Err(format!("{}: {e}", path.display())),
340        }
341    }
342}
343
344impl SettingsStore for FileStore {
345    fn scopes(&self) -> Vec<ValueScope> {
346        self.files.keys().copied().collect()
347    }
348
349    fn load(&self, scope: ValueScope) -> Result<Values, String> {
350        let _one = lock(&self.writing);
351        self.read(scope)
352    }
353
354    fn save(&self, scope: ValueScope, changes: &Changes) -> Result<(), String> {
355        let _one = lock(&self.writing);
356        let mut values = self.read(scope)?;
357        apply(&mut values, changes);
358        let path = self
359            .path(scope)
360            .ok_or_else(|| format!("no file for the {} scope", scope.name()))?;
361        let text = serde_json::to_string_pretty(&values).map_err(|e| e.to_string())?;
362        let at = |e: std::io::Error| format!("{}: {e}", path.display());
363        if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
364            std::fs::create_dir_all(dir).map_err(at)?;
365        }
366        let mut tmp = path.as_os_str().to_owned();
367        tmp.push(".tmp");
368        std::fs::write(&tmp, text + "\n").map_err(at)?;
369        std::fs::rename(&tmp, path).map_err(at)
370    }
371}
372
373type Claim = Arc<dyn Fn(&str) -> bool + Send + Sync>;
374
375/// A store keeping its scopes in memory: a handler for settings that
376/// last the session, a stand-in in tests. [`MemoryStore::change`] stands
377/// for a change made elsewhere: its watchers are told. Clones share the
378/// values.
379#[derive(Clone)]
380pub struct MemoryStore {
381    inner: Arc<MemoryInner>,
382    claim: Option<Claim>,
383}
384
385#[derive(Default)]
386struct MemoryInner {
387    scopes: Vec<ValueScope>,
388    values: Mutex<BTreeMap<ValueScope, Values>>,
389    watchers: Mutex<Vec<(ValueScope, OnChange)>>,
390    fail: Mutex<Option<String>>,
391    saves: Mutex<Vec<(ValueScope, Changes)>>,
392}
393
394impl std::fmt::Debug for MemoryStore {
395    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
396        f.debug_struct("MemoryStore")
397            .field("scopes", &self.inner.scopes)
398            .field("values", &self.inner.values)
399            .finish_non_exhaustive()
400    }
401}
402
403impl MemoryStore {
404    /// A store of these scopes, claiming every setting.
405    pub fn new(scopes: &[ValueScope]) -> MemoryStore {
406        MemoryStore {
407            inner: Arc::new(MemoryInner {
408                scopes: scopes.to_vec(),
409                ..MemoryInner::default()
410            }),
411            claim: None,
412        }
413    }
414
415    /// Claims only the settings `claim` accepts.
416    #[must_use]
417    pub fn claiming(mut self, claim: impl Fn(&str) -> bool + Send + Sync + 'static) -> Self {
418        self.claim = Some(Arc::new(claim));
419        self
420    }
421
422    /// Sets a scope's values, as kept before the app starts (no watcher
423    /// is told).
424    #[must_use]
425    pub fn with(self, scope: ValueScope, values: Values) -> Self {
426        lock(&self.inner.values).insert(scope, values);
427        self
428    }
429
430    /// A scope's values as kept now.
431    pub fn values(&self, scope: ValueScope) -> Values {
432        lock(&self.inner.values)
433            .get(&scope)
434            .cloned()
435            .unwrap_or_default()
436    }
437
438    /// Every save asked, in order.
439    pub fn saves(&self) -> Vec<(ValueScope, Changes)> {
440        lock(&self.inner.saves).clone()
441    }
442
443    /// Makes every save fail with `error` (`None`: they succeed again).
444    pub fn fail_saves(&self, error: Option<&str>) {
445        *lock(&self.inner.fail) = error.map(str::to_string);
446    }
447
448    /// A change made elsewhere: kept, and its watchers told.
449    pub fn change(&self, scope: ValueScope, changes: Changes) {
450        apply(lock(&self.inner.values).entry(scope).or_default(), &changes);
451        let watchers: Vec<OnChange> = lock(&self.inner.watchers)
452            .iter()
453            .filter(|(s, _)| *s == scope)
454            .map(|(_, w)| w.clone())
455            .collect();
456        for w in watchers {
457            w(scope, changes.clone());
458        }
459    }
460}
461
462impl SettingsStore for MemoryStore {
463    fn scopes(&self) -> Vec<ValueScope> {
464        self.inner.scopes.clone()
465    }
466
467    fn claims(&self, setting: &str) -> bool {
468        self.claim.as_ref().is_none_or(|c| c(setting))
469    }
470
471    fn load(&self, scope: ValueScope) -> Result<Values, String> {
472        Ok(self.values(scope))
473    }
474
475    fn save(&self, scope: ValueScope, changes: &Changes) -> Result<(), String> {
476        lock(&self.inner.saves).push((scope, changes.clone()));
477        if let Some(e) = lock(&self.inner.fail).clone() {
478            return Err(e);
479        }
480        apply(lock(&self.inner.values).entry(scope).or_default(), changes);
481        Ok(())
482    }
483
484    fn watch(&self, scope: ValueScope, on_change: OnChange) -> Result<(), String> {
485        lock(&self.inner.watchers).push((scope, on_change));
486        Ok(())
487    }
488}
489
490#[cfg(test)]
491mod tests {
492    use super::*;
493    use serde_json::json;
494
495    const LIB: ValueScope = ValueScope::new("library");
496
497    fn values(pairs: &[(&str, Json)]) -> Values {
498        pairs
499            .iter()
500            .map(|(k, v)| (k.to_string(), v.clone()))
501            .collect()
502    }
503
504    fn composite() -> (MemoryStore, MemoryStore, MemoryStore, CompositeStore) {
505        let node = MemoryStore::new(&[ValueScope::App, LIB]).claiming(|k| k.starts_with("lib."));
506        let wide = MemoryStore::new(&[ValueScope::App]).claiming(|k| k.starts_with("lib.shared"));
507        let file = MemoryStore::new(&[ValueScope::App]);
508        let c = CompositeStore::new(file.clone())
509            .handler(node.clone())
510            .handler(wide.clone());
511        (node, wide, file, c)
512    }
513
514    #[test]
515    fn a_claimed_setting_goes_to_its_handler_and_the_rest_to_the_default() {
516        let (node, wide, file, c) = composite();
517        let changes: Changes = [
518            ("lib.cache".to_string(), Some(json!(5))),
519            ("ui.theme".to_string(), Some(json!("dark"))),
520            ("lib.shared".to_string(), None),
521        ]
522        .into();
523        c.save(ValueScope::App, &changes).unwrap();
524        assert_eq!(node.saves().len(), 1);
525        assert_eq!(node.saves()[0].1.len(), 2, "lib.cache and lib.shared");
526        assert!(wide.saves().is_empty(), "the first handler wins");
527        assert_eq!(
528            file.values(ValueScope::App),
529            values(&[("ui.theme", json!("dark"))])
530        );
531        // The overlap is reported once.
532        assert_eq!(c.overlaps(), ["lib.shared"]);
533        c.save(ValueScope::App, &changes).unwrap();
534        assert_eq!(c.problems().len(), 1);
535    }
536
537    #[test]
538    fn loads_merge_what_each_owns() {
539        let (node, _, file, c) = composite();
540        node.save(
541            ValueScope::App,
542            &[("lib.cache".into(), Some(json!(1)))].into(),
543        )
544        .unwrap();
545        // The default's copy of a claimed setting is not its own.
546        file.save(
547            ValueScope::App,
548            &[
549                ("lib.cache".into(), Some(json!(9))),
550                ("ui.theme".into(), Some(json!("light"))),
551            ]
552            .into(),
553        )
554        .unwrap();
555        assert_eq!(
556            c.load(ValueScope::App).unwrap(),
557            values(&[("lib.cache", json!(1)), ("ui.theme", json!("light"))])
558        );
559        // A scope only the node keeps.
560        assert_eq!(c.scopes(), [ValueScope::App, LIB]);
561        assert!(
562            c.save(LIB, &[("ui.theme".into(), Some(json!(1)))].into())
563                .is_err()
564        );
565    }
566
567    #[test]
568    fn every_handlers_changes_are_followed_less_what_it_does_not_own() {
569        let (node, _, file, c) = composite();
570        let seen = Arc::new(Mutex::new(Vec::new()));
571        let s = seen.clone();
572        c.watch(
573            ValueScope::App,
574            Arc::new(move |scope, ch| lock(&s).push((scope, ch))),
575        )
576        .unwrap();
577        node.change(
578            ValueScope::App,
579            [("lib.cache".into(), Some(json!(3)))].into(),
580        );
581        file.change(
582            ValueScope::App,
583            [("lib.cache".into(), Some(json!(4)))].into(),
584        );
585        file.change(ValueScope::App, [("ui.theme".into(), None)].into());
586        let seen = lock(&seen).clone();
587        assert_eq!(seen.len(), 2, "the default's copy of lib.cache is ignored");
588        assert_eq!(seen[0].1["lib.cache"], Some(json!(3)));
589        assert_eq!(seen[1].1["ui.theme"], None);
590    }
591
592    #[test]
593    fn a_file_store_round_trips_at_the_host_s_path() {
594        let dir = std::env::temp_dir().join(format!("egui-pop-file-store-{}", std::process::id()));
595        let path = dir.join("nested").join("library.json");
596        let s = FileStore::new().file(LIB, &path);
597        assert_eq!(s.scopes(), [LIB]);
598        assert!(s.load(LIB).unwrap().is_empty(), "no file yet");
599        s.save(
600            LIB,
601            &[
602                ("a.b".into(), Some(json!(1))),
603                ("c.d".into(), Some(json!("x"))),
604            ]
605            .into(),
606        )
607        .unwrap();
608        s.save(LIB, &[("a.b".into(), None)].into()).unwrap();
609        assert_eq!(s.load(LIB).unwrap(), values(&[("c.d", json!("x"))]));
610        assert!(s.load(ValueScope::App).is_err(), "no path given");
611        std::fs::remove_dir_all(&dir).ok();
612    }
613
614    #[test]
615    fn diff_and_apply_agree() {
616        let a = values(&[("x", json!(1)), ("y", json!(2))]);
617        let b = values(&[("y", json!(3)), ("z", json!(4))]);
618        let d = diff(&a, &b);
619        assert_eq!(d["x"], None);
620        let mut c = a.clone();
621        apply(&mut c, &d);
622        assert_eq!(c, b);
623    }
624}