//! Debounced notifications for changes other programs make to the mods folder.
use notify::{EventKind, RecursiveMode, Watcher};
use std::{
path::{Path, PathBuf},
sync::mpsc,
time::Duration,
};
/// Finder, installers and the game touch several entries in one burst; rescan once it settles.
pub const QUIET: Duration = Duration::from_millis(400);
/// Only top-level entries matter. Folder-mod contents, dotfiles (Finder's `.DS_Store`), our own
/// partial downloads and the list's temp/backup siblings never trigger a rescan.
pub fn relevant(mods_dir: &Path, canonical: &Path, path: &Path) -> bool {
let Some(parent) = path.parent() else {
return false;
};
if parent != mods_dir && parent != canonical {
return false;
}
let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
return true;
};
!(name.starts_with('.')
|| name.ends_with(".fmm-part")
|| name == "mod-list.json.tmp"
|| name == "mod-list.json.bak")
}
/// Calls `on_change` on a worker thread once per settled burst. Dropping the watcher stops it.
pub fn spawn(
mods_dir: PathBuf,
on_change: impl Fn() + Send + 'static,
) -> notify::Result<notify::RecommendedWatcher> {
// FSEvents reports resolved paths (/private/var for /var on macOS).
let canonical = std::fs::canonicalize(&mods_dir).unwrap_or_else(|_| mods_dir.clone());
let (tx, rx) = mpsc::channel::<()>();
let dir = mods_dir.clone();
let mut watcher =
notify::recommended_watcher(move |result: notify::Result<notify::Event>| match result {
Ok(event) => {
if event.need_rescan()
|| (!matches!(event.kind, EventKind::Access(_))
&& event.paths.iter().any(|p| relevant(&dir, &canonical, p)))
{
let _ = tx.send(());
}
}
Err(e) => eprintln!("Mods folder watch: {e}"),
})?;
watcher.watch(&mods_dir, RecursiveMode::NonRecursive)?;
std::thread::spawn(move || {
while rx.recv().is_ok() {
while rx.recv_timeout(QUIET).is_ok() {}
on_change();
}
});
Ok(watcher)
}
#[cfg(test)]
mod tests {
use super::*;
use std::{fs, time::Instant};
#[test]
fn only_top_level_mod_entries_and_the_list_are_relevant() {
let mods = Path::new("/data/mods");
let canonical = Path::new("/private/data/mods");
for path in [
"/data/mods/a_1.0.0.zip",
"/data/mods/my-folder-mod",
"/data/mods/mod-list.json",
"/private/data/mods/b_2.0.0.zip",
] {
assert!(relevant(mods, canonical, Path::new(path)), "{path}");
}
for path in [
"/data/mods",
"/data/mods/my-folder-mod/control.lua",
"/data/mods/.DS_Store",
"/data/mods/a_1.0.1.zip.fmm-part",
"/data/mods/mod-list.json.tmp",
"/data/mods/mod-list.json.bak",
"/data/mod-backups/a_1.0.0.zip",
] {
assert!(!relevant(mods, canonical, Path::new(path)), "{path}");
}
}
#[test]
fn real_folder_changes_settle_into_one_notification_and_noise_is_ignored() {
let dir = std::env::temp_dir().join(format!("fmm-watch-{}", std::process::id()));
let mods = dir.join("mods");
fs::create_dir_all(mods.join("folder-mod")).unwrap();
let (tx, rx) = mpsc::channel();
let watcher = spawn(mods.clone(), move || {
let _ = tx.send(Instant::now());
})
.unwrap();
// FSEvents may flush events from just before the stream started.
while rx.recv_timeout(Duration::from_secs(1)).is_ok() {}
fs::write(mods.join(".DS_Store"), b"finder").unwrap();
fs::write(mods.join("folder-mod/control.lua"), b"-- edit").unwrap();
fs::write(mods.join("a_1.0.0.zip.fmm-part"), b"partial").unwrap();
assert!(rx.recv_timeout(Duration::from_secs(2)).is_err());
for i in 0..5 {
fs::write(mods.join(format!("m{i}_1.0.0.zip")), b"zip").unwrap();
}
fs::write(mods.join("mod-list.json"), b"{\"mods\":[]}").unwrap();
rx.recv_timeout(Duration::from_secs(10))
.expect("a top-level change notifies");
assert!(
rx.recv_timeout(QUIET * 3).is_err(),
"one burst gives one notification"
);
drop(watcher);
fs::remove_dir_all(dir).unwrap();
}
}