Skip to main content

egui_pop_model/admin/
layers.rs

1//! Value scopes: where a setting's value is set. `app` is this person on
2//! this machine (the settings store, as today) and the only scope a
3//! setting has unless it opts into more; the host application declares
4//! its own scopes above `app` (a project, a library, a workspace...),
5//! each later one winning over the earlier ones; `run` is the command
6//! line's overrides, above them all, shown, never edited.
7//!
8//! The store keeps the **effective** value at `settings/<id>`, so every
9//! reader (`AppHandle::setting`, bindings, listeners) sees it unchanged;
10//! [`Layers`] keeps the layers above `app`, and the `app` value of a path
11//! while a layer above holds it. Saving the user's settings takes the
12//! `app` values back ([`Layers::app_doc`]), so a scope's value never
13//! leaks into the user's file.
14//!
15//! Each change returns the effective value to write when it changes:
16//! the caller writes it (the model stays free of the store's locks).
17
18use std::collections::{BTreeMap, BTreeSet};
19use std::sync::{Mutex, OnceLock};
20
21use serde::{Deserialize, Deserializer, Serialize, Serializer};
22use serde_json::Value as Json;
23
24/// A layer of values, by name: `app` and `run` are egui-pop's, the
25/// others the host application's ([`ValueScope::new`]).
26#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
27pub struct ValueScope(&'static str);
28
29#[allow(
30    non_upper_case_globals,
31    reason = "the scopes read as names (`ValueScope::App`), like enum variants"
32)]
33impl ValueScope {
34    /// This person on this machine: the settings store.
35    pub const App: ValueScope = ValueScope("app");
36    /// The command line's overrides: shown as an origin, never edited.
37    pub const Run: ValueScope = ValueScope("run");
38    /// Helios's former built-in scope.
39    #[deprecated(
40        since = "0.8.0",
41        note = "declare the host's scopes with `ValueScope::new` and `Layers::declare`"
42    )]
43    pub const Library: ValueScope = ValueScope("library");
44    /// Helios's former built-in scope.
45    #[deprecated(
46        since = "0.8.0",
47        note = "declare the host's scopes with `ValueScope::new` and `Layers::declare`"
48    )]
49    pub const Workspace: ValueScope = ValueScope("workspace");
50
51    /// A host application's scope, by its name (`"library"`).
52    pub const fn new(name: &'static str) -> ValueScope {
53        ValueScope(name)
54    }
55
56    /// A scope from its name, as read from a file or a command's
57    /// arguments (a name not seen before is kept for the process).
58    pub fn named(name: &str) -> ValueScope {
59        static NAMES: OnceLock<Mutex<BTreeSet<&'static str>>> = OnceLock::new();
60        for known in ["app", "run"] {
61            if name == known {
62                return ValueScope(known);
63            }
64        }
65        let mut names = NAMES
66            .get_or_init(Mutex::default)
67            .lock()
68            .unwrap_or_else(std::sync::PoisonError::into_inner);
69        if let Some(n) = names.get(name) {
70            return ValueScope(n);
71        }
72        let n: &'static str = Box::leak(name.to_owned().into_boxed_str());
73        names.insert(n);
74        ValueScope(n)
75    }
76
77    pub fn name(self) -> &'static str {
78        self.0
79    }
80
81    pub fn editable(self) -> bool {
82        self != ValueScope::Run
83    }
84}
85
86impl Serialize for ValueScope {
87    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
88        s.serialize_str(self.0)
89    }
90}
91
92impl<'de> Deserialize<'de> for ValueScope {
93    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<ValueScope, D::Error> {
94        let name = String::deserialize(d)?;
95        Ok(ValueScope::named(&name))
96    }
97}
98
99/// The layers above `app`, by path.
100#[derive(Clone, Debug, Default, PartialEq, Serialize)]
101pub struct Layers {
102    /// The host's scopes above `app`, lowest first: a later one wins.
103    declared: Vec<ValueScope>,
104    /// The editable layers the application has open (`app` always).
105    offered: Vec<ValueScope>,
106    /// Each layer's values, `run` included.
107    layers: BTreeMap<ValueScope, BTreeMap<String, Json>>,
108    /// A path's `app` value while a layer above holds it.
109    app: BTreeMap<String, Json>,
110}
111
112impl Layers {
113    pub fn new() -> Layers {
114        Layers {
115            offered: vec![ValueScope::App],
116            ..Layers::default()
117        }
118    }
119
120    /// Declares a host scope above those declared before it (it wins over
121    /// them); declaring it again changes nothing. `app` and `run` are not
122    /// declared.
123    pub fn declare(&mut self, scope: ValueScope) {
124        if scope != ValueScope::App && scope != ValueScope::Run && !self.declared.contains(&scope) {
125            self.declared.push(scope);
126        }
127    }
128
129    /// The host's scopes, lowest first.
130    pub fn declared(&self) -> &[ValueScope] {
131        &self.declared
132    }
133
134    /// Every scope, lowest first: `app`, the host's, `run`.
135    pub fn stack(&self) -> Vec<ValueScope> {
136        let mut out = vec![ValueScope::App];
137        out.extend(self.declared.iter().copied());
138        out.push(ValueScope::Run);
139        out
140    }
141
142    /// Offers a host scope for editing (the application opened its
143    /// library, its workspace...), or takes it back. A scope not declared
144    /// yet is declared, above the others.
145    pub fn offer(&mut self, scope: ValueScope, on: bool) {
146        if !scope.editable() || scope == ValueScope::App {
147            return;
148        }
149        self.declare(scope);
150        self.offered.retain(|s| *s != scope);
151        if on {
152            self.offered.push(scope);
153        }
154        let order = self.stack();
155        self.offered
156            .sort_by_key(|s| order.iter().position(|o| o == s));
157    }
158
159    /// The editable layers open, lowest first.
160    pub fn offered(&self) -> &[ValueScope] {
161        &self.offered
162    }
163
164    fn map(&self, scope: ValueScope) -> Option<&BTreeMap<String, Json>> {
165        if scope == ValueScope::App {
166            return None;
167        }
168        self.layers.get(&scope)
169    }
170
171    fn map_mut(&mut self, scope: ValueScope) -> Option<&mut BTreeMap<String, Json>> {
172        if scope == ValueScope::App {
173            return None;
174        }
175        self.declare(scope);
176        Some(self.layers.entry(scope).or_default())
177    }
178
179    /// The layer the effective value comes from: the highest holding the
180    /// path, else `app`.
181    pub fn origin(&self, path: &str) -> ValueScope {
182        self.stack()
183            .into_iter()
184            .rev()
185            .find(|s| self.map(*s).is_some_and(|m| m.contains_key(path)))
186            .unwrap_or(ValueScope::App)
187    }
188
189    /// The scopes holding a value for the path, lowest first (`app` when
190    /// it differs from the default, as `store` and `default` say).
191    pub fn holders(&self, path: &str, store: &Json, default: &Json) -> Vec<ValueScope> {
192        let mut out = Vec::new();
193        if self.app_value(path, store) != *default {
194            out.push(ValueScope::App);
195        }
196        for s in self.stack().into_iter().skip(1) {
197            if self.map(s).is_some_and(|m| m.contains_key(path)) {
198                out.push(s);
199            }
200        }
201        out
202    }
203
204    /// A layer's own value for the path; `app`'s is the store's unless a
205    /// layer above holds the path.
206    pub fn value_in(&self, scope: ValueScope, path: &str, store: &Json) -> Option<Json> {
207        match scope {
208            ValueScope::App => Some(self.app_value(path, store)),
209            s => self.map(s).and_then(|m| m.get(path)).cloned(),
210        }
211    }
212
213    /// The `app` value: the one kept aside, else the store's.
214    pub fn app_value(&self, path: &str, store: &Json) -> Json {
215        self.app.get(path).cloned().unwrap_or_else(|| store.clone())
216    }
217
218    /// Sets a value in a layer. `store` is the store's value now. Returns
219    /// the effective value when it changes (the caller writes it).
220    /// `None` for `run` (set with [`Layers::set_run`]).
221    pub fn set(
222        &mut self,
223        scope: ValueScope,
224        path: &str,
225        value: Json,
226        store: &Json,
227    ) -> Option<Json> {
228        match scope {
229            ValueScope::Run => None,
230            ValueScope::App => {
231                if self.origin(path) == ValueScope::App {
232                    (value != *store).then_some(value)
233                } else {
234                    self.app.insert(path.into(), value);
235                    None
236                }
237            }
238            s => {
239                if self.origin(path) == ValueScope::App {
240                    self.app.insert(path.into(), store.clone());
241                }
242                self.map_mut(s)?.insert(path.into(), value);
243                let effective = self.effective(path)?;
244                (effective != *store).then_some(effective)
245            }
246        }
247    }
248
249    /// The command line's override of a path.
250    pub fn set_run(&mut self, path: &str, value: Json, store: &Json) -> Option<Json> {
251        if self.origin(path) == ValueScope::App {
252            self.app.insert(path.into(), store.clone());
253        }
254        self.layers
255            .entry(ValueScope::Run)
256            .or_default()
257            .insert(path.into(), value.clone());
258        (value != *store).then_some(value)
259    }
260
261    /// The value of the highest layer above `app` holding the path.
262    fn effective(&self, path: &str) -> Option<Json> {
263        let o = self.origin(path);
264        self.map(o).and_then(|m| m.get(path)).cloned()
265    }
266
267    /// Takes a layer's value back (its reset): `app` goes back to the
268    /// default. Returns the effective value when it changes.
269    pub fn clear(
270        &mut self,
271        scope: ValueScope,
272        path: &str,
273        store: &Json,
274        default: &Json,
275    ) -> Option<Json> {
276        match scope {
277            ValueScope::Run => None,
278            ValueScope::App => {
279                if self.origin(path) == ValueScope::App {
280                    (default != store).then(|| default.clone())
281                } else {
282                    self.app.insert(path.into(), default.clone());
283                    None
284                }
285            }
286            s => {
287                self.map_mut(s)?.remove(path)?;
288                let effective = match self.effective(path) {
289                    Some(v) => v,
290                    None => self.app.remove(path).unwrap_or_else(|| store.clone()),
291                };
292                (effective != *store).then_some(effective)
293            }
294        }
295    }
296
297    /// A layer's values (what the application saves with its library or
298    /// workspace).
299    pub fn export(&self, scope: ValueScope) -> BTreeMap<String, Json> {
300        self.map(scope).cloned().unwrap_or_default()
301    }
302
303    /// Replaces a layer's values (a library or workspace opened, or
304    /// closed with an empty map). `store` reads the store's value of a
305    /// path. Returns the effective values to write.
306    pub fn load(
307        &mut self,
308        scope: ValueScope,
309        values: BTreeMap<String, Json>,
310        store: &dyn Fn(&str) -> Option<Json>,
311    ) -> Vec<(String, Json)> {
312        if scope == ValueScope::App {
313            return Vec::new();
314        }
315        let mut paths: Vec<String> = self.export(scope).into_keys().collect();
316        paths.extend(values.keys().cloned());
317        paths.sort();
318        paths.dedup();
319        let mut writes = Vec::new();
320        for path in &paths {
321            let Some(now) = store(path) else { continue };
322            let before = self.origin(path);
323            if before == ValueScope::App {
324                self.app.insert(path.clone(), now.clone());
325            }
326            if let Some(m) = self.map_mut(scope) {
327                match values.get(path) {
328                    Some(v) => m.insert(path.clone(), v.clone()),
329                    None => m.remove(path),
330                };
331            }
332            let effective = match self.effective(path) {
333                Some(v) => v,
334                None => self.app.remove(path).unwrap_or_else(|| now.clone()),
335            };
336            if effective != now {
337                writes.push((path.clone(), effective));
338            }
339        }
340        writes
341    }
342
343    /// The user's settings document as it should be saved: the `app`
344    /// values in place of the effective ones. `default` reads a path's
345    /// default; a value at its default is left out.
346    pub fn app_doc(
347        &self,
348        values: &mut BTreeMap<String, Json>,
349        default: &dyn Fn(&str) -> Option<Json>,
350    ) {
351        for (path, v) in &self.app {
352            if default(path).as_ref() == Some(v) {
353                values.remove(path);
354            } else {
355                values.insert(path.clone(), v.clone());
356            }
357        }
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364    use serde_json::json;
365
366    const P: &str = "settings/appearance.theme";
367    const LIB: ValueScope = ValueScope::new("library");
368    const WS: ValueScope = ValueScope::new("workspace");
369
370    #[test]
371    fn the_host_declares_its_scopes_and_the_later_one_wins() {
372        let mut l = Layers::new();
373        // Declared workspace first: library wins over it.
374        l.declare(WS);
375        l.declare(LIB);
376        l.declare(WS);
377        assert_eq!(l.declared(), &[WS, LIB]);
378        l.offer(LIB, true);
379        l.offer(WS, true);
380        assert_eq!(l.offered(), &[ValueScope::App, WS, LIB]);
381        let mut store = json!(1);
382        store = l.set(LIB, P, json!(2), &store).unwrap();
383        assert_eq!(l.set(WS, P, json!(3), &store), None, "under the library");
384        assert_eq!(l.origin(P), LIB);
385        assert_eq!(l.holders(P, &store, &json!(1)), vec![WS, LIB]);
386        // The library's reset gives the workspace's value.
387        assert_eq!(l.clear(LIB, P, &store, &json!(1)), Some(json!(3)));
388    }
389
390    #[test]
391    fn a_scope_name_round_trips() {
392        let s: ValueScope = serde_json::from_value(json!("library")).unwrap();
393        assert_eq!(s, LIB);
394        assert_eq!(serde_json::to_value(ValueScope::App).unwrap(), json!("app"));
395        assert_eq!(ValueScope::named("run"), ValueScope::Run);
396    }
397
398    #[test]
399    fn a_layer_above_app_wins_and_its_reset_gives_app_back() {
400        let mut l = Layers::new();
401        l.offer(LIB, true);
402        l.offer(ValueScope::Run, true);
403        assert_eq!(l.offered(), &[ValueScope::App, LIB]);
404        let store = json!("dark");
405        // Library over app: the effective value changes.
406        assert_eq!(l.set(LIB, P, json!("light"), &store), Some(json!("light")));
407        let store = json!("light");
408        assert_eq!(l.origin(P), LIB);
409        assert_eq!(l.value_in(ValueScope::App, P, &store), Some(json!("dark")));
410        // Setting app under it changes nothing shown.
411        assert_eq!(l.set(ValueScope::App, P, json!("system"), &store), None);
412        // Saving the user's settings takes the app value.
413        let mut doc = BTreeMap::from([(P.to_string(), json!("light"))]);
414        l.app_doc(&mut doc, &|_| Some(json!("dark")));
415        assert_eq!(doc[P], json!("system"));
416        // The library's reset gives app's value back.
417        assert_eq!(
418            l.clear(LIB, P, &store, &json!("dark")),
419            Some(json!("system"))
420        );
421        assert_eq!(l.origin(P), ValueScope::App);
422        let mut doc = BTreeMap::new();
423        l.app_doc(&mut doc, &|_| Some(json!("dark")));
424        assert!(doc.is_empty(), "nothing kept aside any more");
425    }
426
427    #[test]
428    fn workspace_wins_over_library_and_run_over_both() {
429        let mut l = Layers::new();
430        let mut store = json!(1);
431        store = l.set(LIB, P, json!(2), &store).unwrap();
432        store = l.set(WS, P, json!(3), &store).unwrap();
433        assert_eq!(l.origin(P), WS);
434        assert_eq!(l.holders(P, &store, &json!(1)), vec![LIB, WS]);
435        store = l.set_run(P, json!(4), &store).unwrap();
436        assert_eq!(l.origin(P), ValueScope::Run);
437        assert_eq!(l.set(ValueScope::Run, P, json!(5), &store), None);
438        // The workspace's reset under run changes nothing shown.
439        assert_eq!(l.clear(WS, P, &store, &json!(1)), None);
440        assert_eq!(l.value_in(LIB, P, &store), Some(json!(2)));
441    }
442
443    #[test]
444    fn loading_a_layer_writes_what_changes() {
445        let mut l = Layers::new();
446        let store = |_: &str| Some(json!(1));
447        let w = l.load(WS, BTreeMap::from([(P.to_string(), json!(9))]), &store);
448        assert_eq!(w, vec![(P.to_string(), json!(9))]);
449        let store = |_: &str| Some(json!(9));
450        let w = l.load(WS, BTreeMap::new(), &store);
451        assert_eq!(w, vec![(P.to_string(), json!(1))]);
452        assert_eq!(l.origin(P), ValueScope::App);
453    }
454}