Skip to content

Visual Studio Code, rebuilt in Rust

Rust

fix(files): drop the watcher callback on the thread that drops it

rokartur6a7ce5116188
diff --git a/native/crates/files/src/watcher.rs b/native/crates/files/src/watcher.rs
index a3fe302de7f..255db491c4e 100644
--- a/native/crates/files/src/watcher.rs
+++ b/native/crates/files/src/watcher.rs
@@ -92,10 +92,21 @@ impl Watch {
}
}
+type OnChanges = Arc<Mutex<Option<Box<dyn Fn(Vec<Change>) + Send>>>>;
+
/// Watches folders and files by id; every batch of changes any watch covers goes to the callback, on the watcher's thread.
pub struct Watcher {
fs_events: notify::RecommendedWatcher,
watches: Arc<Mutex<HashMap<u64, Watch>>>,
+ on_changes: OnChanges,
+}
+
+/// The callback is dropped here, not on the watcher's thread: a channel sender in it, dropped there, would drop or wake
+/// the GPUI foreground task that receives from it off the main thread.
+impl Drop for Watcher {
+ fn drop(&mut self) {
+ self.on_changes.lock().unwrap().take();
+ }
}
impl Watcher {
@@ -104,8 +115,10 @@ impl Watcher {
let watches: Arc<Mutex<HashMap<u64, Watch>>> = Arc::default();
let fs_events = notify::recommended_watcher(move |event: notify::Result<notify::Event>| forward(event, &sender))?;
let batch_watches = watches.clone();
- std::thread::Builder::new().name("file-watcher".into()).spawn(move || deliver_batches(&receiver, &batch_watches, on_changes))?;
- Ok(Watcher { fs_events, watches })
+ let on_changes: OnChanges = Arc::new(Mutex::new(Some(Box::new(on_changes))));
+ let batch_on_changes = on_changes.clone();
+ std::thread::Builder::new().name("file-watcher".into()).spawn(move || deliver_batches(&receiver, &batch_watches, &batch_on_changes))?;
+ Ok(Watcher { fs_events, watches, on_changes })
}
/// `excludes` are glob patterns relative to `path` (`files.watcherExclude`, `IWatchOptions.excludes`).
@@ -143,7 +156,7 @@ fn forward(event: notify::Result<notify::Event>, sender: &Sender<Change>) {
}
}
-fn deliver_batches(receiver: &Receiver<Change>, watches: &Mutex<HashMap<u64, Watch>>, on_changes: impl Fn(Vec<Change>)) {
+fn deliver_batches(receiver: &Receiver<Change>, watches: &Mutex<HashMap<u64, Watch>>, on_changes: &OnChanges) {
const DELAY: Duration = Duration::from_millis(75);
while let Ok(first) = receiver.recv() {
let mut batch = vec![first];
@@ -165,7 +178,9 @@ fn deliver_batches(receiver: &Receiver<Change>, watches: &Mutex<HashMap<u64, Wat
}
}
let changes = coalesce(covered);
- if !changes.is_empty() {
+ if !changes.is_empty()
+ && let Some(on_changes) = &*on_changes.lock().unwrap()
+ {
on_changes(changes);
}
}