1use 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
34pub type Values = BTreeMap<String, Json>;
37
38pub type Changes = BTreeMap<String, Option<Json>>;
41
42pub type OnChange = Arc<dyn Fn(ValueScope, Changes) + Send + Sync>;
45
46pub trait SettingsStore: Send + Sync {
50 fn scopes(&self) -> Vec<ValueScope>;
52
53 fn claims(&self, _setting: &str) -> bool {
55 true
56 }
57
58 fn load(&self, scope: ValueScope) -> Result<Values, String>;
60
61 fn save(&self, scope: ValueScope, changes: &Changes) -> Result<(), String>;
64
65 fn watch(&self, _scope: ValueScope, _on_change: OnChange) -> Result<(), String> {
68 Ok(())
69 }
70
71 fn problems(&self) -> Vec<String> {
74 Vec::new()
75 }
76}
77
78pub 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
88pub 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
104pub 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 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 #[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 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 pub fn overlaps(&self) -> Vec<String> {
164 lock(&self.overlaps).iter().cloned().collect()
165 }
166
167 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 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 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#[derive(Debug, Default)]
308pub struct FileStore {
309 files: BTreeMap<ValueScope, PathBuf>,
310 writing: Mutex<()>,
312}
313
314impl FileStore {
315 pub fn new() -> FileStore {
316 FileStore::default()
317 }
318
319 #[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 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#[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 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 #[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 #[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 pub fn values(&self, scope: ValueScope) -> Values {
432 lock(&self.inner.values)
433 .get(&scope)
434 .cloned()
435 .unwrap_or_default()
436 }
437
438 pub fn saves(&self) -> Vec<(ValueScope, Changes)> {
440 lock(&self.inner.saves).clone()
441 }
442
443 pub fn fail_saves(&self, error: Option<&str>) {
445 *lock(&self.inner.fail) = error.map(str::to_string);
446 }
447
448 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 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 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 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}