rosier 0.2.0

A fast picture and video viewer for large folders
//! 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;
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,
    /// 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,
}

/// 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>,
    /// 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()
    }

    /// 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::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.
            SortBy::Name if *scope != Scope::Favorites => 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 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);
    }
}