use std::path::Path;
use std::sync::{Arc, Mutex};
#[derive(Debug)]
pub(crate) struct Watcher {
watcher: Option<notify::ReadDirectoryChangesWatcher>,
ends: Option<std::thread::JoinHandle<()>>,
}
impl Watcher {
pub(crate) fn on(
dir: &Path,
handler: impl notify::EventHandler,
ended: impl Fn() + Send + 'static,
) -> notify::Result<Watcher> {
use notify::Watcher as _;
let (meta, metas) = std::sync::mpsc::channel();
let mut watcher =
notify::ReadDirectoryChangesWatcher::create(Arc::new(Mutex::new(handler)), meta)?;
watcher.watch(dir, notify::RecursiveMode::NonRecursive)?;
let ends = std::thread::Builder::new()
.name("pitboard-watch-ends".into())
.spawn(move || {
for meta in metas {
if meta == notify::windows::MetaEvent::SingleWatchComplete {
ended();
}
}
})
.map_err(notify::Error::io)?;
Ok(Watcher {
watcher: Some(watcher),
ends: Some(ends),
})
}
}
impl Drop for Watcher {
fn drop(&mut self) {
drop(self.watcher.take());
if let Some(ends) = self.ends.take() {
let _ = ends.join();
}
}
}