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        let dir = dir.into();
37        fs::create_dir_all(&dir)?;
38        Ok(StillStore { dir })
39    }
40
41    /// The default store: `<local data dir>/clairlune/current` (Local AppData on
42    /// Windows, so large regenerated images never roam with the profile).
43    pub fn default_location() -> std::io::Result<Self> {
44        let base = crate::app_data_dir().ok_or_else(|| {
45            std::io::Error::new(std::io::ErrorKind::NotFound, "no data directory")
46        })?;
47        Self::new(base.join("current"))
48    }
49
50    pub fn dir(&self) -> &Path {
51        &self.dir
52    }
53
54    /// Writes a still for a monitor under a new, absolute file name.
55    pub fn write(&self, monitor_id: &str, png: &[u8]) -> std::io::Result<PathBuf> {
56        let ms = SystemTime::now()
57            .duration_since(UNIX_EPOCH)
58            .map(|d| d.as_millis())
59            .unwrap_or(0);
60        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
61        let path = self
62            .dir
63            .join(format!("{}-{ms}-{n}.png", monitor_key(monitor_id)));
64        let tmp = path.with_extension("png.part");
65        fs::write(&tmp, png)?;
66        fs::rename(&tmp, &path)?;
67        std::path::absolute(&path)
68    }
69
70    /// Saves the wallpaper `restore` returns to, unless it is Clairlune's own
71    /// (every monitor showing a still from this store). So the user's wallpaper
72    /// is remembered on the first takeover, and a wallpaper they pick later
73    /// replaces it, but Clairlune never remembers itself.
74    pub fn remember_if_users(&self, snapshot: &Snapshot) -> std::io::Result<bool> {
75        let ours = !snapshot.monitors.is_empty()
76            && snapshot
77                .monitors
78                .iter()
79                .all(|(_, p)| p.as_deref().is_some_and(|p| p.starts_with(&self.dir)));
80        if ours {
81            return Ok(false);
82        }
83        let json = serde_json::to_string_pretty(snapshot).map_err(std::io::Error::other)?;
84        let tmp = self.dir.join(format!("{SNAPSHOT_FILE}.part"));
85        fs::write(&tmp, json)?;
86        fs::rename(tmp, self.dir.join(SNAPSHOT_FILE))?;
87        Ok(true)
88    }
89
90    /// The saved pre-Clairlune wallpaper, if any.
91    pub fn original(&self) -> std::io::Result<Option<Snapshot>> {
92        let path = self.dir.join(SNAPSHOT_FILE);
93        match fs::read_to_string(&path) {
94            Ok(text) => serde_json::from_str(&text)
95                .map(Some)
96                .map_err(std::io::Error::other),
97            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
98            Err(e) => Err(e),
99        }
100    }
101
102    /// Forgets the saved wallpaper (after restoring it).
103    pub fn forget_original(&self) -> std::io::Result<()> {
104        match fs::remove_file(self.dir.join(SNAPSHOT_FILE)) {
105            Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
106            _ => Ok(()),
107        }
108    }
109
110    /// Deletes every still for every monitor (after restoring).
111    pub fn clear_stills(&self) -> usize {
112        let Ok(entries) = fs::read_dir(&self.dir) else {
113            return 0;
114        };
115        entries
116            .flatten()
117            .filter(|e| e.path().extension().is_some_and(|x| x == "png"))
118            .filter(|e| fs::remove_file(e.path()).is_ok())
119            .count()
120    }
121
122    /// Deletes this monitor's other stills, keeping `keep`. Files that are
123    /// still locked (the OS may hold the old one briefly) are left for next time.
124    pub fn prune(&self, monitor_id: &str, keep: &Path) -> usize {
125        let prefix = format!("{}-", monitor_key(monitor_id));
126        let keep_name = keep.file_name();
127        let mut removed = 0;
128        let Ok(entries) = fs::read_dir(&self.dir) else {
129            return 0;
130        };
131        for e in entries.flatten() {
132            let name = e.file_name();
133            let is_ours = name.to_string_lossy().starts_with(&prefix);
134            if is_ours && Some(name.as_os_str()) != keep_name && fs::remove_file(e.path()).is_ok() {
135                removed += 1;
136            }
137        }
138        removed
139    }
140}
141
142/// A short, file-name-safe key for a monitor id (device paths contain `\`,
143/// `#`, `{` and the like).
144pub fn monitor_key(monitor_id: &str) -> String {
145    format!(
146        "{:016x}",
147        clairlune_scene::hash::hash_bytes(monitor_id.as_bytes())
148    )
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    fn temp_store(name: &str) -> StillStore {
156        let dir = std::env::temp_dir().join(format!(
157            "clairlune-store-test-{name}-{}",
158            std::process::id()
159        ));
160        let _ = fs::remove_dir_all(&dir);
161        StillStore::new(dir).unwrap()
162    }
163
164    #[test]
165    fn every_write_gets_a_new_name_and_prune_keeps_the_current_one() {
166        let s = temp_store("names");
167        let a = s.write(r"\\?\DISPLAY#ABC#1", b"one").unwrap();
168        let b = s.write(r"\\?\DISPLAY#ABC#1", b"two").unwrap();
169        let other = s.write(r"\\?\DISPLAY#XYZ#2", b"three").unwrap();
170        assert_ne!(a, b);
171        assert!(a.is_absolute());
172        assert_eq!(s.prune(r"\\?\DISPLAY#ABC#1", &b), 1);
173        assert!(!a.exists() && b.exists() && other.exists());
174        assert_eq!(fs::read(&b).unwrap(), b"two");
175        fs::remove_dir_all(s.dir()).unwrap();
176    }
177
178    #[test]
179    fn remembers_the_users_wallpaper_never_its_own() {
180        let s = temp_store("snap");
181        let original = Snapshot {
182            monitors: vec![
183                ("m1".into(), Some(PathBuf::from(r"C:\pics\sea.jpg"))),
184                ("m2".into(), None),
185            ],
186            position: Some(4),
187        };
188        let ours = Snapshot {
189            monitors: vec![
190                ("m1".into(), Some(s.dir().join("a.png"))),
191                ("m2".into(), Some(s.dir().join("b.png"))),
192            ],
193            position: Some(4),
194        };
195        let later = Snapshot {
196            monitors: vec![("m1".into(), Some(PathBuf::from(r"C:\pics\new.jpg")))],
197            position: Some(2),
198        };
199        assert!(s.remember_if_users(&original).unwrap());
200        assert!(!s.remember_if_users(&ours).unwrap());
201        assert_eq!(s.original().unwrap(), Some(original));
202        assert!(s.remember_if_users(&later).unwrap());
203        assert_eq!(s.original().unwrap(), Some(later));
204        s.forget_original().unwrap();
205        assert_eq!(s.original().unwrap(), None);
206        fs::remove_dir_all(s.dir()).unwrap();
207    }
208
209    #[test]
210    fn monitor_keys_are_file_name_safe_and_stable() {
211        let k = monitor_key(r"\\?\DISPLAY#DEL40F7#5&2b3e0f3&0&UID4352#{e6f07b5f}");
212        assert_eq!(k.len(), 16);
213        assert!(k.chars().all(|c| c.is_ascii_hexdigit()));
214        assert_eq!(
215            k,
216            monitor_key(r"\\?\DISPLAY#DEL40F7#5&2b3e0f3&0&UID4352#{e6f07b5f}")
217        );
218    }
219}