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::{is_noise_dir, is_path_under_noise_dir};
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 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)>>,
}
impl FsWatch {
pub fn spawn(root: &Path, tree: &FileTree) -> Self {
Self {
_watcher: None,
rx: None,
init_rx: Some(Self::start_watcher_thread(root)),
poll_last_check: Instant::now(),
poll_interval: FS_POLL_INTERVAL,
poll_dir_mtimes: Self::snapshot_expanded_dir_mtimes(tree),
poll_open_files: BTreeMap::new(),
}
}
pub fn rebind(&mut self, root: &Path, tree: &FileTree) {
offload_drop(self._watcher.take());
self.rx = None;
self.init_rx = Some(Self::start_watcher_thread(root));
self.poll_dir_mtimes = Self::snapshot_expanded_dir_mtimes(tree);
}
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()
}
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();
while let Ok(result) = rx.try_recv() {
out.got_any = true;
let events = match result {
Ok(evs) => evs,
Err(_) => continue,
};
for ev in events {
let mutates_content = event_mutates_content(&ev.event.kind);
for path in &ev.event.paths {
if mutates_content && editor.matches_open_path(path) {
out.touched_open_file = true;
}
if let Some(dir) = affected_dir_for_event(path, &tree.root) {
affected.insert(dir);
} else if path == &tree.root
|| path.canonicalize().ok().as_deref()
== tree.root.canonicalize().ok().as_deref()
{
affected.insert(tree.root.clone());
}
}
}
}
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| !is_path_under_noise_dir(p));
}
out
}
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| !is_path_under_noise_dir(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) -> 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(&root) {
let _ = init_tx.send(pair);
}
});
init_rx
}
pub(super) fn spawn_watcher(root: &Path) -> 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;
if collect_macos_watch_targets(root, &mut targets, &mut budget) {
targets.push((root.to_path_buf(), RecursiveMode::Recursive));
}
const MAX_WATCHES: usize = 2_000;
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 = |name: &std::ffi::OsStr| -> bool {
FS_WATCH_PROTECTED_NAMES.iter().any(|n| name == *n) || is_noise_dir(name)
};
const MAX_WATCHES: usize = 50_000;
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.file_name()) {
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_name(name: &std::ffi::OsStr) -> bool {
FS_WATCH_PROTECTED_NAMES.iter().any(|n| name == *n) || is_noise_dir(name)
}
#[cfg(target_os = "macos")]
pub(super) fn collect_macos_watch_targets(
dir: &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_name(&entry.file_name()) {
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, 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 event_mutates_content(kind: ¬ify::EventKind) -> bool {
use notify::EventKind;
use notify::event::ModifyKind;
!matches!(
kind,
EventKind::Access(_) | EventKind::Modify(ModifyKind::Metadata(_))
)
}