Skip to main content

clairlune_platform/
store.rs

1//! Where stills live while they are the wallpaper.
2//!
3//! macOS and GNOME don't reload an unchanged path even when the file changed,
4//! so every still gets a new file name: `<monitor key>-<time>-<n>.png`. The
5//! previous files for that monitor are deleted only after the new one is set
6//! (PLAN.md section 2, "Unique file names").
7
8use serde::{Deserialize, Serialize};
9use std::fs;
10use std::path::{Path, PathBuf};
11use std::sync::atomic::{AtomicU64, Ordering};
12use std::time::{SystemTime, UNIX_EPOCH};
13
14/// The wallpaper as it was before Clairlune first set one, so it can be put
15/// back: each monitor's image (or none) and the system's fit mode.
16#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
17pub struct Snapshot {
18    /// Monitor id and its image path; `None` for a solid colour.
19    pub monitors: Vec<(String, Option<PathBuf>)>,
20    /// The OS fit mode (on Windows a `DESKTOP_WALLPAPER_POSITION` value).
21    pub position: Option<i32>,
22    /// The desktop's own wallpaper settings, word for word (Linux: each
23    /// `gsettings` key and its value, such as GNOME's separate dark-mode
24    /// picture and the picture options), put back as they were.
25    #[serde(default, skip_serializing_if = "Vec::is_empty")]
26    pub settings: Vec<(String, String)>,
27}
28
29const SNAPSHOT_FILE: &str = "previous-wallpaper.json";
30
31/// Disambiguates files written within the same millisecond.
32static COUNTER: AtomicU64 = AtomicU64::new(0);
33
34pub struct StillStore {
35    dir: PathBuf,
36}
37
38impl StillStore {
39    /// A store in `dir` (created when missing).
40    pub fn new(dir: impl Into<PathBuf>) -> std::io::Result<Self> {
41        // Absolute, like the paths `write` returns, so "is it ours" holds.
42        let dir = std::path::absolute(dir.into())?;
43        fs::create_dir_all(&dir)?;
44        Ok(StillStore { dir })
45    }
46
47    /// The default store: `<local data dir>/clairlune/current` (Local AppData on
48    /// Windows, so large regenerated images never roam with the profile).
49    pub fn default_location() -> std::io::Result<Self> {
50        let base = crate::app_data_dir().ok_or_else(|| {
51            std::io::Error::new(std::io::ErrorKind::NotFound, "no data directory")
52        })?;
53        Self::new(base.join("current"))
54    }
55
56    pub fn dir(&self) -> &Path {
57        &self.dir
58    }
59
60    /// Writes a still for a monitor under a new, absolute file name.
61    pub fn write(&self, monitor_id: &str, png: &[u8]) -> std::io::Result<PathBuf> {
62        let ms = SystemTime::now()
63            .duration_since(UNIX_EPOCH)
64            .map(|d| d.as_millis())
65            .unwrap_or(0);
66        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
67        let path = self
68            .dir
69            .join(format!("{}-{ms}-{n}.png", monitor_key(monitor_id)));
70        let tmp = path.with_extension("png.part");
71        fs::write(&tmp, png)?;
72        fs::rename(&tmp, &path)?;
73        std::path::absolute(&path)
74    }
75
76    /// Saves the wallpaper `restore` returns to, monitor by monitor: a
77    /// monitor showing the user's own image is remembered (a wallpaper they
78    /// pick later replaces the one saved), one showing a still of Clairlune's
79    /// keeps what was saved for it. So Clairlune never remembers itself, and
80    /// a monitor plugged in while it runs doesn't lose the others' originals.
81    /// Returns whether anything changed.
82    pub fn remember_if_users(&self, snapshot: &Snapshot) -> std::io::Result<bool> {
83        let ours = |p: &Option<PathBuf>| p.as_deref().is_some_and(|p| p.starts_with(&self.dir));
84        let users: Vec<_> = snapshot.monitors.iter().filter(|(_, p)| !ours(p)).collect();
85        if users.is_empty() {
86            // Clairlune's own on every monitor, or no monitors at all (all
87            // asleep): nothing of the user's to save.
88            return Ok(false);
89        }
90        let saved = self.original().ok().flatten();
91        let mut merged = saved.clone().unwrap_or_default();
92        for (id, path) in users {
93            match merged.monitors.iter_mut().find(|(m, _)| m == id) {
94                Some(entry) => entry.1.clone_from(path),
95                None => merged.monitors.push((id.clone(), path.clone())),
96            }
97        }
98        merged.monitors.retain(|(_, p)| !ours(p));
99        // The desktop's settings, but none naming one of Clairlune's stills.
100        let dir = self.dir.to_string_lossy();
101        let theirs: Vec<_> = snapshot
102            .settings
103            .iter()
104            .filter(|(_, v)| !v.contains(dir.as_ref()))
105            .cloned()
106            .collect();
107        for (k, v) in theirs {
108            match merged.settings.iter_mut().find(|(m, _)| *m == k) {
109                Some(entry) => entry.1 = v,
110                None => merged.settings.push((k, v)),
111            }
112        }
113        // The fit mode is the system's, for all monitors: it's the user's only
114        // when none shows Clairlune's (or nothing was saved yet).
115        if snapshot.monitors.iter().all(|(_, p)| !ours(p)) || merged.position.is_none() {
116            merged.position = snapshot.position;
117        }
118        if saved.as_ref() == Some(&merged) {
119            return Ok(false);
120        }
121        let json = serde_json::to_string_pretty(&merged).map_err(std::io::Error::other)?;
122        let tmp = self.dir.join(format!("{SNAPSHOT_FILE}.part"));
123        fs::write(&tmp, json)?;
124        fs::rename(tmp, self.dir.join(SNAPSHOT_FILE))?;
125        Ok(true)
126    }
127
128    /// The saved pre-Clairlune wallpaper, if any.
129    pub fn original(&self) -> std::io::Result<Option<Snapshot>> {
130        let path = self.dir.join(SNAPSHOT_FILE);
131        match fs::read_to_string(&path) {
132            Ok(text) => serde_json::from_str(&text)
133                .map(Some)
134                .map_err(std::io::Error::other),
135            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
136            Err(e) => Err(e),
137        }
138    }
139
140    /// Forgets the saved wallpaper (after restoring it).
141    pub fn forget_original(&self) -> std::io::Result<()> {
142        match fs::remove_file(self.dir.join(SNAPSHOT_FILE)) {
143            Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
144            _ => Ok(()),
145        }
146    }
147
148    /// Deletes every still for every monitor (after restoring).
149    pub fn clear_stills(&self) -> usize {
150        let Ok(entries) = fs::read_dir(&self.dir) else {
151            return 0;
152        };
153        entries
154            .flatten()
155            .filter(|e| e.path().extension().is_some_and(|x| x == "png"))
156            .filter(|e| fs::remove_file(e.path()).is_ok())
157            .count()
158    }
159
160    /// Deletes this monitor's other stills, keeping `keep`. Files that are
161    /// still locked (the OS may hold the old one briefly) are left for next time.
162    pub fn prune(&self, monitor_id: &str, keep: &Path) -> usize {
163        let prefix = format!("{}-", monitor_key(monitor_id));
164        let keep_name = keep.file_name();
165        let mut removed = 0;
166        let Ok(entries) = fs::read_dir(&self.dir) else {
167            return 0;
168        };
169        for e in entries.flatten() {
170            let name = e.file_name();
171            let is_ours = name.to_string_lossy().starts_with(&prefix);
172            if is_ours && Some(name.as_os_str()) != keep_name && fs::remove_file(e.path()).is_ok() {
173                removed += 1;
174            }
175        }
176        removed
177    }
178}
179
180/// A short, file-name-safe key for a monitor id (device paths contain `\`,
181/// `#`, `{` and the like).
182pub fn monitor_key(monitor_id: &str) -> String {
183    format!(
184        "{:016x}",
185        clairlune_scene::hash::hash_bytes(monitor_id.as_bytes())
186    )
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    fn temp_store(name: &str) -> StillStore {
194        let dir = std::env::temp_dir().join(format!(
195            "clairlune-store-test-{name}-{}",
196            std::process::id()
197        ));
198        let _ = fs::remove_dir_all(&dir);
199        StillStore::new(dir).unwrap()
200    }
201
202    #[test]
203    fn every_write_gets_a_new_name_and_prune_keeps_the_current_one() {
204        let s = temp_store("names");
205        let a = s.write(r"\\?\DISPLAY#ABC#1", b"one").unwrap();
206        let b = s.write(r"\\?\DISPLAY#ABC#1", b"two").unwrap();
207        let other = s.write(r"\\?\DISPLAY#XYZ#2", b"three").unwrap();
208        assert_ne!(a, b);
209        assert!(a.is_absolute());
210        assert_eq!(s.prune(r"\\?\DISPLAY#ABC#1", &b), 1);
211        assert!(!a.exists() && b.exists() && other.exists());
212        assert_eq!(fs::read(&b).unwrap(), b"two");
213        fs::remove_dir_all(s.dir()).unwrap();
214    }
215
216    #[test]
217    fn remembers_the_users_wallpaper_never_its_own() {
218        let s = temp_store("snap");
219        let original = Snapshot {
220            monitors: vec![
221                ("m1".into(), Some(PathBuf::from(r"C:\pics\sea.jpg"))),
222                ("m2".into(), None),
223            ],
224            position: Some(4),
225            settings: Vec::new(),
226        };
227        let ours = Snapshot {
228            monitors: vec![
229                ("m1".into(), Some(s.dir().join("a.png"))),
230                ("m2".into(), Some(s.dir().join("b.png"))),
231            ],
232            position: Some(4),
233            settings: Vec::new(),
234        };
235        let later = Snapshot {
236            monitors: vec![("m1".into(), Some(PathBuf::from(r"C:\pics\new.jpg")))],
237            position: Some(2),
238            settings: Vec::new(),
239        };
240        assert!(s.remember_if_users(&original).unwrap());
241        assert!(!s.remember_if_users(&ours).unwrap());
242        assert_eq!(s.original().unwrap(), Some(original));
243        assert!(s.remember_if_users(&later).unwrap());
244        // m2 wasn't there (unplugged): what was saved for it stays.
245        let both = Snapshot {
246            monitors: vec![
247                ("m1".into(), Some(PathBuf::from(r"C:\pics\new.jpg"))),
248                ("m2".into(), None),
249            ],
250            position: Some(2),
251            settings: Vec::new(),
252        };
253        assert_eq!(s.original().unwrap(), Some(both.clone()));
254        // Nothing to save from no monitors.
255        assert!(!s.remember_if_users(&Snapshot::default()).unwrap());
256        assert_eq!(s.original().unwrap(), Some(both));
257        s.forget_original().unwrap();
258        assert_eq!(s.original().unwrap(), None);
259        fs::remove_dir_all(s.dir()).unwrap();
260    }
261
262    #[test]
263    fn a_monitor_showing_clairlune_keeps_its_saved_original() {
264        let s = temp_store("mixed");
265        let a = PathBuf::from(r"C:\pics\a.jpg");
266        let b = PathBuf::from(r"C:\pics\b.jpg");
267        let first = Snapshot {
268            monitors: vec![("A".into(), Some(a.clone())), ("B".into(), Some(b.clone()))],
269            position: Some(4),
270            settings: Vec::new(),
271        };
272        assert!(s.remember_if_users(&first).unwrap());
273        // Clairlune on A only (`set --monitor A`), then remembered again.
274        let still = s.write("A", b"png").unwrap();
275        let mixed = Snapshot {
276            monitors: vec![("A".into(), Some(still)), ("B".into(), Some(b.clone()))],
277            position: Some(10),
278            settings: Vec::new(),
279        };
280        assert!(!s.remember_if_users(&mixed).unwrap());
281        assert_eq!(s.original().unwrap(), Some(first));
282        // A store made from a relative path still knows its own stills.
283        let rel = StillStore::new(std::path::Path::new("target").join("store-rel-test")).unwrap();
284        let mine = rel.write("A", b"png").unwrap();
285        let only_ours = Snapshot {
286            monitors: vec![("A".into(), Some(mine))],
287            position: None,
288            settings: Vec::new(),
289        };
290        assert!(!rel.remember_if_users(&only_ours).unwrap());
291        fs::remove_dir_all(rel.dir()).unwrap();
292        fs::remove_dir_all(s.dir()).unwrap();
293    }
294
295    #[test]
296    fn monitor_keys_are_file_name_safe_and_stable() {
297        let k = monitor_key(r"\\?\DISPLAY#DEL40F7#5&2b3e0f3&0&UID4352#{e6f07b5f}");
298        assert_eq!(k.len(), 16);
299        assert!(k.chars().all(|c| c.is_ascii_hexdigit()));
300        assert_eq!(
301            k,
302            monitor_key(r"\\?\DISPLAY#DEL40F7#5&2b3e0f3&0&UID4352#{e6f07b5f}")
303        );
304    }
305}