Skip to main content

egui_pop_api/admin/
sync.rs

1//! The Settings app and the host's store: loading, saving away from the
2//! UI thread, following changes made elsewhere, keeping the errors to
3//! show ([`super::store`]).
4
5use std::collections::{BTreeMap, BTreeSet};
6use std::sync::atomic::{AtomicUsize, Ordering};
7use std::sync::{Arc, Mutex};
8
9use egui_pop_core::lock;
10use egui_pop_model::admin::ValueScope;
11use egui_pop_model::admin::layers::Layers;
12use egui_pop_model::ids::SettingId;
13
14use super::store::{Changes, SettingsStore, Values, apply, diff};
15use super::{Admin, write};
16use crate::app::AppHandle;
17
18/// Who wrote a change the store read or another of its clients made, as
19/// `pop.settings.changed` says it.
20pub(crate) const BY_STORE: &str = "store";
21
22/// What the store's threads (its worker, its watchers) hand to the UI
23/// thread.
24#[derive(Default)]
25pub(super) struct Shared {
26    /// To wake the UI thread.
27    ctx: Mutex<Option<egui::Context>>,
28    /// Changes made elsewhere, applied at the next pass.
29    events: Mutex<Vec<(ValueScope, Changes)>>,
30    /// The last failed load or save of each scope.
31    errors: Mutex<BTreeMap<ValueScope, String>>,
32    /// Saves sent and not done.
33    pending: AtomicUsize,
34}
35
36impl Shared {
37    fn wake(&self) {
38        if let Some(ctx) = lock(&self.ctx).as_ref() {
39            ctx.request_repaint();
40        }
41    }
42
43    fn done(&self, scope: ValueScope, result: Result<(), String>) {
44        match result {
45            Ok(()) => {
46                lock(&self.errors).remove(&scope);
47            }
48            Err(e) => {
49                log::warn!(target: "egui_pop", "settings: {} not saved: {e}", scope.name());
50                lock(&self.errors).insert(scope, e);
51            }
52        }
53        self.pending.fetch_sub(1, Ordering::AcqRel);
54        self.wake();
55    }
56}
57
58/// The UI thread's side.
59#[derive(Default)]
60pub(super) struct Synced {
61    store: Option<Arc<dyn SettingsStore>>,
62    /// The worker saving in order, away from the UI thread.
63    worker: Option<std::sync::mpsc::Sender<(ValueScope, Changes)>>,
64    /// Each scope's values as the store holds them: the last loaded or
65    /// saved. A scope not loaded yet is not saved.
66    kept: BTreeMap<ValueScope, Values>,
67    /// Scopes to read at the next pass.
68    to_load: BTreeSet<ValueScope>,
69    /// Scopes followed.
70    watched: BTreeSet<ValueScope>,
71    /// The value store's sequence and the layers when last compared.
72    seen: Option<(u64, Layers)>,
73}
74
75impl Admin {
76    /// Gives the Settings app the host's store: its scopes are read at
77    /// the next pass (a host scope once offered), what changes is saved to
78    /// it, and its changes made elsewhere are followed. Replaces a store
79    /// attached before.
80    pub fn attach_store(&self, store: impl SettingsStore + 'static) {
81        let store: Arc<dyn SettingsStore> = Arc::new(store);
82        let mut s = lock(&self.sync);
83        s.to_load = store.scopes().into_iter().collect();
84        s.kept.clear();
85        s.watched.clear();
86        s.seen = None;
87        s.worker = None;
88        s.store = Some(store);
89        lock(&self.shared.errors).clear();
90    }
91
92    /// Whether the host gave a store.
93    pub fn has_store(&self) -> bool {
94        lock(&self.sync).store.is_some()
95    }
96
97    /// Reads a scope from the store again at the next pass (the host
98    /// opened another library): what it holds replaces the layer.
99    pub fn reload(&self, scope: ValueScope) {
100        let mut s = lock(&self.sync);
101        if s.store
102            .as_ref()
103            .is_some_and(|st| st.scopes().contains(&scope))
104        {
105            s.to_load.insert(scope);
106        }
107    }
108
109    /// The store's errors to show: a failed load or save, by scope, and
110    /// its other problems (a setting two handlers claim).
111    pub fn store_errors(&self) -> Vec<(Option<ValueScope>, String)> {
112        let mut out: Vec<(Option<ValueScope>, String)> = lock(&self.shared.errors)
113            .iter()
114            .map(|(s, e)| (Some(*s), e.clone()))
115            .collect();
116        if let Some(store) = lock(&self.sync).store.clone() {
117            out.extend(store.problems().into_iter().map(|p| (None, p)));
118        }
119        out
120    }
121
122    /// Whether saves are on their way to the store.
123    pub fn saving(&self) -> bool {
124        self.shared.pending.load(Ordering::Acquire) > 0
125    }
126
127    /// Whether the values changed here last only the session: no store,
128    /// and neither the application's settings file nor the host's own
129    /// layer handling keeps them.
130    pub fn session_only(&self, app: &AppHandle) -> bool {
131        !self.has_store()
132            && !self.legacy.load(Ordering::Relaxed)
133            && (app.persist().is_none() || self.offered().len() > 1)
134    }
135
136    /// One pass: saves what changed since the last, reads the scopes to
137    /// read, applies the changes made elsewhere.
138    pub(crate) fn sync(&self, app: &AppHandle, ctx: &egui::Context) {
139        let Some(store) = lock(&self.sync).store.clone() else {
140            return;
141        };
142        {
143            let mut c = lock(&self.shared.ctx);
144            if c.is_none() {
145                *c = Some(ctx.clone());
146            }
147        }
148        self.follow(&store);
149        self.save_changes(app, &store);
150        let to_load = std::mem::take(&mut lock(&self.sync).to_load);
151        for scope in to_load {
152            let _writing = crate::bus::settings::writing(scope.name(), Some(BY_STORE));
153            self.load_scope(app, &store, scope);
154        }
155        let events = std::mem::take(&mut *lock(&self.shared.events));
156        let applied = !events.is_empty();
157        for (scope, changes) in events {
158            let _writing = crate::bus::settings::writing(scope.name(), Some(BY_STORE));
159            self.apply_elsewhere(app, &store, scope, &changes);
160        }
161        if applied {
162            // What was applied is what the store holds: nothing goes back.
163            self.mark_seen(app);
164        }
165        // What the store held or another client changed is said on the
166        // bus now: its followers follow it in the pass it is heard.
167        app.deliver_settings();
168    }
169
170    /// Follows every scope of the store not followed yet.
171    fn follow(&self, store: &Arc<dyn SettingsStore>) {
172        let new: Vec<ValueScope> = {
173            let mut s = lock(&self.sync);
174            store
175                .scopes()
176                .into_iter()
177                .filter(|sc| s.watched.insert(*sc))
178                .collect()
179        };
180        for scope in new {
181            let shared = self.shared.clone();
182            let r = store.watch(
183                scope,
184                Arc::new(move |scope, changes| {
185                    lock(&shared.events).push((scope, changes));
186                    shared.wake();
187                }),
188            );
189            if let Err(e) = r {
190                lock(&self.shared.errors).insert(scope, e);
191            }
192        }
193    }
194
195    /// Whether a scope is held now: `app` always, a host scope offered.
196    fn live(&self, scope: ValueScope) -> bool {
197        scope == ValueScope::App || self.offered().contains(&scope)
198    }
199
200    /// The values of a scope the store keeps, as shown now: `app`'s are
201    /// the user's own (not those a layer above holds) away from their
202    /// default.
203    fn values_of(&self, app: &AppHandle, store: &dyn SettingsStore, scope: ValueScope) -> Values {
204        if scope != ValueScope::App {
205            return self
206                .layer_values(scope)
207                .into_iter()
208                .filter(|(k, _)| store.claims(k))
209                .collect();
210        }
211        let layers = lock(&self.layers).clone();
212        let st = app.store();
213        let st = lock(&st);
214        let mut out = Values::new();
215        for e in app.settings() {
216            let id = e.id.as_str();
217            if !store.claims(id) {
218                continue;
219            }
220            let Some(entry) = st.get(&e.path) else {
221                continue;
222            };
223            let v = layers.app_value(&e.path, &entry.value.to_json());
224            if v != entry.descriptor.default.to_json() {
225                out.insert(id.to_string(), v);
226            }
227        }
228        out
229    }
230
231    /// Sends what changed in each scope loaded since the last pass.
232    fn save_changes(&self, app: &AppHandle, store: &Arc<dyn SettingsStore>) {
233        let seq = lock(&app.store()).seq();
234        let layers = self.layers();
235        let changed = lock(&self.sync)
236            .seen
237            .as_ref()
238            .is_none_or(|(s, l)| *s != seq || *l != layers);
239        if !changed {
240            return;
241        }
242        let scopes: Vec<ValueScope> = lock(&self.sync).kept.keys().copied().collect();
243        for scope in scopes {
244            if !self.live(scope) {
245                continue;
246            }
247            let now = self.values_of(app, store.as_ref(), scope);
248            let changes = {
249                let mut s = lock(&self.sync);
250                let kept = s.kept.entry(scope).or_default();
251                let d = diff(kept, &now);
252                *kept = now;
253                d
254            };
255            if !changes.is_empty() {
256                // Changed here, by the person: offered among the recent
257                // ones in the quick settings.
258                self.note_changed(changes.keys().map(String::as_str), super::quick::now());
259                self.send(store, scope, changes);
260            }
261        }
262        lock(&self.sync).seen = Some((seq, layers));
263    }
264
265    /// Saves away from the UI thread, in order (at once on the web, or
266    /// when no thread starts).
267    fn send(&self, store: &Arc<dyn SettingsStore>, scope: ValueScope, changes: Changes) {
268        self.shared.pending.fetch_add(1, Ordering::AcqRel);
269        let mut s = lock(&self.sync);
270        #[cfg(not(target_arch = "wasm32"))]
271        if s.worker.is_none() {
272            let (tx, rx) = std::sync::mpsc::channel::<(ValueScope, Changes)>();
273            let store = store.clone();
274            let shared = self.shared.clone();
275            let spawned = std::thread::Builder::new()
276                .name("egui-pop-settings-store".into())
277                .spawn(move || {
278                    for (scope, changes) in rx {
279                        let r = store.save(scope, &changes);
280                        shared.done(scope, r);
281                    }
282                });
283            match spawned {
284                Ok(_) => s.worker = Some(tx),
285                Err(e) => log::warn!(target: "egui_pop", "settings: no thread to save: {e}"),
286            }
287        }
288        let job = match s.worker.as_ref() {
289            Some(tx) => match tx.send((scope, changes)) {
290                Ok(()) => return,
291                Err(e) => e.0,
292            },
293            None => (scope, changes),
294        };
295        s.worker = None;
296        drop(s);
297        let r = store.save(job.0, &job.1);
298        self.shared.done(job.0, r);
299    }
300
301    /// Reads a scope from the store: its values replace the layer's (or
302    /// the user's own, for `app`); a host scope not offered is taken
303    /// back.
304    fn load_scope(&self, app: &AppHandle, store: &Arc<dyn SettingsStore>, scope: ValueScope) {
305        if !self.live(scope) {
306            self.put_layer(app, scope, BTreeMap::new());
307            lock(&self.sync).kept.remove(&scope);
308            self.mark_seen(app);
309            return;
310        }
311        let values = match store.load(scope) {
312            Ok(v) => {
313                lock(&self.shared.errors).remove(&scope);
314                v
315            }
316            Err(e) => {
317                log::warn!(target: "egui_pop", "settings: {} not loaded: {e}", scope.name());
318                lock(&self.shared.errors).insert(scope, e);
319                // Not loaded: not saved over either.
320                lock(&self.sync).kept.remove(&scope);
321                return;
322            }
323        };
324        let values: Values = values
325            .into_iter()
326            .filter(|(k, _)| store.claims(k))
327            .collect();
328        if scope == ValueScope::App {
329            let now = self.values_of(app, store.as_ref(), scope);
330            let mut changes = diff(&now, &values);
331            // A setting the store has no word on keeps its value.
332            changes.retain(|_, v| v.is_some());
333            self.set_app(app, &changes);
334        } else {
335            self.put_layer(app, scope, values);
336        }
337        let kept = self.values_of(app, store.as_ref(), scope);
338        lock(&self.sync).kept.insert(scope, kept);
339        self.mark_seen(app);
340    }
341
342    /// Applies a change made elsewhere to a scope held now.
343    fn apply_elsewhere(
344        &self,
345        app: &AppHandle,
346        store: &Arc<dyn SettingsStore>,
347        scope: ValueScope,
348        changes: &Changes,
349    ) {
350        if !self.live(scope) || !lock(&self.sync).kept.contains_key(&scope) {
351            return;
352        }
353        if scope == ValueScope::App {
354            self.set_app(app, changes);
355        } else {
356            let mut values = self.layer_values(scope);
357            apply(&mut values, changes);
358            self.put_layer(app, scope, values);
359        }
360        let kept = self.values_of(app, store.as_ref(), scope);
361        lock(&self.sync).kept.insert(scope, kept);
362    }
363
364    /// Sets the user's own values (`None`: the default), without an undo
365    /// step: a layer above keeps showing its own.
366    fn set_app(&self, app: &AppHandle, changes: &Changes) {
367        for (id, v) in changes {
368            let Ok(id) = SettingId::new(id) else { continue };
369            let path = id.path();
370            let (Ok(now), Ok(d)) = (super::current(app, &path), super::descriptor(app, &path))
371            else {
372                continue;
373            };
374            let target = v.clone().unwrap_or_else(|| d.default.to_json());
375            let w = lock(&self.layers).set(ValueScope::App, &path, target, &now);
376            if let Some(v) = w {
377                write(app, &path, &v);
378            }
379        }
380    }
381
382    /// The value store and layers as they are now count as saved.
383    fn mark_seen(&self, app: &AppHandle) {
384        let seq = lock(&app.store()).seq();
385        let layers = self.layers();
386        lock(&self.sync).seen = Some((seq, layers));
387    }
388}