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 { last_saved: String::new() }
39 }
40
41 /// Consider persisting the current state.
42 ///
43 /// `idle` — guard that must be `true` for the save to happen.
44 /// Typically `mouse_buttons_held == 0`; callers can layer other
45 /// conditions (e.g. "no in-flight drag").
46 ///
47 /// `serialize_now` — closure that produces the current serialized
48 /// blob. Only invoked when `idle` is `true`.
49 ///
50 /// `persist` — closure that writes the blob to the platform backend
51 /// (file / localStorage / network). Only invoked when the blob
52 /// differs from the last persisted version.
53 ///
54 /// Returns `true` iff the persist closure was called.
55 pub fn tick<S, P>(
56 &mut self,
57 idle: bool,
58 serialize_now: S,
59 persist: P,
60 ) -> bool
61 where
62 S: FnOnce() -> String,
63 P: FnOnce(&str),
64 {
65 if !idle { return false; }
66 let blob = serialize_now();
67 if blob == self.last_saved { return false; }
68 persist(&blob);
69 self.last_saved = blob;
70 true
71 }
72
73 /// Seed the tracker with a blob that's already on disk (on startup).
74 /// Prevents the first `tick` from writing the same content back to
75 /// the backend unnecessarily.
76 pub fn seed(&mut self, last_saved: String) {
77 self.last_saved = last_saved;
78 }
79}