clairlune 0.17.2

Procedural, animated ASCII-art desktop wallpapers. Local, seeded and deterministic; no AI, no network.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! The archive: every wallpaper set the app applied, kept for a while
//! (PLAN.md section 9).
//!
//! ```text
//! <data_dir>/archive/
//! ├── index.json
//! └── 2026-11-18T17-56-03Z_seed-1234567890/
//!     ├── recipe.json      one recipe per monitor
//!     ├── thumb.png        480 px wide, the primary monitor's scene
//!     ├── wallpaper-0.png  one per monitor, primary first
//!     └── scene/0/         the frozen scene package per monitor (PLAN.md 9c)
//! ```
//!
//! Retention deletes for good (never to the Trash, which would fill up every
//! hour): first unpinned entries older than the retention period, then the
//! oldest unpinned ones while over the size cap. The newest entry (the
//! wallpaper on screen) and pinned entries are never swept.
//!
//! Changes to `index.json` hold a lock (`index.lock`), since the worker, the
//! windows and the CLI may each change it at once. An index that is missing
//! or damaged is rebuilt from the entry folders, all of them pinned: which
//! ones the user pinned is lost, and retention mustn't delete those.

use clairlune_scene::SceneRecipe;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

/// One archived wallpaper set, as listed in `index.json`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Entry {
    /// Directory name: `<UTC stamp>_seed-<seed>`.
    pub name: String,
    /// Unix seconds.
    pub created: u64,
    /// The base seed (the primary monitor's).
    pub seed: u64,
    pub theme: String,
    /// The primary monitor's landscape and activity, for listings.
    pub archetype: String,
    pub activity: Option<String>,
    #[serde(default)]
    pub pinned: bool,
    pub bytes: u64,
}

/// One monitor's scene in an entry.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MonitorScene {
    pub monitor: String,
    pub width: u32,
    pub height: u32,
    pub recipe: SceneRecipe,
}

/// `recipe.json`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntryRecipes {
    pub base_seed: u64,
    pub theme: String,
    pub monitors: Vec<MonitorScene>,
}

/// What to archive: the recipes plus the rendered images.
pub struct NewEntry {
    pub created: u64,
    pub recipes: EntryRecipes,
    /// One PNG per monitor, in `recipes.monitors` order.
    pub pngs: Vec<Vec<u8>>,
    pub thumb_png: Vec<u8>,
    /// One frozen scene per monitor, in `recipes.monitors` order.
    pub packages: Vec<std::sync::Arc<clairlune_render::ScenePackage>>,
}

#[derive(Default, Serialize, Deserialize)]
struct Index {
    /// Oldest first.
    entries: Vec<Entry>,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Sweep {
    pub removed: usize,
    pub freed: u64,
}

pub struct Archive {
    dir: PathBuf,
}

impl Archive {
    pub fn open(dir: impl Into<PathBuf>) -> io::Result<Self> {
        let dir = dir.into();
        fs::create_dir_all(&dir)?;
        Ok(Archive { dir })
    }

    pub fn dir(&self) -> &Path {
        &self.dir
    }

    fn index_path(&self) -> PathBuf {
        self.dir.join("index.json")
    }

    fn load_index(&self) -> Index {
        match fs::read_to_string(self.index_path()) {
            Ok(t) => match serde_json::from_str(&t) {
                Ok(index) => index,
                Err(e) => {
                    tracing::warn!(target: "clairlune", error = %e, "archive index damaged; rebuilding it from the folders");
                    let _ = fs::write(self.dir.join("index.json.bad"), &t);
                    self.rebuild()
                }
            },
            Err(e) if e.kind() == io::ErrorKind::NotFound => self.rebuild(),
            Err(_) => Index::default(),
        }
    }

    /// The index from the entry folders (those with a `recipe.json`), for
    /// when `index.json` is gone or damaged.
    fn rebuild(&self) -> Index {
        let mut entries: Vec<Entry> = fs::read_dir(&self.dir)
            .into_iter()
            .flatten()
            .flatten()
            .filter_map(|d| {
                let dir = d.path();
                let name = d.file_name().to_str()?.to_string();
                let text = fs::read_to_string(dir.join("recipe.json")).ok()?;
                let recipes: EntryRecipes = serde_json::from_str(&text).ok()?;
                let created = d
                    .metadata()
                    .and_then(|m| m.modified())
                    .ok()
                    .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                    .map_or(0, |d| d.as_secs());
                let primary = recipes.monitors.first();
                Some(Entry {
                    created,
                    seed: recipes.base_seed,
                    theme: recipes.theme.clone(),
                    archetype: primary
                        .map(|m| m.recipe.archetype.clone())
                        .unwrap_or_default(),
                    activity: primary.and_then(|m| m.recipe.activity.clone()),
                    pinned: true,
                    bytes: dir_size(&dir),
                    name,
                })
            })
            .collect();
        // Names start with the UTC time they were made: they sort in order.
        entries.sort_by(|a, b| a.name.cmp(&b.name));
        Index { entries }
    }

    fn save_index(&self, index: &Index) -> io::Result<()> {
        // A name of its own, so two writers never share a half-written file.
        static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let tmp = self
            .dir
            .join(format!("index.json.{}-{n}.part", std::process::id()));
        fs::write(&tmp, serde_json::to_string_pretty(index)?)?;
        fs::rename(&tmp, self.index_path()).inspect_err(|_| {
            let _ = fs::remove_file(&tmp);
        })
    }

    /// Holds the index for a read-change-write (released when dropped).
    fn lock(&self) -> io::Result<fs::File> {
        let file = fs::OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(self.dir.join("index.lock"))?;
        file.lock()?;
        Ok(file)
    }

    /// Entries, oldest first.
    pub fn entries(&self) -> Vec<Entry> {
        self.load_index().entries
    }

    /// The newest entry (the wallpaper on screen, when the app set it).
    pub fn latest(&self) -> Option<Entry> {
        self.entries().pop()
    }

    /// The entry before `name`, for "Previous wallpaper".
    pub fn before(&self, name: &str) -> Option<Entry> {
        let entries = self.entries();
        let i = entries.iter().position(|e| e.name == name)?;
        i.checked_sub(1).map(|j| entries[j].clone())
    }

    /// Writes an entry and lists it.
    pub fn add(&self, new: &NewEntry) -> io::Result<Entry> {
        // Held from picking the name on, so two adds can't pick the same.
        let _lock = self.lock()?;
        let base = format!(
            "{}_seed-{}",
            crate::timefmt::stamp(new.created),
            new.recipes.base_seed
        );
        let mut name = base.clone();
        let mut n = 2;
        while self.dir.join(&name).exists() {
            name = format!("{base}-{n}");
            n += 1;
        }
        let dir = self.dir.join(&name);
        fs::create_dir_all(&dir)?;
        fs::write(
            dir.join("recipe.json"),
            serde_json::to_string_pretty(&new.recipes)?,
        )?;
        fs::write(dir.join("thumb.png"), &new.thumb_png)?;
        for (i, png) in new.pngs.iter().enumerate() {
            fs::write(dir.join(format!("wallpaper-{i}.png")), png)?;
        }
        for (i, pkg) in new.packages.iter().enumerate() {
            pkg.save(&dir.join("scene").join(i.to_string()))
                .map_err(io::Error::other)?;
        }
        let primary = new.recipes.monitors.first();
        let entry = Entry {
            name,
            created: new.created,
            seed: new.recipes.base_seed,
            theme: new.recipes.theme.clone(),
            archetype: primary
                .map(|m| m.recipe.archetype.clone())
                .unwrap_or_default(),
            activity: primary.and_then(|m| m.recipe.activity.clone()),
            pinned: false,
            bytes: dir_size(&dir),
        };
        let mut index = self.load_index();
        // Rebuilt from the folders just now, it's listed already (roughly).
        index.entries.retain(|e| e.name != entry.name);
        index.entries.push(entry.clone());
        self.save_index(&index)?;
        Ok(entry)
    }

    /// An entry by name.
    pub fn get(&self, name: &str) -> Option<Entry> {
        self.entries().into_iter().find(|e| e.name == name)
    }

    /// Pins an entry (retention never removes it) or unpins it.
    pub fn set_pinned(&self, name: &str, pinned: bool) -> io::Result<()> {
        let _lock = self.lock()?;
        let mut index = self.load_index();
        let e = index
            .entries
            .iter_mut()
            .find(|e| e.name == name)
            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, name.to_string()))?;
        e.pinned = pinned;
        self.save_index(&index)
    }

    /// Deletes an entry for good.
    pub fn delete(&self, name: &str) -> io::Result<()> {
        let _lock = self.lock()?;
        let mut index = self.load_index();
        match fs::remove_dir_all(self.dir.join(name)) {
            Ok(()) => {}
            Err(e) if e.kind() == io::ErrorKind::NotFound => {}
            Err(e) => return Err(e),
        }
        index.entries.retain(|e| e.name != name);
        self.save_index(&index)
    }

    /// The recipes of an entry.
    #[cfg(test)]
    pub fn recipes(&self, entry: &Entry) -> io::Result<EntryRecipes> {
        let text = fs::read_to_string(self.dir.join(&entry.name).join("recipe.json"))?;
        serde_json::from_str(&text).map_err(io::Error::other)
    }

    /// Applies retention: unpinned entries older than `keep_days` (0 keeps
    /// forever), then the oldest unpinned while their total exceeds `max_bytes`.
    pub fn sweep(&self, now: u64, keep_days: u32, max_bytes: u64) -> Sweep {
        let Ok(_lock) = self.lock() else {
            return Sweep::default();
        };
        let mut index = self.load_index();
        let newest = index.entries.last().map(|e| e.name.clone());
        let sweepable = |e: &Entry| !e.pinned && Some(&e.name) != newest.as_ref();
        let mut doomed: Vec<String> = Vec::new();
        if keep_days > 0 {
            let cutoff = now.saturating_sub(u64::from(keep_days) * 86_400);
            doomed.extend(
                index
                    .entries
                    .iter()
                    .filter(|e| sweepable(e) && e.created < cutoff)
                    .map(|e| e.name.clone()),
            );
        }
        let mut total: u64 = index
            .entries
            .iter()
            .filter(|e| !e.pinned && !doomed.contains(&e.name))
            .map(|e| e.bytes)
            .sum();
        for e in &index.entries {
            if total <= max_bytes {
                break;
            }
            if sweepable(e) && !doomed.contains(&e.name) {
                total -= e.bytes;
                doomed.push(e.name.clone());
            }
        }
        let mut report = Sweep::default();
        index.entries.retain(|e| {
            if !doomed.contains(&e.name) {
                return true;
            }
            match fs::remove_dir_all(self.dir.join(&e.name)) {
                Ok(()) => {
                    report.removed += 1;
                    report.freed += e.bytes;
                    false
                }
                Err(err) if err.kind() == io::ErrorKind::NotFound => false,
                // Locked (being viewed?): keep it listed and try next sweep.
                Err(_) => true,
            }
        });
        if report.removed > 0 {
            let _ = self.save_index(&index);
        }
        report
    }
}

/// Bytes under `dir`, subfolders included.
fn dir_size(dir: &Path) -> u64 {
    fs::read_dir(dir)
        .map(|it| {
            it.flatten()
                .filter_map(|e| {
                    let m = e.metadata().ok()?;
                    Some(if m.is_dir() {
                        dir_size(&e.path())
                    } else {
                        m.len()
                    })
                })
                .sum()
        })
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;
    use clairlune_scene::{Aspect, ContentContext, compose};

    fn temp(name: &str) -> Archive {
        let d =
            std::env::temp_dir().join(format!("clairlune-archive-{name}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&d);
        Archive::open(d).unwrap()
    }

    fn entry(seed: u64, created: u64, bytes: usize) -> NewEntry {
        let recipe = compose(seed, Aspect::from_size(16, 9), &ContentContext::default());
        NewEntry {
            created,
            recipes: EntryRecipes {
                base_seed: seed,
                theme: "dark".into(),
                monitors: vec![MonitorScene {
                    monitor: "m0".into(),
                    width: 1920,
                    height: 1080,
                    recipe,
                }],
            },
            pngs: vec![vec![7; bytes]],
            thumb_png: vec![1; 10],
            packages: Vec::new(),
        }
    }

    const DAY: u64 = 86_400;

    #[test]
    fn add_lists_and_round_trips_recipes() {
        let a = temp("add");
        let e1 = a.add(&entry(1, 10 * DAY, 100)).unwrap();
        let e2 = a.add(&entry(2, 11 * DAY, 100)).unwrap();
        assert_eq!(a.entries(), vec![e1.clone(), e2.clone()]);
        assert_eq!(a.latest().unwrap().seed, 2);
        assert_eq!(a.before(&e2.name).unwrap().name, e1.name);
        assert!(a.before(&e1.name).is_none());
        let r = a.recipes(&e1).unwrap();
        assert_eq!(r.base_seed, 1);
        assert_eq!(
            r.monitors[0].recipe,
            entry(1, 0, 0).recipes.monitors[0].recipe
        );
        assert!(e1.bytes >= 110);
        fs::remove_dir_all(a.dir()).unwrap();
    }

    #[test]
    fn same_second_same_seed_gets_a_suffix() {
        let a = temp("dup");
        let x = a.add(&entry(5, DAY, 1)).unwrap();
        let y = a.add(&entry(5, DAY, 1)).unwrap();
        assert_ne!(x.name, y.name);
        assert!(y.name.ends_with("-2"));
        fs::remove_dir_all(a.dir()).unwrap();
    }

    #[test]
    fn sweep_by_age_keeps_pinned_and_newest() {
        let a = temp("age");
        let old = a.add(&entry(1, DAY, 10)).unwrap();
        let pinned = a.add(&entry(2, 2 * DAY, 10)).unwrap();
        let mut idx = a.load_index();
        idx.entries[1].pinned = true;
        a.save_index(&idx).unwrap();
        let newest = a.add(&entry(3, 3 * DAY, 10)).unwrap();
        // 30 days later with 7 days' retention: only the old unpinned one goes,
        // even though the newest is also past the cutoff.
        let s = a.sweep(33 * DAY, 7, u64::MAX);
        assert_eq!(s.removed, 1);
        let names: Vec<String> = a.entries().into_iter().map(|e| e.name).collect();
        assert_eq!(names, vec![pinned.name, newest.name]);
        assert!(!a.dir().join(&old.name).exists());
        fs::remove_dir_all(a.dir()).unwrap();
    }

    #[test]
    fn a_damaged_index_is_rebuilt_from_the_folders() {
        let a = temp("rebuild");
        let first = a.add(&entry(1, 1_000, 10)).unwrap();
        let second = a.add(&entry(2, 2_000, 10)).unwrap();
        std::fs::write(a.dir().join("index.json"), "{ not json").unwrap();
        let names: Vec<String> = a.entries().into_iter().map(|e| e.name).collect();
        assert_eq!(names, [first.name.clone(), second.name.clone()]);
        assert_eq!(a.latest().unwrap().seed, 2);
        // Which were pinned is unknown: none are swept away.
        assert!(a.entries().iter().all(|e| e.pinned));
        assert_eq!(a.sweep(100 * DAY, 1, 0).removed, 0);
        // Adding goes on from there, without listing anything twice.
        let third = a.add(&entry(3, 3_000, 10)).unwrap();
        let names: Vec<String> = a.entries().into_iter().map(|e| e.name).collect();
        assert_eq!(names, [first.name, second.name, third.name]);
        std::fs::remove_dir_all(a.dir()).unwrap();
    }

    #[test]
    fn writers_at_once_lose_no_entries() {
        let a = std::sync::Arc::new(temp("race"));
        let threads: Vec<_> = (0..8)
            .map(|i| {
                let a = a.clone();
                std::thread::spawn(move || {
                    a.add(&entry(100 + i, 10_000 + i, 10)).unwrap();
                })
            })
            .collect();
        for t in threads {
            t.join().unwrap();
        }
        assert_eq!(a.entries().len(), 8);
        std::fs::remove_dir_all(a.dir()).unwrap();
    }

    #[test]
    fn pin_and_delete() {
        let a = temp("pin");
        let one = a.add(&entry(1, DAY, 10)).unwrap();
        let two = a.add(&entry(2, 2 * DAY, 10)).unwrap();
        a.set_pinned(&one.name, true).unwrap();
        assert!(a.get(&one.name).unwrap().pinned);
        assert!(a.set_pinned("nope", true).is_err());
        a.delete(&two.name).unwrap();
        assert!(a.get(&two.name).is_none());
        assert!(!a.dir().join(&two.name).exists());
        a.delete(&two.name).unwrap(); // already gone: fine
        fs::remove_dir_all(a.dir()).unwrap();
    }

    #[test]
    fn sweep_by_size_removes_oldest_first() {
        let a = temp("size");
        let e: Vec<Entry> = (0..4)
            .map(|i| a.add(&entry(i, DAY * (i + 1), 1000)).unwrap())
            .collect();
        // Room for the two newest entries (sizes differ a little with the
        // recipe): the two oldest go.
        let s = a.sweep(5 * DAY, 0, e[2].bytes + e[3].bytes);
        assert_eq!(s.removed, 2);
        assert_eq!(s.freed, e[0].bytes + e[1].bytes);
        let left: Vec<u64> = a.entries().into_iter().map(|e| e.seed).collect();
        assert_eq!(left, vec![2, 3]);
        fs::remove_dir_all(a.dir()).unwrap();
    }
}