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