rosier 0.5.2

A fast picture and video viewer for large folders
//! Finding media files under a root directory.

use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    Image,
    Video,
    /// A comic archive (ZIP, CBZ) or picture EPUB: one tile, read as pages.
    Book,
}

#[derive(Debug, Clone)]
pub struct Entry {
    /// Row id in the index; 0 for files that are not indexed (bench tools).
    pub id: i64,
    pub path: PathBuf,
    pub kind: Kind,
    pub size: u64,
    pub mtime: u64,
}

impl Entry {
    pub fn is_jpeg(&self) -> bool {
        matches!(ext_lower(&self.path).as_deref(), Some("jpg" | "jpeg"))
    }

    /// Pictures that libmpv decodes (through FFmpeg) rather than the image
    /// crate: AVIF, HEIC/HEIF and JPEG XL. rosier links no decoder of its
    /// own for them, so no other library or license comes with them.
    pub fn decoded_by_mpv(&self) -> bool {
        self.kind == Kind::Image && ext_lower(&self.path).is_some_and(|e| MPV_IMAGES.contains(&e.as_str()))
    }
}

const MPV_IMAGES: [&str; 4] = ["avif", "heic", "heif", "jxl"];

pub(crate) fn ext_lower(path: &Path) -> Option<String> {
    Some(path.extension()?.to_str()?.to_ascii_lowercase())
}

pub fn kind_of(path: &Path) -> Option<Kind> {
    match ext_lower(path)?.as_str() {
        "jpg" | "jpeg" | "png" | "gif" | "webp" | "bmp" | "tif" | "tiff" => Some(Kind::Image),
        e if MPV_IMAGES.contains(&e) => Some(Kind::Image),
        "svg" | "psd" => Some(Kind::Image),
        e if crate::formats::RAW.contains(&e) => Some(Kind::Image),
        "zip" | "cbz" | "epub" => Some(Kind::Book),
        "mp4" | "mkv" | "avi" | "mov" | "webm" | "m4v" | "ts" | "wmv" | "flv" => Some(Kind::Video),
        _ => None,
    }
}

/// The library entry for the file at `path`, or None when rosier does not
/// show it. `metadata` is read only for a file rosier shows.
pub fn entry(path: PathBuf, metadata: impl FnOnce() -> Option<std::fs::Metadata>) -> Option<Entry> {
    let kind = kind_of(&path)?;
    // A Live Photo's MOV is shown as the motion of its still.
    if kind == Kind::Video && crate::motion::is_live_video(&path) {
        return None;
    }
    let md = metadata()?;
    let mtime = md.modified().ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map_or(0, |d| d.as_secs());
    Some(Entry { id: 0, path, kind, size: md.len(), mtime })
}

/// Walks `root` in parallel and returns every image and video, sorted by path.
pub fn scan(root: &Path) -> Vec<Entry> {
    use rayon::prelude::*;
    // jwalk reads folders in parallel but hands back one folder's files on
    // one thread, so a folder of 20,000 photos made 20,000 metadata reads in
    // a row (most of a first scan). They run on every core instead.
    let files: Vec<PathBuf> = jwalk::WalkDir::new(root)
        .skip_hidden(true)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_type().is_file() && kind_of(Path::new(&e.file_name)).is_some())
        .map(|e| e.path())
        .collect();
    let mut v: Vec<Entry> =
        files.into_par_iter().filter_map(|p| entry(p.clone(), || std::fs::metadata(&p).ok())).collect();
    v.par_sort_by(|a, b| natural_cmp(&a.path, &b.path));
    v
}

/// Compares paths the way people count: "clip_2" before "clip_10".
pub fn natural_cmp(a: &Path, b: &Path) -> std::cmp::Ordering {
    use std::cmp::Ordering;
    let (a, b) = (a.as_os_str().as_encoded_bytes(), b.as_os_str().as_encoded_bytes());
    let (mut i, mut j) = (0, 0);
    while i < a.len() && j < b.len() {
        if a[i].is_ascii_digit() && b[j].is_ascii_digit() {
            let si = i;
            while i < a.len() && a[i].is_ascii_digit() {
                i += 1;
            }
            let sj = j;
            while j < b.len() && b[j].is_ascii_digit() {
                j += 1;
            }
            // Compare digit runs by value: drop leading zeros, then length,
            // then digits. Ties on value fall back to the shorter run.
            let (na, nb) = (&a[si..i], &b[sj..j]);
            let ta = &na[na.iter().take_while(|&&c| c == b'0').count()..];
            let tb = &nb[nb.iter().take_while(|&&c| c == b'0').count()..];
            let ord = ta.len().cmp(&tb.len()).then_with(|| ta.cmp(tb)).then_with(|| na.len().cmp(&nb.len()));
            if ord != Ordering::Equal {
                return ord;
            }
        } else {
            let (ca, cb) = (a[i].to_ascii_lowercase(), b[j].to_ascii_lowercase());
            if ca != cb {
                return ca.cmp(&cb);
            }
            i += 1;
            j += 1;
        }
    }
    (a.len() - i).cmp(&(b.len() - j)).then_with(|| a.cmp(b))
}

#[cfg(test)]
mod tests {
    use super::natural_cmp;
    use std::cmp::Ordering::*;
    use std::path::Path;

    #[test]
    fn numbers_compare_by_value() {
        let c = |a: &str, b: &str| natural_cmp(Path::new(a), Path::new(b));
        assert_eq!(c("clip_2.mp4", "clip_10.mp4"), Less);
        assert_eq!(c("clip_10.mp4", "clip_2.mp4"), Greater);
        assert_eq!(c("a/img_001.jpg", "a/img_2.jpg"), Less);
        assert_eq!(c("Ep 9", "ep 10"), Less);
        assert_eq!(c("x", "x"), Equal);
        // A folder's files stay together: "a/z" sorts before "a_b/a".
        assert_eq!(c("a/z.jpg", "a/zz.jpg"), Less);
    }
}