rosier 0.3.0

A fast picture and video viewer for large folders
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
//! What the library holds and what each view of it shows: the indexed
//! files, favorites, hidden folders, the sidebar counts, and the filters
//! that pick and order the files for the grid and the panes.
//!
//! Nothing here touches the UI or the disk, so the rules are tested here
//! directly.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::db::{Source, Watch};
use crate::media::{self, Entry, Kind};
use crate::pane::PaneSource;

/// What part of the library the grid shows.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Scope {
    All,
    Favorites,
    /// Videos stopped part way, the most recent first.
    Continue,
    /// A source or a folder inside one (includes subfolders).
    Folder(PathBuf),
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum KindFilter {
    All,
    Photos,
    Videos,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SortBy {
    Name,
    Date,
    Size,
}

/// How many stretches a video is split into for its watch profile.
pub const HEAT_BINS: usize = 100;

/// Positions this close to the start or the end are not kept: the video
/// starts from the beginning next time.
const RESUME_MARGIN: f64 = 10.0;

/// Sidebar entry for a folder directly under a source.
#[derive(Debug, PartialEq, Eq)]
pub struct SideFolder {
    pub name: String,
    pub path: PathBuf,
    pub count: usize,
}

/// Lookups over one list of files: built off the UI thread, then handed to
/// `Library::set_index`.
#[derive(Default)]
pub struct Index {
    entries: Arc<Vec<Entry>>,
    id_index: HashMap<i64, usize>,
    /// Files directly in each folder, in natural order.
    dirs: HashMap<PathBuf, Vec<usize>>,
    source_counts: Vec<usize>,
    side_folders: Vec<Vec<SideFolder>>,
}

impl Index {
    /// Indexes `items` (in natural path order) for the given sources.
    pub fn build(sources: &[Source], items: Vec<Entry>) -> Self {
        let id_index = items.iter().enumerate().map(|(i, e)| (e.id, i)).collect();
        let mut dirs: HashMap<PathBuf, Vec<usize>> = HashMap::new();
        // Files of one folder are mostly next to each other, so the folder
        // is looked up only when it changes.
        let mut run: Option<(&Path, Vec<usize>)> = None;
        for (i, e) in items.iter().enumerate() {
            let parent = e.path.parent().unwrap_or(Path::new(""));
            match &mut run {
                Some((dir, files)) if *dir == parent => files.push(i),
                _ => {
                    if let Some((dir, files)) = run.replace((parent, vec![i])) {
                        dirs.entry(dir.to_path_buf()).or_default().extend(files);
                    }
                }
            }
        }
        if let Some((dir, files)) = run {
            dirs.entry(dir.to_path_buf()).or_default().extend(files);
        }
        // Rare: a folder whose files are not contiguous (names that differ
        // only in case sort together) gets its runs merged in order.
        for files in dirs.values_mut() {
            if !files.is_sorted() {
                files.sort_unstable();
            }
        }
        let (source_counts, side_folders) = sidebar(sources, &dirs);
        Index { entries: Arc::new(items), id_index, dirs, source_counts, side_folders }
    }
}

/// Files per source, and the folders right under each with their counts.
fn sidebar(sources: &[Source], dirs: &HashMap<PathBuf, Vec<usize>>) -> (Vec<usize>, Vec<Vec<SideFolder>>) {
    let mut counts = vec![0usize; sources.len()];
    let mut folders: Vec<HashMap<String, usize>> = vec![HashMap::new(); sources.len()];
    for (dir, files) in dirs {
        let Some((si, rel)) =
            sources.iter().enumerate().find_map(|(si, s)| Some((si, dir.strip_prefix(&s.path).ok()?)))
        else {
            continue;
        };
        counts[si] += files.len();
        if let Some(first) = rel.components().next() {
            *folders[si].entry(first.as_os_str().to_string_lossy().into_owned()).or_default() += files.len();
        }
    }
    let side = folders
        .into_iter()
        .zip(sources)
        .map(|(m, src)| {
            let mut v: Vec<SideFolder> =
                m.into_iter().map(|(name, count)| SideFolder { path: src.path.join(&name), name, count }).collect();
            v.sort_by(|a, b| media::natural_cmp(&a.path, &b.path));
            v
        })
        .collect();
    (counts, side)
}

#[derive(Default)]
pub struct Library {
    pub sources: Vec<Source>,
    /// Every file in natural path order. Shared with background work.
    pub entries: Arc<Vec<Entry>>,
    id_index: HashMap<i64, usize>,
    dirs: HashMap<PathBuf, Vec<usize>>,
    /// Favorite item ids, in the order they were added.
    pub favorites: Vec<i64>,
    favorite_set: HashSet<i64>,
    /// Folders hidden from the library (and their subfolders).
    pub excluded: Vec<PathBuf>,
    /// Length and stopping point of videos, by item id.
    pub watch: HashMap<i64, Watch>,
    /// Seconds watched in each of `HEAT_BINS` stretches of a video, by item
    /// id: parts watched again stand out.
    pub heat: HashMap<i64, Vec<f32>>,
    /// Files per source, and the folders right under each, for the sidebar.
    pub source_counts: Vec<usize>,
    pub side_folders: Vec<Vec<SideFolder>>,
}

impl Library {
    /// Replaces everything with a fresh read of the database. `index` must
    /// have been built for `sources`.
    pub fn replace(&mut self, sources: Vec<Source>, index: Index, favorites: Vec<i64>, excluded: Vec<PathBuf>) {
        self.sources = sources;
        self.favorites = favorites;
        self.excluded = excluded;
        self.set_index(index);
    }

    /// Replaces the file list, keeping sources and favorites.
    pub fn set_index(&mut self, index: Index) {
        let Index { entries, id_index, dirs, source_counts, side_folders } = index;
        self.entries = entries;
        self.id_index = id_index;
        self.dirs = dirs;
        self.source_counts = source_counts;
        self.side_folders = side_folders;
        self.favorite_set = self.favorites.iter().copied().collect();
    }

    /// Index of the entry at `path`, if it is in the library.
    pub fn find(&self, path: &Path) -> Option<usize> {
        // Entries are sorted with `natural_cmp`, so a binary search finds it.
        self.entries.binary_search_by(|e| media::natural_cmp(&e.path, path)).ok()
    }

    pub fn path(&self, i: usize) -> Option<&Path> {
        self.entries.get(i).map(|e| e.path.as_path())
    }

    pub fn is_favorite(&self, i: usize) -> bool {
        self.entries.get(i).is_some_and(|e| self.favorite_set.contains(&e.id))
    }

    /// Flips entry `i` in or out of the favorites. Returns its item id and
    /// whether it is a favorite now, for the caller to save.
    pub fn toggle_favorite(&mut self, i: usize) -> Option<(i64, bool)> {
        let id = self.entries.get(i)?.id;
        let on = self.favorite_set.insert(id);
        if on {
            self.favorites.push(id);
        } else {
            self.favorite_set.remove(&id);
            self.favorites.retain(|&f| f != id);
        }
        Some((id, on))
    }

    /// Favorites that are in the library now, in the order they were added.
    pub fn favorite_entries(&self) -> Vec<usize> {
        self.favorites.iter().filter_map(|id| self.id_index.get(id).copied()).collect()
    }

    /// The video's length in seconds, once known.
    pub fn duration(&self, i: usize) -> Option<f64> {
        self.watch.get(&self.entries.get(i)?.id)?.duration
    }

    /// Where to start entry `i`: where the user stopped, unless that was
    /// at the very start or end.
    pub fn resume_at(&self, i: usize) -> Option<f64> {
        let w = self.watch.get(&self.entries.get(i)?.id)?;
        (w.position > 0.0).then_some(w.position)
    }

    /// How far into entry `i` the user got, 0 to 1, for the tile's bar.
    pub fn progress(&self, i: usize) -> Option<f32> {
        let w = self.watch.get(&self.entries.get(i)?.id)?;
        let d = w.duration.filter(|d| *d > 0.0)?;
        (w.position > 0.0).then(|| (w.position / d).clamp(0.0, 1.0) as f32)
    }

    /// Notes that entry `i` is at `pos` of `dur` seconds. Near the start
    /// nothing is kept; near the end it counts as watched and starts over
    /// next time. Returns the item id and what to save, when that changed.
    pub fn record(&mut self, i: usize, pos: f64, dur: f64, now: i64) -> Option<(i64, Watch)> {
        let id = self.entries.get(i)?.id;
        let w = self.watch.entry(id).or_default();
        if dur > 0.0 {
            w.duration = Some(dur);
        }
        let near_end = dur > 0.0 && (pos >= dur - RESUME_MARGIN || pos >= dur * 0.95);
        let position = if pos < RESUME_MARGIN || near_end { 0.0 } else { pos };
        if position == 0.0 && w.position == 0.0 {
            return None;
        }
        w.position = position;
        w.at = now;
        Some((id, *w))
    }

    /// Adds `secs` of playback at `pos` of `dur` seconds to entry `i`'s
    /// watch profile. Returns the item id.
    pub fn add_watched(&mut self, i: usize, pos: f64, dur: f64, secs: f64) -> Option<i64> {
        if dur <= 0.0 || secs <= 0.0 || !(0.0..dur).contains(&pos) {
            return None;
        }
        let id = self.entries.get(i)?.id;
        let bins = self.heat.entry(id).or_insert_with(|| vec![0.0; HEAT_BINS]);
        let b = ((pos * HEAT_BINS as f64 / dur) as usize).min(HEAT_BINS - 1);
        bins[b] += secs as f32;
        Some(id)
    }

    /// Entry `i`'s watch profile, smoothed over neighboring stretches and
    /// scaled to 0..=1, once some part of it has been watched about twice;
    /// a video watched once through is flat and shows nothing.
    pub fn heat_profile(&self, i: usize) -> Option<Vec<f32>> {
        let e = self.entries.get(i)?;
        let bins = self.heat.get(&e.id)?;
        let per_bin = (self.watch.get(&e.id)?.duration? / HEAT_BINS as f64) as f32;
        // Playback is sampled a few times a second, so one stretch can get
        // a sample of its neighbor's; averaging over three evens that out.
        let smooth: Vec<f32> = (0..bins.len())
            .map(|k| {
                let lo = k.saturating_sub(1);
                let hi = (k + 2).min(bins.len());
                bins[lo..hi].iter().sum::<f32>() / (hi - lo) as f32
            })
            .collect();
        let max = smooth.iter().copied().fold(0.0, f32::max);
        if per_bin <= 0.0 || max < 1.8 * per_bin {
            return None;
        }
        Some(smooth.iter().map(|b| b / max).collect())
    }

    /// Notes a video's length read in the background.
    pub fn set_duration(&mut self, id: i64, dur: f64) {
        self.watch.entry(id).or_default().duration = Some(dur);
    }

    /// Videos in the library whose length is not known yet.
    pub fn without_duration(&self) -> Vec<Entry> {
        self.entries
            .iter()
            .filter(|e| e.kind == Kind::Video && self.watch.get(&e.id).is_none_or(|w| w.duration.is_none()))
            .cloned()
            .collect()
    }

    /// Videos stopped part way, the most recently watched first.
    pub fn continue_entries(&self) -> Vec<usize> {
        let mut v: Vec<(i64, usize)> = self
            .watch
            .iter()
            .filter(|(_, w)| w.position > 0.0)
            .filter_map(|(id, w)| Some((w.at, *self.id_index.get(id)?)))
            .collect();
        v.sort_unstable_by(|a, b| b.cmp(a));
        v.into_iter().map(|(_, i)| i).collect()
    }

    /// Which files the grid shows for `scope` and `kind`, in `sort` order.
    pub fn shown(&self, scope: &Scope, kind: KindFilter, sort: SortBy) -> Vec<usize> {
        let e = &self.entries;
        let mut shown: Vec<usize> = match scope {
            Scope::All => (0..e.len()).collect(),
            Scope::Favorites => self.favorite_entries(),
            Scope::Continue => self.continue_entries(),
            Scope::Folder(p) => self
                .dirs
                .iter()
                .filter(|(d, _)| d.starts_with(p))
                .flat_map(|(_, files)| files.iter().copied())
                .collect(),
        };
        shown.retain(|&i| match kind {
            KindFilter::All => true,
            KindFilter::Photos => e[i].kind == Kind::Image,
            KindFilter::Videos => e[i].kind == Kind::Video,
        });
        match sort {
            // Index order is natural path order; favorites stay in the
            // order they were added, and videos to continue most recent first.
            SortBy::Name if !matches!(scope, Scope::Favorites | Scope::Continue) => shown.sort_unstable(),
            SortBy::Name => {}
            SortBy::Date => shown.sort_by_key(|&i| std::cmp::Reverse(e[i].mtime)),
            SortBy::Size => shown.sort_by_key(|&i| std::cmp::Reverse(e[i].size)),
        }
        shown
    }

    /// Files a pane plays for `source`, in order. A folder plays only its
    /// own files, not its subfolders'.
    pub fn items_for(&self, source: &PaneSource) -> Vec<usize> {
        match source {
            PaneSource::Favorites => self.favorite_entries(),
            PaneSource::Folder(dir) => self.dirs.get(dir).cloned().unwrap_or_default(),
        }
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;

    pub fn entry(id: i64, path: &str, kind: Kind, size: u64, mtime: u64) -> Entry {
        Entry { id, path: PathBuf::from(path), kind, size, mtime }
    }

    fn sample() -> Library {
        let mut items = vec![
            entry(1, "/p/a.jpg", Kind::Image, 10, 3),
            entry(2, "/p/trip/b.jpg", Kind::Image, 30, 1),
            entry(3, "/p/trip/c.mp4", Kind::Video, 20, 2),
            entry(4, "/p/trip/day2/d.jpg", Kind::Image, 5, 5),
            entry(5, "/v/clip.mkv", Kind::Video, 50, 4),
        ];
        items.sort_by(|a, b| media::natural_cmp(&a.path, &b.path));
        let sources = vec![Source { id: 1, path: "/p".into() }, Source { id: 2, path: "/v".into() }];
        let index = Index::build(&sources, items);
        let mut lib = Library::default();
        lib.replace(sources, index, vec![5, 2], Vec::new());
        lib
    }

    fn ids(lib: &Library, v: &[usize]) -> Vec<i64> {
        v.iter().map(|&i| lib.entries[i].id).collect()
    }

    #[test]
    fn videos_resume_where_they_stopped_unless_at_either_end() {
        let mut lib = sample();
        let clip = lib.find(Path::new("/v/clip.mkv")).unwrap();
        let c = lib.find(Path::new("/p/trip/c.mp4")).unwrap();
        assert_eq!(lib.record(clip, 3.0, 600.0, 1), None, "the first seconds are not kept");
        assert_eq!(lib.resume_at(clip), None);
        assert_eq!(lib.duration(clip), Some(600.0), "the length is kept anyway");
        let (id, w) = lib.record(clip, 120.0, 600.0, 2).unwrap();
        assert_eq!((id, w.position, w.at), (5, 120.0, 2));
        assert_eq!(lib.resume_at(clip), Some(120.0));
        assert_eq!(lib.progress(clip), Some(0.2));
        lib.record(c, 50.0, 100.0, 3);
        assert_eq!(ids(&lib, &lib.shown(&Scope::Continue, KindFilter::All, SortBy::Name)), vec![3, 5]);
        // Watched to the end: starts over, and leaves the list.
        let (_, w) = lib.record(clip, 595.0, 600.0, 4).unwrap();
        assert_eq!(w.position, 0.0);
        assert_eq!(lib.resume_at(clip), None);
        assert_eq!(ids(&lib, &lib.continue_entries()), vec![3]);
        assert_eq!(lib.record(clip, 0.5, 600.0, 5), None, "nothing new to save");
    }

    #[test]
    fn parts_watched_again_stand_out() {
        let mut lib = sample();
        let clip = lib.find(Path::new("/v/clip.mkv")).unwrap();
        lib.set_duration(5, 100.0);
        // Once through, a second at a time: flat, nothing to show.
        for s in 0..100 {
            lib.add_watched(clip, s as f64, 100.0, 1.0);
        }
        assert_eq!(lib.heat_profile(clip), None);
        // Seconds 40 to 49 again, twice.
        for _ in 0..2 {
            for s in 40..50 {
                lib.add_watched(clip, s as f64, 100.0, 1.0);
            }
        }
        let p = lib.heat_profile(clip).unwrap();
        assert_eq!(p.len(), HEAT_BINS);
        assert_eq!(p[45], 1.0);
        assert!((p[10] - 1.0 / 3.0).abs() < 1e-6);
        assert!(p[40] > p[30] && p[40] < 1.0, "the edges of the stretch are smoothed");
        assert_eq!(lib.add_watched(clip, 120.0, 100.0, 1.0), None, "past the end");
        assert_eq!(lib.add_watched(clip, 10.0, 0.0, 1.0), None, "length unknown");
    }

    #[test]
    fn video_lengths_are_read_once() {
        let mut lib = sample();
        let ids_missing = |lib: &Library| lib.without_duration().iter().map(|e| e.id).collect::<Vec<_>>();
        assert_eq!(ids_missing(&lib), vec![3, 5], "only videos");
        lib.set_duration(5, 42.0);
        assert_eq!(ids_missing(&lib), vec![3]);
        assert_eq!(lib.duration(lib.find(Path::new("/v/clip.mkv")).unwrap()), Some(42.0));
    }

    #[test]
    fn scope_kind_and_sort_pick_the_grid() {
        let lib = sample();
        let all = lib.shown(&Scope::All, KindFilter::All, SortBy::Name);
        assert_eq!(ids(&lib, &all), vec![1, 2, 3, 4, 5]);
        let trip = lib.shown(&Scope::Folder("/p/trip".into()), KindFilter::All, SortBy::Name);
        assert_eq!(ids(&lib, &trip), vec![2, 3, 4], "a folder includes its subfolders");
        let videos = lib.shown(&Scope::All, KindFilter::Videos, SortBy::Name);
        assert_eq!(ids(&lib, &videos), vec![3, 5]);
        let photos = lib.shown(&Scope::All, KindFilter::Photos, SortBy::Size);
        assert_eq!(ids(&lib, &photos), vec![2, 1, 4], "largest first");
        let newest = lib.shown(&Scope::All, KindFilter::All, SortBy::Date);
        assert_eq!(ids(&lib, &newest), vec![4, 5, 1, 3, 2], "newest first");
        let favs = lib.shown(&Scope::Favorites, KindFilter::All, SortBy::Name);
        assert_eq!(ids(&lib, &favs), vec![5, 2], "favorites keep the order they were added");
    }

    #[test]
    fn a_folder_pane_plays_only_that_folder() {
        let lib = sample();
        let items = lib.items_for(&PaneSource::Folder("/p/trip".into()));
        assert_eq!(ids(&lib, &items), vec![2, 3]);
        assert_eq!(ids(&lib, &lib.items_for(&PaneSource::Favorites)), vec![5, 2]);
    }

    #[test]
    fn favorites_toggle_and_ignore_files_no_longer_indexed() {
        let mut lib = sample();
        let a = lib.find(Path::new("/p/a.jpg")).unwrap();
        assert!(!lib.is_favorite(a));
        assert_eq!(lib.toggle_favorite(a), Some((1, true)));
        assert!(lib.is_favorite(a));
        assert_eq!(lib.favorites, vec![5, 2, 1]);
        assert_eq!(lib.toggle_favorite(a), Some((1, false)));
        assert_eq!(lib.favorites, vec![5, 2]);
        assert_eq!(lib.toggle_favorite(99), None);
        // id 5 leaves the index: it stays saved but is not shown.
        let kept: Vec<Entry> = lib.entries.iter().filter(|e| e.id != 5).cloned().collect();
        lib.set_index(Index::build(&lib.sources, kept));
        assert_eq!(ids(&lib, &lib.favorite_entries()), vec![2]);
        assert_eq!(lib.favorites, vec![5, 2]);
    }

    #[test]
    fn sidebar_counts_files_per_source_and_top_folder() {
        let lib = sample();
        assert_eq!(lib.source_counts, vec![4, 1]);
        assert_eq!(lib.side_folders[0], vec![SideFolder { name: "trip".into(), path: "/p/trip".into(), count: 3 }]);
        assert!(lib.side_folders[1].is_empty(), "files at a source's root make no folder row");
    }

    #[test]
    fn folders_whose_files_interleave_still_play_in_order() {
        // "A" and "a" sort together, so their files alternate.
        let mut items = vec![
            entry(1, "/s/A/1.jpg", Kind::Image, 1, 1),
            entry(2, "/s/a/2.jpg", Kind::Image, 1, 1),
            entry(3, "/s/A/3.jpg", Kind::Image, 1, 1),
            entry(4, "/s/a/4.jpg", Kind::Image, 1, 1),
        ];
        items.sort_by(|a, b| media::natural_cmp(&a.path, &b.path));
        let sources = vec![Source { id: 1, path: "/s".into() }];
        let mut lib = Library::default();
        lib.replace(sources.clone(), Index::build(&sources, items), vec![], vec![]);
        assert_eq!(ids(&lib, &lib.items_for(&PaneSource::Folder("/s/A".into()))), vec![1, 3]);
        assert_eq!(ids(&lib, &lib.items_for(&PaneSource::Folder("/s/a".into()))), vec![2, 4]);
        assert_eq!(lib.source_counts, vec![4]);
        assert!(lib.items_for(&PaneSource::Folder("/nowhere".into())).is_empty());
    }

    #[test]
    fn find_locates_entries_by_path() {
        let lib = sample();
        assert_eq!(lib.path(lib.find(Path::new("/p/trip/c.mp4")).unwrap()), Some(Path::new("/p/trip/c.mp4")));
        assert_eq!(lib.find(Path::new("/p/zzz.jpg")), None);
        assert_eq!(lib.path(99), None);
    }
}