agg_gui/persistence.rs
1//! Small persistence helpers shared across platform harnesses.
2//!
3//! Both the native (disk) and wasm (localStorage) harnesses follow the
4//! same auto-save policy: each frame, serialize the current session
5//! state, compare to the last-persisted blob, and write only when they
6//! differ AND no mouse button is currently held. The "no mouse held"
7//! guard keeps us from hammering the backend while the user is
8//! mid-drag / mid-resize.
9//!
10//! This module owns the diff-and-save policy so hosts don't reimplement
11//! it. Callers plug in their own serializer and persist backend via
12//! closures — [`AutoSave::tick`] takes care of the rest.
13
14/// Tracks the last-persisted serialized blob so the platform harness
15/// can avoid writing unchanged state every frame.
16///
17/// # Example (pseudo-Rust)
18/// ```ignore
19/// let mut auto_save = AutoSave::new();
20/// loop {
21/// paint_frame();
22/// auto_save.tick(
23/// mouse_buttons_held == 0,
24/// || state.serialize(),
25/// |blob| std::fs::write("state.json", blob).ok(),
26/// );
27/// }
28/// ```
29#[derive(Default)]
30pub struct AutoSave {
31 last_saved: String,
32}
33
34impl AutoSave {
35 /// Create an empty auto-save tracker. First `tick` call will always
36 /// persist (because the last-saved blob is empty).
37 pub const fn new() -> Self {
38 Self {
39 last_saved: String::new(),
40 }
41 }
42
43 /// Consider persisting the current state.
44 ///
45 /// `idle` — guard that must be `true` for the save to happen.
46 /// Typically `mouse_buttons_held == 0`; callers can layer other
47 /// conditions (e.g. "no in-flight drag").
48 ///
49 /// `serialize_now` — closure that produces the current serialized
50 /// blob. Only invoked when `idle` is `true`.
51 ///
52 /// `persist` — closure that writes the blob to the platform backend
53 /// (file / localStorage / network). Only invoked when the blob
54 /// differs from the last persisted version.
55 ///
56 /// Returns `true` iff the persist closure was called.
57 pub fn tick<S, P>(&mut self, idle: bool, serialize_now: S, persist: P) -> bool
58 where
59 S: FnOnce() -> String,
60 P: FnOnce(&str),
61 {
62 if !idle {
63 return false;
64 }
65 let blob = serialize_now();
66 if blob == self.last_saved {
67 return false;
68 }
69 persist(&blob);
70 self.last_saved = blob;
71 true
72 }
73
74 /// Seed the tracker with a blob that's already on disk (on startup).
75 /// Prevents the first `tick` from writing the same content back to
76 /// the backend unnecessarily.
77 pub fn seed(&mut self, last_saved: String) {
78 self.last_saved = last_saved;
79 }
80}