| 1 | |
| 2 | |
| 3 | use std::path::PathBuf; |
| 4 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 5 | use std::sync::Arc; |
| 6 | use std::thread; |
| 7 | use std::time::Duration; |
| 8 | |
| 9 | use smithay::reexports::calloop::channel::SyncSender; |
| 10 | |
| 11 | pub struct Watcher { |
| 12 | should_stop: Arc<AtomicBool>, |
| 13 | } |
| 14 | |
| 15 | impl Drop for Watcher { |
| 16 | fn drop(&mut self) { |
| 17 | self.should_stop.store(true, Ordering::SeqCst); |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | impl 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 | } |