rosier 0.4.0

A fast picture and video viewer for large folders
//! Watching the source folders, so files that appear, change or go away
//! show up in the library without a restart.
//!
//! Events come in bursts (an image generator writes a file in several
//! steps, a copy brings hundreds), so they are gathered until the folders
//! have been quiet for a moment, and then one rescan is asked for.

use std::path::PathBuf;
use std::sync::mpsc;
use std::time::{Duration, Instant};

use notify::{EventKind, RecursiveMode, Watcher as _};

/// How long the folders must be quiet before a rescan.
const QUIET: Duration = Duration::from_millis(400);
/// A rescan happens at least this often during a long burst.
const MAX_WAIT: Duration = Duration::from_secs(2);

pub struct Watch {
    dirs: Vec<PathBuf>,
    /// Dropping it stops watching, which also ends the gathering thread.
    _watcher: Option<notify::RecommendedWatcher>,
}

impl Watch {
    /// Starts watching `dirs` and their subfolders. The receiver gets one
    /// message per burst of changes.
    pub fn start(dirs: Vec<PathBuf>) -> (Watch, async_channel::Receiver<()>) {
        let (tx, rx) = async_channel::bounded(1);
        let (ev_tx, ev_rx) = mpsc::channel::<()>();
        let watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
            if res.is_ok_and(|e| relevant(&e)) {
                let _ = ev_tx.send(());
            }
        })
        .map(|mut w| {
            for d in &dirs {
                // A folder that cannot be watched (gone, or too many
                // watches) is still rescanned at start.
                if let Err(e) = w.watch(d, RecursiveMode::Recursive) {
                    eprintln!("not watching {}: {e}", d.display());
                }
            }
            w
        });
        let watcher = match watcher {
            Ok(w) => Some(w),
            Err(e) => {
                eprintln!("folder watching is unavailable: {e}");
                None
            }
        };
        std::thread::Builder::new()
            .name("rosier-watch".into())
            .spawn(move || gather(&ev_rx, &tx, QUIET, MAX_WAIT))
            .ok();
        (Watch { dirs, _watcher: watcher }, rx)
    }

    pub fn dirs(&self) -> &[PathBuf] {
        &self.dirs
    }
}

/// Whether an event can change what the library holds: a picture or video
/// came, changed or went, or a folder was renamed or removed.
fn relevant(e: &notify::Event) -> bool {
    match e.kind {
        EventKind::Access(_) | EventKind::Other => false,
        EventKind::Remove(_) | EventKind::Modify(notify::event::ModifyKind::Name(_)) => true,
        _ => e.paths.iter().any(|p| crate::media::kind_of(p).is_some()),
    }
}

/// Turns bursts of events into single messages until either side closes.
fn gather(events: &mpsc::Receiver<()>, out: &async_channel::Sender<()>, quiet: Duration, max_wait: Duration) {
    while events.recv().is_ok() {
        let start = Instant::now();
        loop {
            let left = max_wait.saturating_sub(start.elapsed());
            match events.recv_timeout(quiet.min(left)) {
                Ok(()) if !left.is_zero() => continue,
                Err(mpsc::RecvTimeoutError::Disconnected) => return,
                _ => break,
            }
        }
        // A full channel already holds a rescan request.
        if out.try_send(()).is_err() && out.is_closed() {
            return;
        }
    }
}

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

    #[test]
    fn a_burst_of_events_asks_for_one_rescan() {
        let (ev_tx, ev_rx) = mpsc::channel();
        let (tx, rx) = async_channel::bounded(1);
        let t = std::thread::spawn(move || gather(&ev_rx, &tx, Duration::from_millis(50), Duration::from_secs(5)));
        for _ in 0..20 {
            ev_tx.send(()).unwrap();
        }
        std::thread::sleep(Duration::from_millis(200));
        assert!(rx.try_recv().is_ok());
        assert!(rx.try_recv().is_err(), "one message for the whole burst");
        drop(ev_tx);
        t.join().unwrap();
    }

    #[test]
    fn only_media_and_folder_changes_count() {
        use notify::event::{AccessKind, CreateKind, RemoveKind};
        let ev = |kind, p: &str| notify::Event::new(kind).add_path(PathBuf::from(p));
        assert!(relevant(&ev(EventKind::Create(CreateKind::File), "/a/b.png")));
        assert!(!relevant(&ev(EventKind::Create(CreateKind::File), "/a/b.txt")));
        assert!(!relevant(&ev(EventKind::Access(AccessKind::Any), "/a/b.png")));
        assert!(relevant(&ev(EventKind::Remove(RemoveKind::Folder), "/a/old")));
    }

    #[test]
    fn new_files_are_reported() {
        let dir = std::env::temp_dir().join(format!("rosier-watch-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let (_w, rx) = Watch::start(vec![dir.clone()]);
        std::thread::sleep(Duration::from_millis(100));
        std::fs::write(dir.join("new.jpg"), b"x").unwrap();
        let deadline = Instant::now() + Duration::from_secs(5);
        while rx.try_recv().is_err() {
            assert!(Instant::now() < deadline, "no change reported");
            std::thread::sleep(Duration::from_millis(20));
        }
        let _ = std::fs::remove_dir_all(&dir);
    }
}