forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB0411fd8Ivan Molodetskikh3 years ago263 commits

watcher.rs60 lines, 1.8 KiBHistoryRawDownload
1//! File modification watcher.
2
3use std::path::PathBuf;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::Arc;
6use std::thread;
7use std::time::Duration;
8
9use smithay::reexports::calloop::channel::SyncSender;
10
11pub struct Watcher {
12 should_stop: Arc<AtomicBool>,
13}
14
15impl Drop for Watcher {
16 fn drop(&mut self) {
17 self.should_stop.store(true, Ordering::SeqCst);
18 }
19}
20
21impl Watcher {
22 pub fn new(path: PathBuf, changed: SyncSender<()>) -> Self {
23 let should_stop = Arc::new(AtomicBool::new(false));
24
25 {
26 let should_stop = should_stop.clone();
27 thread::Builder::new()
28 .name(format!("Filesystem Watcher for {}", path.to_string_lossy()))
29 .spawn(move || {
30 let mut last_mtime = path.metadata().and_then(|meta| meta.modified()).ok();
31
32 loop {
33 thread::sleep(Duration::from_millis(500));
34
35 if should_stop.load(Ordering::SeqCst) {
36 break;
37 }
38
39 if let Ok(mtime) = path.metadata().and_then(|meta| meta.modified()) {
40 if last_mtime != Some(mtime) {
41 trace!("file changed: {}", path.to_string_lossy());
42
43 if let Err(err) = changed.send(()) {
44 warn!("error sending change notification: {err:?}");
45 break;
46 }
47
48 last_mtime = Some(mtime);
49 }
50 }
51 }
52
53 debug!("exiting watcher thread for {}", path.to_string_lossy());
54 })
55 .unwrap();
56 }
57
58 Self { should_stop }
59 }
60}