use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use std::time::{Duration, Instant, SystemTime};
use anyhow::{Context, Result};
use crate::widgets::editor::EditorTabs;
use crate::widgets::file_finder::{has_noise_path_run, is_noise_dir, is_noise_path_under_root};
use crate::widgets::file_tree::{FileTree, affected_dir_for_event};
const FS_POLL_INTERVAL: Duration = Duration::from_millis(50);
const FS_WATCH_PROTECTED_NAMES: &[&str] = &["Library", ".Trash"];
#[cfg(target_os = "macos")]
const WATCH_WALK_DIR_BUDGET: usize = 8_192;
type FsWatcherInit = (
notify_debouncer_full::Debouncer<
notify::RecommendedWatcher,
notify_debouncer_full::RecommendedCache,
>,
Receiver<notify_debouncer_full::DebounceEventResult>,
);
#[derive(Default)]
pub struct FsPoll {
pub open_file_changed: bool,
pub dirs_changed: bool,
pub finder_relevant: bool,
}
#[derive(Default)]
pub struct FsDrain {
pub got_any: bool,
pub touched_open_file: bool,
pub dirs_changed: bool,
pub finder_relevant: bool,
pub changed_files: BTreeSet<PathBuf>,
pub rescan_dropped_events: bool,
}
pub struct FsWatch {
_watcher: Option<
notify_debouncer_full::Debouncer<
notify::RecommendedWatcher,
notify_debouncer_full::RecommendedCache,
>,
>,
rx: Option<Receiver<notify_debouncer_full::DebounceEventResult>>,
init_rx: Option<Receiver<FsWatcherInit>>,
poll_last_check: Instant,
poll_interval: Duration,
poll_dir_mtimes: BTreeMap<PathBuf, Option<SystemTime>>,
poll_open_files: BTreeMap<PathBuf, Option<(SystemTime, u64)>>,
watch_root: PathBuf,
canon_watch_root: PathBuf,
}
fn canon_of(root: &Path) -> PathBuf {
root.canonicalize().unwrap_or_else(|_| root.to_path_buf())
}
impl FsWatch {
pub fn spawn(root: &Path, tree: &FileTree) -> Self {
Self::spawn_sharing(root, tree, 1)
}
pub fn spawn_sharing(root: &Path, tree: &FileTree, shares: usize) -> Self {
Self {
_watcher: None,
rx: None,
init_rx: Some(Self::start_watcher_thread(root, shares)),
poll_last_check: Instant::now(),
poll_interval: FS_POLL_INTERVAL,
poll_dir_mtimes: Self::snapshot_expanded_dir_mtimes(tree),
poll_open_files: BTreeMap::new(),
watch_root: root.to_path_buf(),
canon_watch_root: canon_of(root),
}
}
pub fn spawn_event_only(root: &Path, shares: usize) -> Self {
Self {
_watcher: None,
rx: None,
init_rx: Some(Self::start_watcher_thread(root, shares)),
poll_last_check: Instant::now(),
poll_interval: FS_POLL_INTERVAL,
poll_dir_mtimes: BTreeMap::new(),
poll_open_files: BTreeMap::new(),
watch_root: root.to_path_buf(),
canon_watch_root: canon_of(root),
}
}
pub fn rebind(&mut self, root: &Path, tree: &FileTree) {
self.rebind_sharing(root, tree, 1)
}
pub fn rebind_sharing(&mut self, root: &Path, tree: &FileTree, shares: usize) {
offload_drop(self._watcher.take());
self.rx = None;
self.init_rx = Some(Self::start_watcher_thread(root, shares));
self.poll_dir_mtimes = Self::snapshot_expanded_dir_mtimes(tree);
self.watch_root = root.to_path_buf();
self.canon_watch_root = canon_of(root);
}
pub fn disable(&mut self) {
offload_drop(self._watcher.take());
self.rx = None;
self.init_rx = None;
}
pub fn try_install_watcher(&mut self) -> bool {
let Some(rx) = self.init_rx.as_ref() else {
return false;
};
match rx.try_recv() {
Ok((w, evrx)) => {
self._watcher = Some(w);
self.rx = Some(evrx);
self.init_rx = None;
true
}
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
self.init_rx = None;
false
}
Err(std::sync::mpsc::TryRecvError::Empty) => false,
}
}
pub fn sync_open_file_mtime(&mut self, open_paths: &[PathBuf]) {
self.poll_open_files = Self::stamp_all(open_paths);
}
fn stamp_all(paths: &[PathBuf]) -> BTreeMap<PathBuf, Option<(SystemTime, u64)>> {
paths
.iter()
.map(|p| (p.clone(), Self::file_stamp(p)))
.collect()
}
fn is_noise_event_path(&self, path: &Path) -> bool {
let root = if path.starts_with(&self.watch_root) {
&self.watch_root
} else {
&self.canon_watch_root
};
is_noise_path_under_root(path, root)
}
fn is_noise_polled_dir(&self, tree: &FileTree, dir: &Path) -> bool {
match tree
.root_paths()
.filter(|r| dir.starts_with(r))
.max_by_key(|r| r.as_os_str().len())
{
Some(root) => is_noise_path_under_root(dir, root),
None => self.is_noise_event_path(dir),
}
}
pub fn drain(&mut self, tree: &mut FileTree, editor: &EditorTabs) -> FsDrain {
let mut out = FsDrain::default();
let Some(rx) = self.rx.as_ref() else {
return out;
};
let mut affected: BTreeSet<PathBuf> = BTreeSet::new();
let mut new_dirs: Vec<PathBuf> = Vec::new();
while let Ok(result) = rx.try_recv() {
out.got_any = true;
let events = match result {
Ok(evs) => evs,
Err(_) => continue,
};
for ev in events {
if ev.event.need_rescan() {
out.rescan_dropped_events = true;
}
let mutates_content = event_mutates_content(&ev.event.kind);
let arrives = arrives_at_path(&ev.event.kind);
for path in &ev.event.paths {
if arrives && path.is_dir() && !self.is_noise_event_path(path) {
new_dirs.push(path.clone());
}
if mutates_content && editor.matches_open_path(path) {
out.touched_open_file = true;
}
if mutates_content
&& !removes_a_directory(&ev.event.kind)
&& !self.is_noise_event_path(path)
&& !path.is_dir()
{
out.changed_files.insert(path.clone());
}
if let Some(dir) =
affected_dir_for_event(path, &self.watch_root, &self.canon_watch_root)
{
affected.insert(dir);
} else if path == &self.watch_root
|| path.as_path() == self.canon_watch_root
|| path.canonicalize().ok().as_deref()
== Some(self.canon_watch_root.as_path())
{
affected.insert(self.watch_root.clone());
}
}
}
}
self.watch_new_dirs(new_dirs, &mut out);
if !affected.is_empty() {
for dir in affected.iter().rev() {
if let Some(idx) = tree.index_of_dir(dir) {
tree.refresh_children(idx);
} else if let Ok(c) = dir.canonicalize()
&& let Some(idx) = tree.index_of_dir(&c)
{
tree.refresh_children(idx);
}
}
self.poll_dir_mtimes = Self::snapshot_expanded_dir_mtimes(tree);
out.dirs_changed = true;
out.finder_relevant = affected.iter().any(|p| !self.is_noise_event_path(p));
}
out
}
fn watch_new_dirs(&mut self, dirs: Vec<PathBuf>, out: &mut FsDrain) {
if dirs.is_empty() || cfg!(target_os = "macos") {
return;
}
let (root, canon) = (self.watch_root.clone(), self.canon_watch_root.clone());
let noise = |p: &Path| {
is_noise_path_under_root(p, if p.starts_with(&root) { &root } else { &canon })
};
let Some(watcher) = self._watcher.as_mut() else {
out.rescan_dropped_events = true;
return;
};
let mut budget = 2_000usize;
let mut stack = dirs;
while let Some(dir) = stack.pop() {
if budget == 0 {
out.rescan_dropped_events = true;
return;
}
budget -= 1;
let _ = watcher.watch(&dir, notify::RecursiveMode::NonRecursive);
let Ok(rd) = std::fs::read_dir(&dir) else {
continue;
};
for entry in rd.filter_map(Result::ok) {
let path = entry.path();
let Ok(ft) = entry.file_type() else {
continue;
};
if ft.is_dir() {
let name = path.file_name().unwrap_or_default();
if !FS_WATCH_PROTECTED_NAMES.iter().any(|n| name == *n) && !noise(&path) {
stack.push(path);
}
} else if ft.is_file() && !noise(&path) {
out.changed_files.insert(path);
}
}
}
}
pub fn poll_due(&self) -> bool {
self.poll_last_check.elapsed() >= self.poll_interval
}
pub fn poll(&mut self, tree: &mut FileTree, open_paths: &[PathBuf]) -> FsPoll {
let mut out = FsPoll::default();
if !self.poll_due() {
return out;
}
let poll_start = Instant::now();
self.poll_last_check = poll_start;
out.open_file_changed = self.poll_open_file_change(open_paths);
let current = Self::snapshot_expanded_dir_mtimes(tree);
let changed_dirs: Vec<PathBuf> = current
.iter()
.filter_map(|(path, stamp)| {
if self.poll_dir_mtimes.get(path) == Some(stamp) {
None
} else {
Some(path.clone())
}
})
.collect();
if changed_dirs.is_empty() {
self.poll_dir_mtimes = current;
self.poll_interval = Self::back_off(poll_start);
return out;
}
for dir in changed_dirs.iter().rev() {
if let Some(idx) = tree.index_of_dir(dir) {
tree.refresh_children(idx);
}
}
self.poll_dir_mtimes = Self::snapshot_expanded_dir_mtimes(tree);
out.dirs_changed = true;
out.finder_relevant = changed_dirs
.iter()
.any(|p| !self.is_noise_polled_dir(tree, p));
self.poll_interval = Self::back_off(poll_start);
out
}
fn poll_open_file_change(&mut self, open_paths: &[PathBuf]) -> bool {
let current = Self::stamp_all(open_paths);
let changed = current.iter().any(
|(path, stamp)| matches!(self.poll_open_files.get(path), Some(old) if old != stamp),
);
self.poll_open_files = current;
changed
}
fn back_off(poll_start: Instant) -> Duration {
poll_start
.elapsed()
.saturating_mul(10)
.clamp(FS_POLL_INTERVAL, Duration::from_secs(10))
}
fn snapshot_expanded_dir_mtimes(tree: &FileTree) -> BTreeMap<PathBuf, Option<SystemTime>> {
tree.nodes
.iter()
.filter(|n| n.is_dir && n.expanded)
.map(|n| (n.path.clone(), Self::dir_modified(&n.path)))
.collect()
}
fn dir_modified(path: &Path) -> Option<SystemTime> {
std::fs::metadata(path).and_then(|m| m.modified()).ok()
}
fn file_stamp(path: &Path) -> Option<(SystemTime, u64)> {
let meta = std::fs::metadata(path).ok()?;
let modified = meta.modified().ok()?;
Some((modified, meta.len()))
}
fn start_watcher_thread(root: &Path, shares: usize) -> Receiver<FsWatcherInit> {
let (init_tx, init_rx) = std::sync::mpsc::channel();
let root = root.to_path_buf();
std::thread::spawn(move || {
if let Ok(pair) = Self::spawn_watcher_sharing(&root, shares) {
let _ = init_tx.send(pair);
}
});
init_rx
}
#[cfg(test)]
pub(super) fn spawn_watcher(root: &Path) -> Result<FsWatcherInit> {
Self::spawn_watcher_sharing(root, 1)
}
pub(super) fn spawn_watcher_sharing(root: &Path, shares: usize) -> Result<FsWatcherInit> {
use notify::RecursiveMode;
use notify_debouncer_full::new_debouncer;
let (tx, rx) = std::sync::mpsc::channel();
let mut debouncer = new_debouncer(Duration::from_millis(100), None, tx)
.context("creating filesystem watcher")?;
#[cfg(target_os = "macos")]
{
let mut targets: Vec<(PathBuf, RecursiveMode)> = Vec::new();
let mut budget = WATCH_WALK_DIR_BUDGET / shares.max(1);
if collect_macos_watch_targets(root, root, &mut targets, &mut budget) {
targets.push((root.to_path_buf(), RecursiveMode::Recursive));
}
const MAX_WATCHES: usize = 2_000;
let max_watches = MAX_WATCHES / shares.max(1);
if targets.len() > max_watches {
targets.sort_by_key(|(p, _)| p.components().count());
targets.truncate(max_watches);
}
for (path, mode) in targets {
let _ = debouncer.watch(&path, mode);
}
}
#[cfg(not(target_os = "macos"))]
{
let is_skippable = |path: &Path| -> bool {
let name = path.file_name().unwrap_or_default();
FS_WATCH_PROTECTED_NAMES.iter().any(|n| name == *n)
|| is_noise_dir(name)
|| has_noise_path_run(path, root)
};
const MAX_WATCHES: usize = 50_000;
let max_watches = MAX_WATCHES / shares.max(1);
if max_watches == 0 {
return Ok((debouncer, rx));
}
let mut stack = vec![root.to_path_buf()];
let mut watched = 0usize;
while let Some(dir) = stack.pop() {
if debouncer.watch(&dir, RecursiveMode::NonRecursive).is_ok() {
watched += 1;
}
if watched >= max_watches {
break;
}
let Ok(rd) = std::fs::read_dir(&dir) else {
continue;
};
for entry in rd.filter_map(Result::ok) {
if is_skippable(&entry.path()) {
continue;
}
if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
stack.push(entry.path());
}
}
}
}
Ok((debouncer, rx))
}
#[cfg(test)]
pub fn set_test_events(&mut self, rx: Receiver<notify_debouncer_full::DebounceEventResult>) {
self._watcher = None;
self.init_rx = None;
self.rx = Some(rx);
}
#[cfg(test)]
pub fn force_poll_due(&mut self) {
self.poll_last_check = Instant::now()
.checked_sub(self.poll_interval)
.unwrap_or_else(Instant::now);
}
#[cfg(test)]
pub fn clear_dir_mtimes(&mut self) {
self.poll_dir_mtimes.clear();
}
}
#[cfg(target_os = "macos")]
fn is_skippable_path(path: &Path, root: &Path) -> bool {
let name = path.file_name().unwrap_or_default();
FS_WATCH_PROTECTED_NAMES.iter().any(|n| name == *n)
|| is_noise_dir(name)
|| has_noise_path_run(path, root)
}
#[cfg(target_os = "macos")]
pub(super) fn collect_macos_watch_targets(
dir: &Path,
root: &Path,
targets: &mut Vec<(PathBuf, notify::RecursiveMode)>,
budget: &mut usize,
) -> bool {
use notify::RecursiveMode;
if *budget == 0 {
return false;
}
*budget -= 1;
let mut has_noise = false;
let mut subdirs: Vec<PathBuf> = Vec::new();
if let Ok(rd) = std::fs::read_dir(dir) {
for entry in rd.filter_map(Result::ok) {
if is_skippable_path(&entry.path(), root) {
has_noise = true;
continue;
}
if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
subdirs.push(entry.path());
}
}
}
let child_clean: Vec<(PathBuf, bool)> = subdirs
.into_iter()
.map(|sd| {
let clean = collect_macos_watch_targets(&sd, root, targets, budget);
(sd, clean)
})
.collect();
if !has_noise && child_clean.iter().all(|(_, clean)| *clean) {
return true;
}
for (sd, clean) in child_clean {
if clean {
targets.push((sd, RecursiveMode::Recursive));
}
}
false
}
impl Drop for FsWatch {
fn drop(&mut self) {
offload_drop(self._watcher.take());
}
}
pub(super) fn offload_drop<T: Send + 'static>(value: T) {
std::thread::spawn(move || drop(value));
}
fn removes_a_directory(kind: ¬ify::EventKind) -> bool {
use notify::EventKind;
use notify::event::RemoveKind;
matches!(kind, EventKind::Remove(RemoveKind::Folder))
}
fn arrives_at_path(kind: ¬ify::EventKind) -> bool {
use notify::EventKind;
use notify::event::{ModifyKind, RenameMode};
matches!(
kind,
EventKind::Create(_)
| EventKind::Modify(ModifyKind::Name(RenameMode::To | RenameMode::Both))
)
}
fn event_mutates_content(kind: ¬ify::EventKind) -> bool {
use notify::EventKind;
use notify::event::ModifyKind;
!matches!(
kind,
EventKind::Access(_) | EventKind::Modify(ModifyKind::Metadata(_))
)
}