From c8952a8f83e2ffa357a681e5eb1a275fbe37f064 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 20:50:03 -0700 Subject: [PATCH 1/8] ALI-2598: Show a folder's item count in the Size column A folder's Size cell now says how many items it holds: "8 items", "1 item", "Empty", or "10,000+ items" past the cap, where counting stops. It follows the show-hidden setting, and a screen reader reads it as the cell's text. - Counting is one listing of the folder, done on the listing's stat thread after each chunk's stats, only for rows on screen, so first paint is unchanged. Counts are kept per listing in a small map, so a folder of files costs nothing. - Each counted folder gets a one-shot inotify watch in a set the window polls. A change marks the count stale, and it's counted again 100 ms later; the old count shows meanwhile. Reading the folder again keeps the counts on screen showing until they're recounted. - Network places aren't counted: the folder's real path and the mount table decide, so NFS, SMB, GVfs and other FUSE mounts (but not fuseblk), autofs points and links into them stay blank. - Sorting by size counts every folder and orders folders by their count, still before files. Toggling hidden files re-sorts when sorted by size. - A long count reaches left of its column, and the name beside it is cut short of it. --- README.md | 8 + crates/app/src/a11y.rs | 12 +- crates/app/src/app.rs | 163 ++++++++++++++++-- crates/app/src/format.rs | 42 ++++- crates/app/src/main.rs | 28 ++- crates/app/src/paint.rs | 20 ++- crates/core/src/counts.rs | 342 +++++++++++++++++++++++++++++++++++++ crates/core/src/lib.rs | 1 + crates/core/src/listing.rs | 250 +++++++++++++++++++++++++-- tests/e2e.py | 47 +++++ 10 files changed, 868 insertions(+), 45 deletions(-) create mode 100644 crates/core/src/counts.rs diff --git a/README.md b/README.md index 78a85c7..2685198 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,14 @@ always come first. The preview window walks a folder in the order the list shows and Save dialogs from other apps read and save the same orders. The orders are kept in `$XDG_STATE_HOME/gannet/sorts`, which is `~/.local/state/gannet/sorts` by default. +A folder's Size says how many items it holds: "8 items", "1 item", "Empty", or "10,000+ items", +where counting stops. Hidden items count only while hidden files show. Only folders on screen +are counted, on a thread of their own after the rows show, so opening a folder is no slower. +Each folder counted is watched, so a change in it counts it again. Folders on network places +(SMB, SFTP, FTP, NFS, WebDAV and other FUSE mounts) aren't counted, as each count would be a +round trip, and their Size stays blank. Sorting by size counts every folder, and puts the +fullest first. + ## Dragging Drag files onto a folder in the list or a place in the sidebar. Dragging one selected item diff --git a/crates/app/src/a11y.rs b/crates/app/src/a11y.rs index 8ca7229..9f7aa84 100644 --- a/crates/app/src/a11y.rs +++ b/crates/app/src/a11y.rs @@ -327,6 +327,8 @@ pub struct Rows { pub columns: Vec, /// The column the list is sorted by, and whether it's in descending order. pub sort: (Column, bool), + /// Whether hidden files show, which a folder's count of items follows. + pub show_hidden: bool, } /// One of the file list's columns. @@ -375,7 +377,7 @@ impl PartialEq for Rows { (None, None) => true, _ => false, }; - self.era == o.era && same_listing && Arc::ptr_eq(&self.order, &o.order) && Arc::ptr_eq(&self.selected, &o.selected) && Arc::ptr_eq(&self.cut, &o.cut) && self.area == o.area && self.row_h == o.row_h && self.scroll == o.scroll && self.columns == o.columns && self.sort == o.sort + self.era == o.era && same_listing && Arc::ptr_eq(&self.order, &o.order) && Arc::ptr_eq(&self.selected, &o.selected) && Arc::ptr_eq(&self.cut, &o.cut) && self.area == o.area && self.row_h == o.row_h && self.scroll == o.scroll && self.columns == o.columns && self.sort == o.sort && self.show_hidden == o.show_hidden } } @@ -406,14 +408,14 @@ impl Rows { Some(if l.search().is_some() { crate::app::search_location(folder, &self.here.dir, &self.here.title) } else { crate::app::home_location(folder, self.here.home.as_deref()) }) } - /// What a row's cell in a column says, as the list shows it. A folder has no size, and a - /// file not looked at yet has none of either. + /// What a row's cell in a column says, as the list shows it. A folder's size is how many + /// items it holds, and a row not looked at yet has none of either. pub fn cell(&self, entry: u32, column: Column, now: i64) -> String { let Some(l) = self.listing.as_deref().filter(|l| (entry as usize) < l.len()) else { return String::new() }; match (column, l.stat(entry)) { (Column::Name, _) => self.name(entry), (Column::Location, _) => self.location(entry).unwrap_or_default(), - (Column::Size, Stat::Known { size, .. }) if !matches!(l.kind(entry), Kind::Dir | Kind::LinkDir) => crate::format::size(size), + (Column::Size, _) => crate::format::size_cell(l, entry, self.show_hidden), (Column::Modified, Stat::Known { mtime, .. }) => crate::format::date(mtime, now), (Column::Modified, Stat::Failed) => "unknown".into(), _ => String::new(), @@ -842,7 +844,7 @@ impl Link { SortKey::Size => Column::Size, SortKey::Modified => Column::Modified, }; - let rows = Rows { era: self.era, listing: app.listing.clone(), order, index, selected, cut: app.cut_paths.clone(), area: l.list, row_h: l.row_h.max(1), scroll: app.scroll, here: self.here.clone(), columns: columns(app, &l), sort: (column, sort.descending) }; + let rows = Rows { era: self.era, listing: app.listing.clone(), order, index, selected, cut: app.cut_paths.clone(), area: l.list, row_h: l.row_h.max(1), scroll: app.scroll, here: self.here.clone(), columns: columns(app, &l), sort: (column, sort.descending), show_hidden: app.show_hidden }; let place_h = app.place_h(); let places: Vec = app.places.iter().enumerate().map(|(i, p)| { diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index 7be24ed..4004848 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -57,6 +57,8 @@ const SMALL_BUTTON: f32 = size::SMALL_BUTTON; const DOUBLE_CLICK: Duration = motion::DOUBLE_CLICK; const TYPE_AHEAD_RESET: Duration = motion::TYPE_AHEAD_RESET; const HOLD_FOR_LOAD: Duration = motion::HOLD_FOR_LOAD; +/// How long after a counted folder changes it's counted again. +const RECOUNT_AFTER: Duration = Duration::from_millis(100); const JOB_SHOW_AFTER: Duration = motion::JOB_SHOW_AFTER; const UNDO_DEPTH: usize = 20; pub(crate) const DIALOG_GUARD: Duration = motion::DIALOG_GUARD; @@ -778,6 +780,11 @@ pub struct App { /// from another window. Many compositors keep the keyboard from a window during one. pub(crate) has_keyboard: bool, pub watch: Option>, + /// The watches on folders whose items are counted, which the window polls. + pub counts: Option>, + /// When the folders that changed are counted again: a moment after the first change, so a + /// burst of them is one count. + recount_at: Option, /// A re-sort is on its way, so a lighter request mustn't replace it. resort_pending: bool, /// A change arrived during a load, so another load follows it. @@ -981,6 +988,8 @@ impl App { mods_now: Mods::default(), has_keyboard: false, watch: None, + counts: None, + recount_at: None, resort_pending: false, reload_after_load: false, stater_gen: 0, @@ -1221,6 +1230,8 @@ impl App { self.sorted = c.sorted; self.rows = self.choosable(&c.listing, visible_rows(&c.listing, &self.sorted, self.show_hidden, &self.filter)); self.selected = vec![0; c.listing.len().div_ceil(64)]; + // Its folders weren't watched while it was away, so each is counted again. + c.listing.recount(None); self.new_stater(c.listing); self.place_pending_cursor(true, false); self.request_stats(); @@ -1293,6 +1304,11 @@ impl App { if self.hold_paint.is_some_and(|t| t <= now) { self.hold_paint = None; } + if self.recount_at.is_some_and(|t| t <= now) { + self.recount_at = None; + self.stats_range = (0, 0); + self.request_stats(); + } self.band_on_timer(now); self.side_scroll_on_timer(now); self.preview_on_timer(now); @@ -1312,7 +1328,7 @@ impl App { // A clash takes answers once it has been up a moment. Its buttons look and read the // same meanwhile, so the wake-up only ends the guard on time. let guard = self.dialog_guard.map(|t| t + DIALOG_GUARD).filter(|&t| t > Instant::now() && self.dialog.is_some()); - [self.reload_at, self.hold_paint, job, self.preview_deadline(), band, self.side_scroll_at, guard].into_iter().flatten().min() + [self.reload_at, self.hold_paint, self.recount_at, job, self.preview_deadline(), band, self.side_scroll_at, guard].into_iter().flatten().min() } fn on_loaded(&mut self, l: Loaded) { @@ -1425,10 +1441,15 @@ impl App { } else if self.req_hidden != self.show_hidden || self.req_filter != self.filter { self.rederive(false); } + self.clamp_scroll(); + // The folders on screen show what they held until they're counted again. + if let Some(o) = old.as_ref().filter(|_| same_dir) { + let (from, to) = self.stats_window(); + l.listing.adopt_counts(o, &self.rows[from..to]); + } if l.settled && l.listing.complete { self.remember(l.listing, l.sort); } - self.clamp_scroll(); self.stats_range = (0, 0); self.request_stats(); self.invalidate_all(); @@ -1458,7 +1479,9 @@ impl App { let hub = self.hub.clone(); self.stater_gen += 1; let generation = self.stater_gen; - self.stater = Stater::new(listing, move || hub.send(Msg::Stats(generation))); + // A new listing lets go of the last one's watches on counted folders. + let watch = self.counts.as_ref().map(|w| (w.clone(), w.begin())); + self.stater = Stater::counting(listing, watch, move || hub.send(Msg::Stats(generation))); self.stats_range = (0, 0); } @@ -1502,7 +1525,7 @@ impl App { let (hub, generation, sort, hidden, filter, cancel, sorted) = (self.hub.clone(), self.derive_gen, self.view_sort(), self.show_hidden, self.filter.clone(), self.derive_cancel.clone(), self.sorted.clone()); let choosing = self.chooser.as_ref().map(|c| c.rows.clone()); let spawned = std::thread::Builder::new().name("gannet-derive".into()).spawn(move || { - let sorted = if resort { Arc::new(sort_entries(&l, sort, &cancel)) } else { sorted }; + let sorted = if resort { Arc::new(sort_entries(&l, sort, hidden, &cancel)) } else { sorted }; let rows = visible_rows(&l, &sorted, hidden, &filter); let rows = match &choosing { Some(only) => only.keep_rows(&l, rows), @@ -1818,19 +1841,40 @@ impl App { self.thumbs.as_ref()?.picture(&l.path(id)) } - /// Asks for sizes and times of the rows on screen, and a screenful around them. - pub fn request_stats(&mut self) { - self.request_thumbnails(); - let (Some(l), Some(st)) = (self.listing.clone(), self.stater.as_ref()) else { return }; + /// The rows on screen, and half a screenful each side, whose sizes, times and counts are + /// wanted. + fn stats_window(&self) -> (usize, usize) { let row_h = self.layout().row_h.max(1) as f64; let cap = self.row_capacity(); let first = (self.scroll / row_h) as usize; - let range = (first.saturating_sub(cap / 2).min(self.rows.len()), (first + cap + cap / 2).min(self.rows.len())); + (first.saturating_sub(cap / 2).min(self.rows.len()), (first + cap + cap / 2).min(self.rows.len())) + } + + /// Folders whose items were counted changed: each is counted again shortly, showing what it + /// had until then. + pub fn counts_changed(&mut self) { + let Some(w) = self.counts.clone() else { return }; + let rows = w.drain(); + if rows.is_empty() { + return; + } + if let Some(l) = &self.listing { + l.recount(Some(&rows)); + } + self.recount_at.get_or_insert(Instant::now() + RECOUNT_AFTER); + } + + /// Asks for sizes and times of the rows on screen, and a screenful around them, and how + /// many items each folder among them holds. + pub fn request_stats(&mut self) { + self.request_thumbnails(); + let (Some(l), Some(st)) = (self.listing.clone(), self.stater.as_ref()) else { return }; + let range = self.stats_window(); if range == self.stats_range { return; } self.stats_range = range; - let ids: Vec = self.rows[range.0..range.1].iter().copied().filter(|&i| l.stat(i) == Stat::Unknown).collect(); + let ids: Vec = self.rows[range.0..range.1].iter().copied().filter(|&i| l.stat(i) == Stat::Unknown || l.wants_count(i)).collect(); if !ids.is_empty() { st.request(ids); } @@ -2354,7 +2398,8 @@ impl App { Action::Preview => self.open_preview(), Action::ToggleHidden => { self.show_hidden = !self.show_hidden; - self.rederive(false); + // Folders sorted by size go by the items that show. + self.rederive(self.view_sort().key == SortKey::Size); // Hidden folders are only searched when they show. if self.search_query().is_some() { self.start_load(); @@ -12810,6 +12855,94 @@ mod tests { app.paint(&mut crate::canvas::Canvas::new(&mut px, app.w, app.h)); } + /// What each row's Size cell says, by name, once every folder on screen is counted. + fn size_cells(r: &mut Rig) -> Vec<(String, String)> { + r.pump_until("counts known", |a| a.listing.as_ref().is_some_and(|l| a.rows.iter().all(|&e| !l.wants_count(e) && l.stat(e) != Stat::Unknown))); + let l = r.app.listing.clone().unwrap(); + r.app.rows.iter().map(|&i| (String::from_utf8_lossy(l.name(i)).into_owned(), crate::format::size_cell(&l, i, r.app.show_hidden))).collect() + } + + fn cells(v: &[(&str, &str)]) -> Vec<(String, String)> { + v.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect() + } + + #[test] + fn a_folders_size_is_how_many_items_it_holds_following_hidden_files() { + let mut r = Rig::new("counts"); + fs::create_dir(r.work().join("eight")).unwrap(); + for i in 0..8 { + fs::write(r.work().join("eight").join(i.to_string()), "").unwrap(); + } + fs::create_dir_all(r.work().join("one/sub")).unwrap(); + fs::create_dir(r.work().join("none")).unwrap(); + fs::create_dir(r.work().join("secret")).unwrap(); + fs::write(r.work().join("secret/.hidden"), "").unwrap(); + fs::write(r.work().join("file.txt"), "abc").unwrap(); + r.open(r.work()); + assert_eq!(size_cells(&mut r), cells(&[("eight", "8 items"), ("none", "Empty"), ("one", "1 item"), ("secret", "Empty"), ("file.txt", "3 B")])); + r.app.action(Action::ToggleHidden); + r.pump_until("hidden shown", |a| a.show_hidden); + assert_eq!(size_cells(&mut r).iter().find(|(n, _)| n == "secret").unwrap().1, "1 item", "a hidden file counts once hidden files show"); + } + + #[test] + fn sorting_by_size_keeps_folders_first_ordered_by_how_many_items_they_hold() { + let mut r = Rig::new("counts-sort"); + for (dir, n) in [("a", 3), ("b", 1), ("c", 5)] { + fs::create_dir(r.work().join(dir)).unwrap(); + for i in 0..n { + fs::write(r.work().join(dir).join(i.to_string()), "").unwrap(); + } + } + fs::write(r.work().join("big.bin"), vec![0u8; 5000]).unwrap(); + fs::write(r.work().join("small.txt"), "x").unwrap(); + r.open(r.work()); + r.app.action(Action::SortBy(SortKey::Size)); + r.pump_until("sorted by size", |a| a.sort.key == SortKey::Size && !a.loading && a.rows.len() == 5 && !a.resort_pending); + assert_eq!(r.row_names(), ["c", "a", "b", "big.bin", "small.txt"], "biggest first, folders before files"); + r.app.action(Action::SortBy(SortKey::Size)); + r.pump_until("reversed", |a| !a.sort.descending && !a.resort_pending); + assert_eq!(r.row_names(), ["b", "a", "c", "small.txt", "big.bin"]); + } + + #[test] + fn a_change_in_a_counted_folder_counts_it_again_without_reading_the_folder_showing() { + let mut r = Rig::new("counts-watch"); + r.app.counts = Some(Arc::new(gannet_core::counts::Watches::new().unwrap())); + fs::create_dir(r.work().join("sub")).unwrap(); + r.open(r.work()); + assert_eq!(size_cells(&mut r), cells(&[("sub", "Empty")])); + let loads = r.app.loads(); + fs::write(r.work().join("sub/new.txt"), "").unwrap(); + // The window polls the watches; here they're drained as it would on hearing from them. + let cell = |a: &App| a.listing.as_ref().map(|l| crate::format::size_cell(l, a.rows[0], false)).unwrap_or_default(); + let end = Instant::now() + Duration::from_secs(10); + while cell(&r.app) != "1 item" { + assert!(Instant::now() < end, "timed out: counted again"); + r.app.counts_changed(); + assert!(!cell(&r.app).is_empty(), "the old count shows until the new one"); + if let Ok(m) = r.rx.recv_timeout(Duration::from_millis(20)) { + r.app.on_msg(m); + } + r.app.on_timer(Instant::now()); + } + assert_eq!(r.app.loads(), loads, "only the folder that changed is read again"); + } + + #[test] + fn reading_the_folder_again_keeps_its_counts_showing() { + let mut r = Rig::new("counts-reload"); + fs::create_dir(r.work().join("sub")).unwrap(); + fs::write(r.work().join("sub/x"), "").unwrap(); + r.open(r.work()); + assert_eq!(size_cells(&mut r), cells(&[("sub", "1 item")])); + let old = r.app.listing.clone().unwrap(); + r.app.reload(); + r.pump_until("read again", |a| a.listing.as_ref().is_some_and(|l| !Arc::ptr_eq(l, &old))); + let l = r.app.listing.clone().unwrap(); + assert_eq!(crate::format::size_cell(&l, r.app.rows[0], false), "1 item", "shown from the last reading until it's counted again"); + } + #[test] fn a_screen_reader_reads_the_list_as_a_table_and_sorts_by_its_headings() { use crate::a11y::{Act, Column, Role, COLUMN_LOCATION, COLUMN_MODIFIED, COLUMN_NAME, COLUMN_SIZE, FRAME, LIST}; @@ -12817,7 +12950,7 @@ mod tests { fs::write(r.work().join("a.txt"), "aaaa").unwrap(); fs::create_dir(r.work().join("sub")).unwrap(); r.open(r.work()); - r.pump_until("sizes known", |a| a.listing.as_ref().is_some_and(|l| a.rows.iter().all(|&e| matches!(l.stat(e), Stat::Known { .. })))); + r.pump_until("sizes and counts known", |a| a.listing.as_ref().is_some_and(|l| a.rows.iter().all(|&e| matches!(l.stat(e), Stat::Known { .. }) && !l.wants_count(e)))); let s = a11y_snapshot(&mut r.app); assert_eq!(s.get(LIST).map(|n| n.role), Some(Role::Table)); assert_eq!(s.get(LIST).unwrap().name, s.get(FRAME).unwrap().name.trim_end_matches(" - Gannet"), "the table is named for its folder"); @@ -12827,16 +12960,16 @@ mod tests { let size = s.get(COLUMN_SIZE).unwrap(); assert_eq!((size.role, size.action.map(|a| a.keys)), (Role::ColumnHeader, Some("2"))); assert_eq!(s.rows.sort, (Column::Name, false)); - // Each row's cells read as the list shows them: a folder has no size. + // Each row's cells read as the list shows them: a folder's size is how many items it holds. let now = gannet_core::time::now(); let (sub, a) = (s.rows.entry(0).unwrap(), s.rows.entry(1).unwrap()); assert_eq!((s.rows.name(a), s.rows.cell(a, Column::Size, now)), ("a.txt".to_string(), "4 B".to_string())); - assert_eq!(s.rows.cell(sub, Column::Size, now), ""); + assert_eq!(s.rows.cell(sub, Column::Size, now), "Empty"); let date = s.rows.cell(a, Column::Modified, now); assert!(!date.is_empty()); assert_eq!(s.rows.summary(a, now), format!("4 B, {date}"), "the row says its other cells"); // A folder says so first, as its icon does: its name alone can't tell it from a file. - assert_eq!(s.rows.summary(sub, now), format!("folder, {date}")); + assert_eq!(s.rows.summary(sub, now), format!("folder, Empty, {date}")); // A heading sorts by its column, as a click does, and the new order is news. r.app.on_msg(Msg::A11y(Act::Press(COLUMN_SIZE))); r.pump_until("sorted by size", |a| a.sort.key == SortKey::Size && !a.rows.is_empty()); diff --git a/crates/app/src/format.rs b/crates/app/src/format.rs index 150f1e0..a45a1b3 100644 --- a/crates/app/src/format.rs +++ b/crates/app/src/format.rs @@ -1,5 +1,7 @@ //! How sizes and dates read. +use gannet_core::counts::CAP; +use gannet_core::listing::{Listing, Stat}; use gannet_core::time::{Local, local}; /// Sizes in decimal units. Core has it, as its messages say sizes too. @@ -24,13 +26,41 @@ fn date_parts(t: Local, now: Local) -> String { } pub fn count(n: usize, one: &str, many: &str) -> String { + format!("{} {}", grouped(n), if n == 1 { one } else { many }) +} + +/// `12,345`. +fn grouped(n: usize) -> String { let mut digits = n.to_string(); let mut i = digits.len() as isize - 3; while i > 0 { digits.insert(i as usize, ','); i -= 3; } - format!("{digits} {}", if n == 1 { one } else { many }) + digits +} + +/// How many items a folder holds: `Empty`, `1 item`, `8 items`, or `10,000+ items` past the +/// most that's counted. +pub fn items(n: u32) -> String { + match n { + 0 => "Empty".into(), + n if n > CAP => format!("{}+ items", grouped(CAP as usize)), + n => count(n as usize, "item", "items"), + } +} + +/// What a row's Size cell says, as the list shows it and a screen reader reads it: a file's +/// size, or how many items a folder holds, by the show-hidden setting. Empty until it's known, +/// and for good for a folder on a network place. +pub fn size_cell(l: &Listing, id: u32, show_hidden: bool) -> String { + if l.kind(id).is_dirlike() { + return l.items(id, show_hidden).map(items).unwrap_or_default(); + } + match l.stat(id) { + Stat::Known { size: bytes, .. } => size(bytes), + _ => String::new(), + } } #[cfg(test)] @@ -56,4 +86,14 @@ mod tests { assert_eq!(count(1234567, "x", "xs"), "1,234,567 xs"); assert_eq!(count(999, "x", "xs"), "999 xs"); } + + #[test] + fn folder_counts_read_well() { + assert_eq!(items(0), "Empty"); + assert_eq!(items(1), "1 item"); + assert_eq!(items(8), "8 items"); + assert_eq!(items(1234), "1,234 items"); + assert_eq!(items(CAP), "10,000 items"); + assert_eq!(items(CAP + 1), "10,000+ items"); + } } diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 4587e9f..34eeb14 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -245,6 +245,8 @@ fn main() { app.servers_file = Some(d.state.join("gannet/servers")); let dir_watch = Watch::threaded().ok().map(Arc::new); app.watch = dir_watch.clone(); + let count_watch = gannet_core::counts::Watches::new().ok().map(Arc::new); + app.counts = count_watch.clone(); app.cache_home = Some(d.cache.clone()); app.terminal = gannet_core::terminal::Terminal::find(std::env::var_os("PATH").as_deref(), std::env::var_os("XDG_RUNTIME_DIR").as_deref().map(Path::new)); app.kinds = Arc::new(preview::Kinds::new(d.mime.clone(), language()).with_thumbnailers(d.thumbnailers.clone())); @@ -458,6 +460,10 @@ fn main() { fds.push(PollFd::from_borrowed_fd(w.as_ref().as_fd(), PollFlags::IN)); fds.len() - 1 }); + let counts_at = count_watch.as_ref().map(|w| { + fds.push(PollFd::from_borrowed_fd(w.as_ref().as_fd(), PollFlags::IN)); + fds.len() - 1 + }); let theme_at = theme_watch.as_ref().map(|w| { fds.push(PollFd::from_borrowed_fd(w.watch.as_fd(), PollFlags::IN)); fds.len() - 1 @@ -476,6 +482,7 @@ fn main() { let wl_hup = fds[0].revents().intersects(PollFlags::HUP | PollFlags::ERR); let repeat_ready = repeat_at.is_some_and(ready); let dir_ready = dir_at.is_some_and(ready); + let counts_ready = counts_at.is_some_and(ready); let theme_ready = theme_at.is_some_and(ready); let bookmarks_ready = bookmarks_at.is_some_and(ready); let settings_ready = settings_at.is_some_and(ready); @@ -504,6 +511,9 @@ fn main() { if dir_ready && dir_watch.as_ref().is_some_and(|w| w.drain()) { app.folder_changed(); } + if counts_ready { + app.counts_changed(); + } if bookmarks_ready && bookmarks_watch.as_mut().is_some_and(gannet_core::watch::ConfigWatch::changed) { app.bookmarks_changed(); } @@ -742,6 +752,8 @@ mod bench { /// The search results last reported: what for, how many, and whether they were all. search_stamped: Option<(String, usize, bool)>, thumbs_stamped: (usize, usize), + /// How many folders on screen show their count, of how many folders are on screen. + counts_stamped: (usize, usize), } pub fn mono_ms() -> f64 { @@ -761,6 +773,7 @@ mod bench { loads_stamped: 0, search_stamped: None, thumbs_stamped: (0, 0), + counts_stamped: (0, 0), } } @@ -780,6 +793,18 @@ mod bench { if !ready { self.rows_stamped = None; } + // The folders on screen that show their count, as each paint shows more. + if let Some(l) = app.listing.as_ref().filter(|_| self.log.is_some()) { + let row_h = app.layout().row_h.max(1); + let first = (app.scroll / row_h as f64) as usize; + let on_screen = (app.layout().list.h / row_h + 1) as usize; + let dirs = app.rows.iter().skip(first).take(on_screen).filter(|&&i| l.kind(i).is_dirlike()); + let (known, all) = dirs.fold((0, 0), |(k, a), &i| (k + usize::from(l.items(i, app.show_hidden).is_some()), a + 1)); + if (known, all) != self.counts_stamped { + self.counts_stamped = (known, all); + self.stamp(format!("counts {known} {all} {:.1}", mono_ms())); + } + } // Each time the folder is read again, as when a change to it is seen. if app.loads() != self.loads_stamped { self.loads_stamped = app.loads(); @@ -889,11 +914,12 @@ mod bench { Edit::NewFolder(f) => format!("newfolder:{}", f.text), }; format!( - "{{\"dir\":{},\"loading\":{},\"count\":{},\"names\":{},\"cursor\":{},\"cursor_shown\":{},\"selected\":{},\"filter\":{},\"edit\":{},\"name_error\":{},\"hidden\":{},\"sort\":{},\"desc\":{},\"scroll\":{},\"notices\":{},\"menu\":{},\"menu_items\":{},\"error\":{},\"base\":{},\"can_back\":{},\"can_forward\":{},\"jobs\":{},\"visible_jobs\":{},\"dialog\":{},\"undo\":{},\"redo\":{},\"panel\":{},\"preview\":{},\"previewing\":{},\"drag\":{},\"places\":{},\"headings\":{},\"side_scroll\":{},\"side_max\":{},\"chooser\":{},\"searching\":{},\"found\":{},\"locations\":{},\"status\":{},\"thumbs\":{},\"side_focus\":{},\"server\":{},\"suggest\":{},\"message\":{},\"targets\":{}}}\n", + "{{\"dir\":{},\"loading\":{},\"count\":{},\"names\":{},\"sizes\":{},\"cursor\":{},\"cursor_shown\":{},\"selected\":{},\"filter\":{},\"edit\":{},\"name_error\":{},\"hidden\":{},\"sort\":{},\"desc\":{},\"scroll\":{},\"notices\":{},\"menu\":{},\"menu_items\":{},\"error\":{},\"base\":{},\"can_back\":{},\"can_forward\":{},\"jobs\":{},\"visible_jobs\":{},\"dialog\":{},\"undo\":{},\"redo\":{},\"panel\":{},\"preview\":{},\"previewing\":{},\"drag\":{},\"places\":{},\"headings\":{},\"side_scroll\":{},\"side_max\":{},\"chooser\":{},\"searching\":{},\"found\":{},\"locations\":{},\"status\":{},\"thumbs\":{},\"side_focus\":{},\"server\":{},\"suggest\":{},\"message\":{},\"targets\":{}}}\n", esc(&a.dir.to_string_lossy()), a.loading, a.rows.len(), list(a.rows.iter().take(300).map(|&i| name(i))), + list(a.rows.iter().take(300).map(|&i| a.listing.as_ref().map_or_else(String::new, |l| crate::format::size_cell(l, i, a.show_hidden)))), a.cursor, a.cursor_shown, list(a.selected_ids().into_iter().take(300).map(name)), diff --git a/crates/app/src/paint.rs b/crates/app/src/paint.rs index 00fc803..704614a 100644 --- a/crates/app/src/paint.rs +++ b/crates/app/src/paint.rs @@ -1,6 +1,6 @@ //! Drawing the window. Each part checks the clip first, so a small change repaints little. -use gannet_core::listing::{Kind, SortKey, Stat}; +use gannet_core::listing::{SortKey, Stat}; use gannet_core::places::PlaceKind; use gannet_core::time; use gannet_core::tokens::{radius, scale, size, spacing}; @@ -626,6 +626,12 @@ impl App { } let shown = String::from_utf8_lossy(name); let by = y + ((row_h as f32 + self.text.ascent - self.text.descent) / 2.0).round() as i32; + // A file's size, or how many items a folder holds. A long count, like "10,000+ + // items", reaches left of its column, and the name beside it stops short of it. + let size_text = format::size_cell(&listing, id, self.show_hidden); + let size_w = if size_text.is_empty() { 0.0 } else { self.text.measure(&size_text) }; + let size_left = (date_x - self.px(spacing::SPACE_16)) as f32 - size_w; + let row_name_max = if origin.is_none() { name_max.min(size_left - (self.px(spacing::SPACE_10) + name_x) as f32) } else { name_max }; // Recent's and the Trash's rows are each somewhere of their own. let is_cut = !self.cut_paths.is_empty() && { let here = listing.path(id); @@ -649,7 +655,7 @@ impl App { let box_h = (row_h - self.px(spacing::SPACE_2)).max(1); self.paint_field(c, Rect::new(name_x - self.px(spacing::SPACE_4), y + 1, name_max as i32 + self.px(spacing::SPACE_8), box_h), &f, true); } else { - self.text.draw_fitted(c, &shown, name_x as f32, by, name_max, if is_cut { dim } else { fg }); + self.text.draw_fitted(c, &shown, name_x as f32, by, row_name_max, if is_cut { dim } else { fg }); } if let Some((ox, ow)) = origin && let Some(folder) = listing.location(id) @@ -657,13 +663,11 @@ impl App { let shown = if listing.search().is_some() { self.search_location(folder) } else { crate::app::home_location(folder, home.as_deref()) }; self.text.draw_fitted(c, &shown, ox as f32, by, ow as f32, dim); } + if !size_text.is_empty() { + self.text.draw_str(c, &size_text, size_left, by, dim); + } match listing.stat(id) { - Stat::Known { size, mtime } => { - if !matches!(kind, Kind::Dir | Kind::LinkDir) { - let s = format::size(size); - let w = self.text.measure(&s); - self.text.draw_str(c, &s, (date_x - self.px(spacing::SPACE_16)) as f32 - w, by, dim); - } + Stat::Known { mtime, .. } => { let d = format::date(mtime, now); self.text.draw_str(c, &d, date_x as f32, by, dim); } diff --git a/crates/core/src/counts.rs b/crates/core/src/counts.rs new file mode 100644 index 0000000..68c29ee --- /dev/null +++ b/crates/core/src/counts.rs @@ -0,0 +1,342 @@ +//! How many items a folder holds, for a folder's Size cell, and the watches that keep those +//! counts up to date. +//! +//! A count is one listing of the folder, stopped at `CAP`, so a huge folder costs no more than +//! a small one. Counting happens only for rows on screen, on the listing's stat thread, and +//! never on network places, where each count would be a round trip. Each folder counted is +//! watched, in one inotify set the window polls, so a change in it counts it again; nothing is +//! read while nothing changes. + +use std::collections::HashMap; +use std::ffi::CStr; +use std::mem::MaybeUninit; +use std::os::unix::ffi::OsStrExt; +use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd}; +use std::path::{Component, Path, PathBuf}; +use std::sync::Mutex; + +use rustix::fs::{Mode, OFlags, RawDir}; +use rustix::fs::inotify::{self, CreateFlags, ReadFlags, WatchFlags}; +use rustix::io::Errno; + +use crate::mounts::Mount; + +/// Past this many, a folder says "10,000+ items", and counting it stops. +pub const CAP: u32 = 10_000; + +/// How many items a folder holds, each capped at `CAP + 1`: all of them, and those that +/// aren't hidden. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Count { + pub all: u32, + pub shown: u32, +} + +impl Count { + /// The count the list shows, by the show-hidden setting. + pub fn items(self, show_hidden: bool) -> u32 { + if show_hidden { self.all } else { self.shown } + } +} + +/// Counts the folder `name` in `dir`, with `buf` to read into. The folder is opened first and +/// handed to `opened`, to be watched before it's read, so a change during the count isn't +/// missed. Reading stops once more than `CAP` items that aren't hidden are found. +pub fn count_in(dir: BorrowedFd<'_>, name: &CStr, buf: &mut [MaybeUninit], opened: impl FnOnce(BorrowedFd<'_>)) -> Option { + // O_NONBLOCK and O_DIRECTORY: anything that isn't a folder fails at once, and nothing hangs + // opening it. NOFOLLOW isn't set, as a link to a folder is counted as the folder. + let fd = rustix::fs::openat(dir, name, OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NONBLOCK | OFlags::CLOEXEC, Mode::empty()).ok()?; + opened(fd.as_fd()); + count_open(&fd, buf) +} + +fn count_open(fd: &OwnedFd, buf: &mut [MaybeUninit]) -> Option { + let mut c = Count { all: 0, shown: 0 }; + let mut iter = RawDir::new(fd, buf); + while let Some(e) = iter.next() { + let e = e.ok()?; + let n = e.file_name().to_bytes(); + if n == b"." || n == b".." { + continue; + } + c.all = c.all.saturating_add(1); + if n.first() != Some(&b'.') { + c.shown += 1; + if c.shown > CAP { + break; + } + } + } + c.all = c.all.min(CAP + 1); + Some(c) +} + +/// Whether folders on this kind of filesystem go uncounted: network shares, where each count +/// is a round trip, and anything through FUSE but a local disk's (`fuseblk`, as ntfs-3g is), +/// as GVfs, sshfs and rclone are all FUSE. An automount point that isn't mounted yet is +/// `autofs`, and counting it would mount it. +pub fn uncounted(fs_type: &str) -> bool { + fs_type == "autofs" || (crate::mounts::inodes_may_change(fs_type) && fs_type != "fuseblk") +} + +/// Where a folder's rows may be counted: the folder's real path and what's mounted, read once +/// for each listing from the kernel's memory, which touches no disk. +pub struct Policy { + /// `None` when the folder itself is on a network place: nothing in it is counted. + real: Option, + mounts: Vec, +} + +impl Policy { + pub fn new(real: Option, mounts: Vec) -> Self { + let real = real.filter(|r| fs_type_of(&mounts, r).is_none_or(|t| !uncounted(t))); + Self { real, mounts } + } + + /// Whether a row may be counted: a folder, or a link to one, and not a network place + /// mounted there or one a link points into. A link is resolved by its text alone, so + /// checking it can't hang on the place it points to. + pub fn allows(&self, name: &[u8], link: Option<&Path>) -> bool { + let Some(real) = &self.real else { return false }; + let path = match link { + Some(target) => lexical(&real.join(target)), + None => real.join(std::ffi::OsStr::from_bytes(name)), + }; + fs_type_of(&self.mounts, &path).is_none_or(|t| !uncounted(t)) + } +} + +fn fs_type_of<'a>(mounts: &'a [Mount], path: &Path) -> Option<&'a str> { + mounts.iter().filter(|m| path.starts_with(&m.point)).max_by_key(|m| m.point.as_os_str().len()).map(|m| m.fs_type.as_str()) +} + +/// `..` and `.` taken out of a path, by its text. +fn lexical(p: &Path) -> PathBuf { + let mut out = PathBuf::new(); + for c in p.components() { + match c { + Component::ParentDir => { + out.pop(); + } + Component::CurDir => {} + c => out.push(c), + } + } + out +} + +/// How many folders one listing watches at most. Scrolling through a folder of more folders +/// than this still counts each, but only these many are kept up to date until it's read again. +const MAX_WATCHES: usize = 1024; + +/// What a change in a counted folder looks like. A watch goes after its first event, as +/// `ONESHOT`, and counting the folder again watches it again, so a busy folder wakes the +/// window at most once each time it's counted. +const MASK: WatchFlags = WatchFlags::CREATE.union(WatchFlags::DELETE).union(WatchFlags::MOVED_FROM).union(WatchFlags::MOVED_TO).union(WatchFlags::ONLYDIR).union(WatchFlags::ONESHOT); + +/// The watches on counted folders. The window polls `as_fd`, and `drain` says which rows' +/// folders changed. Each listing starts a new generation, which lets go of the last one's +/// watches; a stat thread still counting for an old listing can't add to the new one. +pub struct Watches { + fd: OwnedFd, + inner: Mutex, +} + +#[derive(Default)] +struct Inner { + generation: u64, + /// Each watch, and the rows it's for: two rows can be one folder, as a link to it is. + rows: HashMap>, +} + +impl Watches { + pub fn new() -> rustix::io::Result { + let fd = inotify::init(CreateFlags::CLOEXEC | CreateFlags::NONBLOCK)?; + Ok(Self { fd, inner: Mutex::new(Inner::default()) }) + } + + /// Lets go of every watch, for a new listing, and returns its generation. + pub fn begin(&self) -> u64 { + let Ok(mut inner) = self.inner.lock() else { return 0 }; + for wd in std::mem::take(&mut inner.rows).into_keys() { + let _ = inotify::remove_watch(&self.fd, wd); + } + inner.generation += 1; + inner.generation + } + + /// Watches an open folder for a row of the listing of `generation`, unless a newer listing + /// has started. Added through `/proc/self/fd`, so no name is looked up. + pub fn add(&self, generation: u64, folder: BorrowedFd<'_>, row: u32) { + let Ok(mut inner) = self.inner.lock() else { return }; + if inner.generation != generation || inner.rows.len() >= MAX_WATCHES { + return; + } + let Ok(wd) = inotify::add_watch(&self.fd, format!("/proc/self/fd/{}", folder.as_raw_fd()), MASK) else { return }; + let rows = inner.rows.entry(wd).or_default(); + if !rows.contains(&row) { + rows.push(row); + } + } + + /// The rows whose folders changed since last asked, from everything pending. Never blocks. + pub fn drain(&self) -> Vec { + let mut wds = Vec::new(); + let mut buf = [MaybeUninit::::uninit(); 4096]; + loop { + let mut reader = inotify::Reader::new(&self.fd, &mut buf); + match reader.next() { + Ok(ev) => { + let mut take = |ev: &inotify::Event<'_>| { + if ev.events().contains(ReadFlags::QUEUE_OVERFLOW) { + wds.push(-1); + } else if !ev.events().contains(ReadFlags::IGNORED) { + wds.push(ev.wd()); + } + }; + take(&ev); + while let Ok(ev) = reader.next() { + take(&ev); + } + } + Err(Errno::INTR) => continue, + Err(_) => break, + } + } + let Ok(mut inner) = self.inner.lock() else { return Vec::new() }; + let mut out = Vec::new(); + // Events were lost: every folder watched counts again. + if wds.contains(&-1) { + wds = inner.rows.keys().copied().collect(); + } + for wd in wds { + // A watch fires once, so it's gone; counting again watches it again. + if let Some(rows) = inner.rows.remove(&wd) { + out.extend(rows); + } + } + out + } + + /// How many folders are watched, for tests. + pub fn len(&self) -> usize { + self.inner.lock().map_or(0, |i| i.rows.len()) + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +impl AsFd for Watches { + fn as_fd(&self) -> BorrowedFd<'_> { + self.fd.as_fd() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::Scratch; + use std::fs; + + fn count(dir: &Path, name: &str) -> Option { + let d = fs::File::open(dir).unwrap(); + let mut buf = vec![MaybeUninit::uninit(); 32 * 1024]; + count_in(d.as_fd(), &std::ffi::CString::new(name).unwrap(), &mut buf, |_| {}) + } + + #[test] + fn counts_items_hidden_ones_apart() { + let s = Scratch::new(); + s.file("f/a", b""); + s.file("f/.b", b""); + s.dir("f/sub"); + s.dir("empty"); + assert_eq!(count(s.path(), "f"), Some(Count { all: 3, shown: 2 })); + assert_eq!(count(s.path(), "empty"), Some(Count { all: 0, shown: 0 })); + assert_eq!(count(s.path(), "f").unwrap().items(false), 2); + assert_eq!(count(s.path(), "f").unwrap().items(true), 3); + } + + #[test] + fn a_file_or_a_missing_folder_isnt_counted() { + let s = Scratch::new(); + s.file("plain", b"x"); + assert_eq!(count(s.path(), "plain"), None); + assert_eq!(count(s.path(), "nothing"), None); + } + + #[test] + fn counting_stops_past_the_cap() { + let s = Scratch::new(); + let big = s.dir("big"); + for i in 0..CAP + 5 { + fs::File::create(big.join(i.to_string())).unwrap(); + } + assert_eq!(count(s.path(), "big"), Some(Count { all: CAP + 1, shown: CAP + 1 })); + } + + #[test] + fn a_link_to_a_folder_is_counted_as_the_folder() { + let s = Scratch::new(); + s.file("real/x", b""); + std::os::unix::fs::symlink(s.path().join("real"), s.path().join("link")).unwrap(); + assert_eq!(count(s.path(), "link"), Some(Count { all: 1, shown: 1 })); + } + + fn mount(point: &str, fs_type: &str) -> Mount { + Mount { point: point.into(), fs_type: fs_type.into(), source: String::new() } + } + + #[test] + fn network_places_and_what_points_into_them_arent_counted() { + let mounts = vec![mount("/", "ext4"), mount("/home/me/nas", "nfs4"), mount("/run/user/1000/gvfs", "fuse.gvfsd-fuse"), mount("/mnt/win", "fuseblk"), mount("/mnt/auto", "autofs")]; + let home = Policy::new(Some("/home/me".into()), mounts.clone()); + assert!(home.allows(b"Documents", None)); + assert!(!home.allows(b"nas", None), "a share mounted in the folder"); + assert!(!home.allows(b"films", Some(Path::new("nas/films"))), "a link into a share"); + assert!(!home.allows(b"up", Some(Path::new("../me/nas"))), "a link into a share, by way of .."); + assert!(home.allows(b"docs", Some(Path::new("/home/me/Documents")))); + assert!(!Policy::new(Some("/run/user/1000/gvfs/smb-share:server=nas".into()), mounts.clone()).allows(b"photos", None), "inside a GVfs share"); + assert!(!Policy::new(Some("/home/me/nas/films".into()), mounts.clone()).allows(b"x", None), "inside an NFS share"); + assert!(Policy::new(Some("/mnt/win".into()), mounts.clone()).allows(b"x", None), "a local disk through FUSE"); + assert!(!Policy::new(Some("/mnt".into()), mounts.clone()).allows(b"auto", None), "an automount that isn't mounted yet"); + assert!(!Policy::new(None, mounts).allows(b"x", None), "a folder with no real path"); + } + + #[test] + fn a_change_in_a_watched_folder_names_its_rows_once() { + let s = Scratch::new(); + let sub = s.dir("sub"); + let w = Watches::new().unwrap(); + let g = w.begin(); + let d = fs::File::open(s.path()).unwrap(); + let mut buf = vec![MaybeUninit::uninit(); 4096]; + count_in(d.as_fd(), c"sub", &mut buf, |f| w.add(g, f, 7)).unwrap(); + assert_eq!(w.drain(), Vec::::new(), "counting isn't a change"); + fs::File::create(sub.join("new")).unwrap(); + assert_eq!(w.drain(), [7]); + fs::File::create(sub.join("newer")).unwrap(); + assert_eq!(w.drain(), Vec::::new(), "a watch fires once, until counted again"); + } + + #[test] + fn a_new_listing_lets_go_of_the_old_ones_watches() { + let s = Scratch::new(); + let sub = s.dir("sub"); + let w = Watches::new().unwrap(); + let old = w.begin(); + let d = fs::File::open(s.path()).unwrap(); + let mut buf = vec![MaybeUninit::uninit(); 4096]; + count_in(d.as_fd(), c"sub", &mut buf, |f| w.add(old, f, 1)).unwrap(); + assert_eq!(w.len(), 1); + let new = w.begin(); + assert!(w.is_empty()); + count_in(d.as_fd(), c"sub", &mut buf, |f| w.add(old, f, 1)).unwrap(); + assert!(w.is_empty(), "an old listing's thread can't add to the new one"); + count_in(d.as_fd(), c"sub", &mut buf, |f| w.add(new, f, 2)).unwrap(); + fs::File::create(sub.join("x")).unwrap(); + assert_eq!(w.drain(), [2]); + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 2c954a6..8a5a7e7 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -8,6 +8,7 @@ pub mod bookmarks; pub mod bus; pub mod cli; pub mod clipboard; +pub mod counts; pub mod disks; pub mod folder_sorts; pub mod foldersize; diff --git a/crates/core/src/listing.rs b/crates/core/src/listing.rs index 203e571..5165c9f 100644 --- a/crates/core/src/listing.rs +++ b/crates/core/src/listing.rs @@ -14,11 +14,13 @@ use std::os::unix::ffi::{OsStrExt, OsStringExt}; use std::os::unix::fs::OpenOptionsExt; use std::path::{Path, PathBuf}; use std::sync::atomic::{self, AtomicBool, AtomicI64, AtomicU64, AtomicUsize}; -use std::sync::{Arc, mpsc}; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock, mpsc}; use std::time::{Duration, Instant}; use rustix::fs::{AtFlags, FileType, RawDir, StatxFlags, statat, statx}; +use crate::counts::{self, Count, Watches}; use crate::mounts::read_mounts; use crate::sort::{natural_cmp, par_sort_by}; use crate::trash::{self, Info, Root, Trashed}; @@ -81,6 +83,19 @@ pub struct Listing { recent: Option>>, /// Set for search results, whose rows are anywhere below `dir`. search: Option>, + /// How many items each folder counted so far holds, by row. Only rows on screen are + /// counted, so this stays small, and a listing with no folders on screen has none. + counts: Mutex>, + /// Where rows may be counted, worked out on the first count. + policy: OnceLock, +} + +/// A row's count: `None` if it isn't counted, as on a network place, or couldn't be read. A +/// stale one is shown until it's counted again, so a recount doesn't blank the cell. +#[derive(Clone, Copy, Debug)] +struct Counted { + count: Option, + stale: bool, } /// What a search found: each row's path, and what was asked. @@ -308,6 +323,131 @@ impl Listing { }); } + /// Whether this view's folders are counted: a folder's own listing, not the Trash, Recent + /// or search results. + fn counts_folders(&self) -> bool { + self.fd.is_some() && self.trash.is_none() && self.paths().is_none() + } + + /// How many items a folder's row holds, as its Size cell says, by the show-hidden setting: + /// up to `counts::CAP`, or more than that. `None` until it's counted, and for good on a + /// network place. + pub fn items(&self, i: u32, show_hidden: bool) -> Option { + let counts = self.counts.lock().ok()?; + Some(counts.get(&i)?.count?.items(show_hidden)) + } + + /// Whether a row is a folder still to count, or to count again. + pub fn wants_count(&self, i: u32) -> bool { + self.kind(i).is_dirlike() && self.counts_folders() && self.counts.lock().is_ok_and(|c| c.get(&i).is_none_or(|c| c.stale)) + } + + /// Where rows may be counted: nowhere on a network place. Where the folder really is comes + /// from the kernel's record of the open folder, and what's mounted from its memory too. + fn policy(&self) -> &counts::Policy { + self.policy.get_or_init(|| { + use std::os::fd::AsRawFd; + let real = self.fd.as_ref().filter(|_| self.counts_folders()).and_then(|f| std::fs::read_link(format!("/proc/self/fd/{}", f.as_raw_fd())).ok()); + let mounts = if real.is_some() { read_mounts() } else { Vec::new() }; + counts::Policy::new(real, mounts) + }) + } + + /// Counts a folder's row if it needs it; true if it did. A count is watched for changes + /// with `watch`, for the listing of its generation. + fn count_one(&self, i: u32, buf: &mut Vec>, watch: Option<(&Watches, u64)>) -> bool { + if !self.wants_count(i) { + return false; + } + let Some(fd) = self.fd.as_ref() else { return false }; + let name = self.name(i); + let link = if self.kind(i) == Kind::LinkDir { CString::new(name).ok().and_then(|n| rustix::fs::readlinkat(fd.as_fd(), n.as_c_str(), Vec::new()).ok()) } else { None }; + let allowed = (self.kind(i) == Kind::Dir || link.is_some()) && self.policy().allows(name, link.as_deref().map(|l| Path::new(OsStr::from_bytes(l.to_bytes())))); + let count = if allowed { + if buf.is_empty() { + buf.resize(READ_BUFFER, MaybeUninit::uninit()); + } + CString::new(name).ok().and_then(|n| counts::count_in(fd.as_fd(), n.as_c_str(), buf, |f| if let Some((w, generation)) = watch { w.add(generation, f, i) })) + } else { + None + }; + if let Ok(mut counts) = self.counts.lock() { + counts.insert(i, Counted { count, stale: false }); + } + true + } + + /// Counts the given rows that are folders still to count; true if any were. + pub fn count_entries(&self, ids: &[u32], buf: &mut Vec>, watch: Option<(&Watches, u64)>) -> bool { + let mut any = false; + for &i in ids { + any |= self.count_one(i, buf, watch); + } + any + } + + /// Counts every folder, as sorting by size needs, on several threads, with nothing watched. + /// Stops early if `cancel` gets set. + pub fn count_all(&self, cancel: &AtomicBool) { + if !self.counts_folders() { + return; + } + let dirs: Vec = (0..self.len() as u32).filter(|&i| self.wants_count(i)).collect(); + let next = AtomicUsize::new(0); + let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(4).min(dirs.len().div_ceil(64)).max(1); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| { + let mut buf = Vec::new(); + while !cancel.load(atomic::Ordering::Relaxed) { + let start = next.fetch_add(64, atomic::Ordering::Relaxed); + if start >= dirs.len() { + return; + } + self.count_entries(&dirs[start..(start + 64).min(dirs.len())], &mut buf, None); + } + }); + } + }); + } + + /// Takes the counts of the rows given from the last listing of this folder, by name, as + /// stale: each is shown until it's counted again, so reading the folder again doesn't + /// blank them. + pub fn adopt_counts(&self, old: &Listing, ids: &[u32]) { + if !self.counts_folders() { + return; + } + let known: HashMap<&[u8], Option> = match old.counts.lock() { + Ok(c) if !c.is_empty() => c.iter().filter(|(i, _)| (**i as usize) < old.len()).map(|(&i, c)| (old.name(i), c.count)).collect(), + _ => return, + }; + let Ok(mut counts) = self.counts.lock() else { return }; + for &i in ids { + if let Some(&count) = known.get(self.name(i)) + && self.kind(i).is_dirlike() + { + counts.entry(i).or_insert(Counted { count, stale: true }); + } + } + } + + /// Marks the rows given as to count again, or every row counted, keeping what they show + /// until then. + pub fn recount(&self, ids: Option<&[u32]>) { + let Ok(mut counts) = self.counts.lock() else { return }; + match ids { + Some(ids) => { + for i in ids { + if let Some(c) = counts.get_mut(i) { + c.stale = true; + } + } + } + None => counts.values_mut().for_each(|c| c.stale = true), + } + } + fn snapshot(&self) -> Listing { Listing { dir: self.dir.clone(), @@ -321,6 +461,8 @@ impl Listing { trash: self.trash.clone(), recent: self.recent.clone(), search: self.search.clone(), + counts: Default::default(), + policy: OnceLock::new(), } } } @@ -355,21 +497,28 @@ impl Default for SortSpec { } } -/// Sorts every entry: folders first, then by the key, with the name breaking ties. -/// Sorting by size or time stats the whole folder first, so call this off the UI thread. -pub fn sort_entries(l: &Listing, spec: SortSpec, cancel: &AtomicBool) -> Vec { +/// Sorts every entry: folders first, then by the key, with the name breaking ties. Folders +/// sorted by size go by how many items they hold, by the show-hidden setting. +/// Sorting by size or time stats the whole folder first, and sorting by size counts every +/// folder in it, so call this off the UI thread. +pub fn sort_entries(l: &Listing, spec: SortSpec, show_hidden: bool, cancel: &AtomicBool) -> Vec { if spec.key != SortKey::Name { l.stat_all(cancel); } - sort_known(l, spec) + if spec.key == SortKey::Size { + l.count_all(cancel); + } + sort_known(l, spec, show_hidden) } /// Sorts using whatever stats are known right now, without fetching any. -fn sort_known(l: &Listing, spec: SortSpec) -> Vec { +fn sort_known(l: &Listing, spec: SortSpec, show_hidden: bool) -> Vec { // Stats can change while we sort, as other threads fill them in, and a comparator // whose answers change breaks the sort. So the keys are copied first. let keys: Vec = match spec.key { SortKey::Name => Vec::new(), + // A folder's is how many items it holds, and one not counted goes first. + SortKey::Size if l.counts_folders() => (0..l.len() as u32).map(|i| if l.kind(i).is_dirlike() { l.items(i, show_hidden).map_or(-1, i128::from) } else { size_of(l, i) as i128 }).collect(), SortKey::Size => (0..l.len() as u32).map(|i| size_of(l, i) as i128).collect(), SortKey::Modified => (0..l.len() as u32).map(|i| time_of(l, i) as i128).collect(), }; @@ -380,8 +529,8 @@ fn sort_known(l: &Listing, spec: SortSpec) -> Vec { db.cmp(&da).then_with(|| { let by_key = match spec.key { SortKey::Name => natural_cmp(l.name(a), l.name(b)), - // Folder sizes mean nothing, so folders stay in name order. - SortKey::Size if da => Ordering::Equal, + // Folder sizes mean nothing: those that aren't counted stay in name order. + SortKey::Size if da && !l.counts_folders() => Ordering::Equal, _ => keys[a as usize].cmp(&keys[b as usize]), }; let by_key = if spec.descending { by_key.reverse() } else { by_key }; @@ -606,7 +755,7 @@ fn load(req: LoadRequest, watch: Option<&Arc>, cancel: &Arc, return; } }; - let mut l = Listing { dir: req.dir.clone(), fd: Some(file.clone()), names: Vec::new(), slots: Vec::new(), meta: Vec::new(), complete: false, read_error: None, slow_stat: req.slow_stat, trash: None, recent: None, search: None }; + let mut l = Listing { dir: req.dir.clone(), fd: Some(file.clone()), names: Vec::new(), slots: Vec::new(), meta: Vec::new(), complete: false, read_error: None, slow_stat: req.slow_stat, trash: None, recent: None, search: None, counts: Default::default(), policy: OnceLock::new() }; // Small enough that a slow disk returns often, and big enough to be cheap on a fast one. let mut buf: Vec> = vec![MaybeUninit::uninit(); if req.slow_read.is_some() { 4096 } else { READ_BUFFER }]; let mut iter = RawDir::new(file.as_fd(), &mut buf); @@ -752,7 +901,7 @@ fn load_trash(req: LoadRequest, spec: &TrashSpec, watch: Option<&Arc>, ca if let Some(w) = watch { w.want(req.generation, Want::Dirs(vec![home.files()])); } - let mut l = Listing { dir: req.dir.clone(), fd: None, names: Vec::new(), slots: Vec::new(), meta: Vec::new(), complete: false, read_error: None, slow_stat: req.slow_stat, trash: None, recent: None, search: None }; + let mut l = Listing { dir: req.dir.clone(), fd: None, names: Vec::new(), slots: Vec::new(), meta: Vec::new(), complete: false, read_error: None, slow_stat: req.slow_stat, trash: None, recent: None, search: None, counts: Default::default(), policy: OnceLock::new() }; let mut t = TrashRows { roots: Vec::new(), fds: Vec::new(), root_of: Vec::new(), file_names: Vec::new(), info: Vec::new() }; match read_trash_root(&home, req.slow_read, cancel) { Ok((file, entries)) => add_trash_root(&mut l, &mut t, home, file, entries), @@ -829,7 +978,7 @@ fn load_recent(req: LoadRequest, watch: Option<&Arc>, cancel: &Arc crate::recent::parse(&bytes), // No list yet just means nothing's been used. @@ -933,7 +1082,7 @@ fn load_search(req: LoadRequest, watch: Option<&Arc>, cancel: &Arc) -> Listing { - let mut l = Listing { dir: req.dir.clone(), fd: None, names: Vec::new(), slots: Vec::new(), meta: Vec::new(), complete: done.is_some(), read_error: None, slow_stat: None, trash: None, recent: None, search: None }; + let mut l = Listing { dir: req.dir.clone(), fd: None, names: Vec::new(), slots: Vec::new(), meta: Vec::new(), complete: done.is_some(), read_error: None, slow_stat: None, trash: None, recent: None, search: None, counts: Default::default(), policy: OnceLock::new() }; let mut paths = Vec::with_capacity(found.len()); for f in found { let Some(name) = f.path.file_name().map(|n| n.as_bytes()) else { continue }; @@ -1028,13 +1177,19 @@ fn publish_partial(l: Listing, req: &LoadRequest, cancel: &Arc, sink fn publish_final(l: Arc, req: &LoadRequest, cancel: &Arc, sink: &LoadSink) { if req.sort.key != SortKey::Name { let (tx, rx) = mpsc::channel(); - let (l2, c2) = (l.clone(), cancel.clone()); + let (l2, c2, sort) = (l.clone(), cancel.clone(), req.sort); let spawned = std::thread::Builder::new().name("gannet-stat-all".into()).spawn(move || { l2.stat_all(&c2); + if sort.key == SortKey::Size { + l2.count_all(&c2); + } let _ = tx.send(()); }); if spawned.is_err() { l.stat_all(cancel); + if sort.key == SortKey::Size { + l.count_all(cancel); + } } else if rx.recv_timeout(SORT_STAT_HEAD_START).is_err() { emit(l.clone(), SortSpec::default(), req, cancel, false, sink); let _ = rx.recv(); @@ -1044,7 +1199,7 @@ fn publish_final(l: Arc, req: &LoadRequest, cancel: &Arc, s } fn emit(l: Arc, order: SortSpec, req: &LoadRequest, cancel: &Arc, settled: bool, sink: &LoadSink) { - let sorted = sort_known(&l, order); + let sorted = sort_known(&l, order, req.show_hidden); let rows = visible_rows(&l, &sorted, req.show_hidden, &req.filter); let start = req.first_row.min(rows.len()); let end = (start + req.row_count).min(rows.len()); @@ -1102,11 +1257,19 @@ pub struct Stater { impl Stater { /// `None` if the system can't start a thread; rows then just keep blank columns. pub fn new(listing: Arc, on_progress: impl Fn() + Send + 'static) -> Option { + Self::counting(listing, None, on_progress) + } + + /// As `new`, also counting the items in each folder asked for, after its stat, and watching + /// each with `watch`, for the listing of its generation. + pub fn counting(listing: Arc, watch: Option<(Arc, u64)>, on_progress: impl Fn() + Send + 'static) -> Option { let (tx, rx) = mpsc::channel::>(); std::thread::Builder::new() .name("gannet-stat".into()) .spawn(move || { let mut next = None; + // Allocated on the first count, so a folder of files never needs it. + let mut buf = Vec::new(); loop { let ids = match next.take() { Some(ids) => ids, @@ -1116,7 +1279,8 @@ impl Stater { }, }; for chunk in ids.chunks(64) { - if listing.stat_entries(chunk) { + let statted = listing.stat_entries(chunk); + if statted | listing.count_entries(chunk, &mut buf, watch.as_ref().map(|(w, g)| (&**w, *g))) { on_progress(); } // Newer requests replace this one: the window moved on. @@ -1392,6 +1556,62 @@ mod tests { assert!(matches!(l.listing.stat(l.rows[50]), Stat::Known { size: 3, .. })); } + #[test] + fn stater_counts_the_folders_asked_for_and_only_those() { + let s = Scratch::new(); + s.file("two/a", b""); + s.file("two/.b", b""); + s.file("two/c", b""); + s.file("other/x", b""); + s.file("plain", b"abc"); + let mut r = request(s.path()); + r.row_count = 0; + let l = last(run(r)); + let id = |n: &str| l.listing.find(n.as_bytes()).unwrap(); + assert!(l.listing.wants_count(id("two")) && !l.listing.wants_count(id("plain")), "only folders are counted"); + let (tx, rx) = mpsc::channel(); + let st = Stater::counting(l.listing.clone(), None, move || { + let _ = tx.send(()); + }) + .unwrap(); + st.request(vec![id("two"), id("plain")]); + rx.recv_timeout(Duration::from_secs(5)).unwrap(); + assert_eq!((l.listing.items(id("two"), false), l.listing.items(id("two"), true)), (Some(2), Some(3))); + assert_eq!(l.listing.items(id("other"), false), None, "a folder not asked for isn't counted"); + assert_eq!(l.listing.items(id("plain"), false), None); + // Marked to count again, it keeps its count until it is. + l.listing.recount(Some(&[id("two")])); + assert!(l.listing.wants_count(id("two"))); + assert_eq!(l.listing.items(id("two"), false), Some(2)); + } + + #[test] + fn sorting_by_size_counts_every_folder_and_orders_them_by_it() { + let s = Scratch::new(); + s.file("few/a", b""); + s.file("many/a", b""); + s.file("many/b", b""); + s.file("many/.c", b""); + s.file("lots/.a", b""); + s.file("lots/.b", b""); + s.file("lots/.c", b""); + s.file("lots/.d", b""); + s.file("file", b"x"); + let mut r = request(s.path()); + r.sort = SortSpec { key: SortKey::Size, descending: true }; + assert_eq!(row_names(&last(run(r.clone()))), ["many", "few", "lots", "file"], "by the items that show"); + r.show_hidden = true; + assert_eq!(row_names(&last(run(r))), ["lots", "many", "few", "file"], "hidden ones too, when they show"); + } + + #[test] + fn the_trash_recent_and_search_results_dont_count() { + let s = Scratch::new(); + s.file("found/x", b""); + let l = last(run(search_request(s.path(), "found"))); + assert!(!l.listing.wants_count(l.rows[0])); + } + #[test] fn a_fifo_fails_at_once_instead_of_hanging() { let s = Scratch::new(); diff --git a/tests/e2e.py b/tests/e2e.py index 076062b..f63d764 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -747,6 +747,53 @@ def live_refresh_keeps_selection(h): a.close() +@check +def a_folders_size_says_how_many_items_it_holds(h): + fs = fresh_fs() + spec = {f"eight/{i}.txt": "" for i in range(8)} + spec.update({"one/x.txt": "", "none": None, "secret/.hidden": "", "notes.txt": "abc"}) + tree(fs, spec) + # Past 10,000, counting stops. The long name shows the count fits beside a name cut short. + big = fs / "Every photo from the whole trip, from every camera and phone, sorted by day, with the ones from the boat and the hike up the mountain too" + big.mkdir() + for i in range(10_001): + (big / str(i)).touch() + sizes = lambda s: dict(zip(s["names"], s["sizes"])) + want = {big.name: "10,000+ items", "eight": "8 items", "none": "Empty", "one": "1 item", "secret": "Empty", "notes.txt": "3 B"} + # The built-in themes, light then dark, whatever theme an earlier check left. + shutil.rmtree(SCRATCH / "client/home/.local/state/aliasos", ignore_errors=True) + gtk = SCRATCH / "client/config/gtk-4.0" + try: + for theme in ("light", "dark"): + if theme == "dark": + gtk.mkdir(parents=True, exist_ok=True) + (gtk / "settings.ini").write_text("[Settings]\ngtk-application-prefer-dark-theme=1\n") + a = App(h, fs) + s = a.wait(lambda s: sizes(s) == want, "each folder's count") + assert (s["base"] == 0xfafafa) == (theme == "light"), f"{theme}: {s['base']:06x}" + a.shot(f"folder-counts-{theme}") + if theme == "light": + # A change in a folder shown counts it again, by itself. + (fs / "one/y.txt").write_text("") + a.wait(lambda s: sizes(s)["one"] == "2 items", "counted again after a change in it") + (fs / "eight/0.txt").unlink() + a.wait(lambda s: sizes(s)["eight"] == "7 items", "and after a removal") + # Hidden files count once they show. + a.key("h", mods=["ctrl"]) + a.wait(lambda s: s["hidden"] and sizes(s).get("secret") == "1 item", "a hidden file counts once shown") + a.key("h", mods=["ctrl"]) + a.wait(lambda s: not s["hidden"] and sizes(s).get("secret") == "Empty", "and not once hidden again") + # Sorted by size, folders stay first, the fullest first. + a.key("2", mods=["ctrl"]) + a.wait(lambda s: s["sort"] == "Size" and s["names"] == [big.name, "eight", "one", "none", "secret", "notes.txt"], "folders by count, before files") + a.shot("folder-counts-by-size-light") + (fs / "one/y.txt").unlink() + (fs / "eight/0.txt").write_text("") + a.close() + finally: + shutil.rmtree(gtk, ignore_errors=True) + + @check def theme_follows_swaps_and_works_without_any(h): fs = fresh_fs() From 445111160393341eb3aeb7fab83ae5150f521078 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 21:02:21 -0700 Subject: [PATCH 2/8] ALI-2598: The screen reader check hears folders' counts as their Size --- tests/e2e.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/e2e.py b/tests/e2e.py index f63d764..6fd92f0 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -2332,10 +2332,11 @@ def a_screen_reader_reads_columns_the_path_and_drives_and_hears_the_news(h): sr.until("apps", lambda x: x == ["Gannet"], "registered once a screen reader is on") # The list is a table: its headings say which sorts it, and each row's cells read as shown. - t = sr.until("table", lambda t: len(t["rows"]) == 4 and t["rows"][2][1] == "4 B", "the table, sizes known") + t = sr.until("table", lambda t: len(t["rows"]) == 4 and t["rows"][2][1] == "4 B" and t["rows"][1][1], "the table, sizes and counts known") assert (t["role"], t["row_role"]) == ("table", "table row"), t assert [(c["name"], c["role"], c["sort"], c["actions"]) for c in t["columns"]] == [("Name", "column header", "ascending", 1), ("Size", "column header", "none", 1), ("Modified", "column header", "none", 1)], t["columns"] - assert [r[:2] for r in t["rows"]] == [["dest", ""], ["sub", ""], ["a.txt", "4 B"], ["bb.txt", "2.0 kB"]], t["rows"] + # A folder's size is how many items it holds. + assert [r[:2] for r in t["rows"]] == [["dest", "1 item"], ["sub", "1 item"], ["a.txt", "4 B"], ["bb.txt", "2.0 kB"]], t["rows"] assert all(r[2] for r in t["rows"]), "every row has a date" assert t["cell"] == {"role": "table cell", "position": [0, 2], "headings": ["Modified"], "parent": "dest"}, t["cell"] # A row says its other cells after its name. From 4653da6d93f6bb6f6779fa37cbccd2a5fb5634f5 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 21:52:33 -0700 Subject: [PATCH 3/8] ALI-2598: Keep every counted folder up to date, and count less - A folder counted for the Size sort isn't watched, so once it's on screen it's opened, watched, and read again only if its inode or modified time changed since it was counted. The same goes for a listing shown again from the cache, and for a folder that found no room for a watch. - A change heard while a folder is being read marks it to count again: each entry keeps a mark that `recount` bumps, even before the row has a count, and a count that sees it moved leaves the row stale. - Reading a folder again starts from the last listing's counts by name. The row's stat checks each against the folder's inode and modified time, so sorted by size only folders that changed are read again. - A folder that keeps changing waits twice as long each time, up to 2 s, and goes back to 100 ms once it's quiet for a second. The waits are motion tokens: recount-after, recount-quiet and recount-max-wait. - Counting stops after reading 100,000 entries, saying "10,000+ items". - Links are followed a step at a time with readlink, up to 40, and each path on the way is checked against the mount table first, so a chain of links or a linked folder can't lead into a network place. - Showing a hidden file from Quick View re-sorts when sorted by size. - The stat thread looks for a newer request between folders it counts. --- README.md | 19 +- crates/app/src/app.rs | 105 ++++++++--- crates/app/src/preview.rs | 5 +- crates/core/src/cli.rs | 2 +- crates/core/src/counts.rs | 247 +++++++++++++++++++++----- crates/core/src/listing.rs | 276 +++++++++++++++++++++++++---- crates/core/src/tokens.rs | 9 + crates/core/tests/watch_threads.rs | 2 +- design/tokens.json | 15 ++ tests/e2e.py | 6 + 10 files changed, 568 insertions(+), 118 deletions(-) diff --git a/README.md b/README.md index 2685198..7c5c11b 100644 --- a/README.md +++ b/README.md @@ -154,12 +154,19 @@ and Save dialogs from other apps read and save the same orders. The orders are k `$XDG_STATE_HOME/gannet/sorts`, which is `~/.local/state/gannet/sorts` by default. A folder's Size says how many items it holds: "8 items", "1 item", "Empty", or "10,000+ items", -where counting stops. Hidden items count only while hidden files show. Only folders on screen -are counted, on a thread of their own after the rows show, so opening a folder is no slower. -Each folder counted is watched, so a change in it counts it again. Folders on network places -(SMB, SFTP, FTP, NFS, WebDAV and other FUSE mounts) aren't counted, as each count would be a -round trip, and their Size stays blank. Sorting by size counts every folder, and puts the -fullest first. +where counting stops (also after reading 100,000 entries, mostly hidden ones). Hidden items count +only while hidden files show. Only folders on screen are counted, on a thread of their own after +the rows show, so opening a folder is no slower. Each folder on screen is watched once counted, +so a change in it counts it again, a moment later; one that keeps changing is counted at most +every 2 seconds. Sorting by size counts every folder, fullest first, without watching them; each +is watched when it comes on screen, and read again then only if it changed. Reading a folder +again keeps the counts it had and reads again only the folders that changed. A folder of more +than 1,024 folders watches the first 1,024 it shows; past that, or past the system's limit on +watches, a count isn't kept up to date until there's room for a watch when it's on screen again, +or the folder is read again. A count wider than the Size column, as "10,000+ items" is, reaches +to its left, and the name beside it is cut short of it. Folders on network places (SMB, SFTP, FTP, +NFS, WebDAV and other FUSE mounts), and links that lead into one, aren't counted, as each count +would be a round trip, and their Size stays blank. ## Dragging diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index 4004848..83fee9b 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -57,8 +57,9 @@ const SMALL_BUTTON: f32 = size::SMALL_BUTTON; const DOUBLE_CLICK: Duration = motion::DOUBLE_CLICK; const TYPE_AHEAD_RESET: Duration = motion::TYPE_AHEAD_RESET; const HOLD_FOR_LOAD: Duration = motion::HOLD_FOR_LOAD; -/// How long after a counted folder changes it's counted again. -const RECOUNT_AFTER: Duration = Duration::from_millis(100); +const RECOUNT_AFTER: Duration = motion::RECOUNT_AFTER; +const RECOUNT_QUIET: Duration = motion::RECOUNT_QUIET; +const RECOUNT_MAX_WAIT: Duration = motion::RECOUNT_MAX_WAIT; const JOB_SHOW_AFTER: Duration = motion::JOB_SHOW_AFTER; const UNDO_DEPTH: usize = 20; pub(crate) const DIALOG_GUARD: Duration = motion::DIALOG_GUARD; @@ -782,9 +783,14 @@ pub struct App { pub watch: Option>, /// The watches on folders whose items are counted, which the window polls. pub counts: Option>, - /// When the folders that changed are counted again: a moment after the first change, so a - /// burst of them is one count. + /// When the soonest folder that changed is counted again. recount_at: Option, + /// Folders that changed, by row, and when each is counted again: a moment after its first + /// change, so a burst of them is one count. + recount_due: HashMap, + /// When each folder was last counted again, and how long it waited: one that keeps + /// changing waits twice as long each time, up to `RECOUNT_MAX_WAIT`. + recounted: HashMap, /// A re-sort is on its way, so a lighter request mustn't replace it. resort_pending: bool, /// A change arrived during a load, so another load follows it. @@ -990,6 +996,8 @@ impl App { watch: None, counts: None, recount_at: None, + recount_due: HashMap::new(), + recounted: HashMap::new(), resort_pending: false, reload_after_load: false, stater_gen: 0, @@ -1230,8 +1238,9 @@ impl App { self.sorted = c.sorted; self.rows = self.choosable(&c.listing, visible_rows(&c.listing, &self.sorted, self.show_hidden, &self.filter)); self.selected = vec![0; c.listing.len().div_ceil(64)]; - // Its folders weren't watched while it was away, so each is counted again. - c.listing.recount(None); + // Its folders weren't watched while it was away: each on screen is watched again, and + // read again if it changed. + c.listing.forget_watches(); self.new_stater(c.listing); self.place_pending_cursor(true, false); self.request_stats(); @@ -1280,6 +1289,9 @@ impl App { trash: self.is_trash_view().then(|| TrashSpec { home_trash: self.home_trash(), uid: rustix::process::geteuid().as_raw(), mounts: self.trash_mounts.clone(), disks_give_up: DISKS_GIVE_UP }), recent: self.is_recent_view(), search: self.req_search.clone(), + // Reading the folder again starts from the counts it has, so only folders that + // changed are read again. + prior: self.listing.clone().filter(|l| l.dir == self.dir && l.search().is_none() && self.req_search.is_none()).map(gannet_core::listing::Prior), search_skips_trash: Some((self.home_trash(), rustix::process::geteuid().as_raw())), }; let hub = self.hub.clone(); @@ -1305,7 +1317,12 @@ impl App { self.hold_paint = None; } if self.recount_at.is_some_and(|t| t <= now) { - self.recount_at = None; + let due: Vec = self.recount_due.iter().filter(|&(_, &t)| t <= now).map(|(&row, _)| row).collect(); + self.recount_due.retain(|_, t| *t > now); + self.recount_at = self.recount_due.values().min().copied(); + if let Some(l) = &self.listing { + l.recount(Some(&due)); + } self.stats_range = (0, 0); self.request_stats(); } @@ -1442,11 +1459,6 @@ impl App { self.rederive(false); } self.clamp_scroll(); - // The folders on screen show what they held until they're counted again. - if let Some(o) = old.as_ref().filter(|_| same_dir) { - let (from, to) = self.stats_window(); - l.listing.adopt_counts(o, &self.rows[from..to]); - } if l.settled && l.listing.complete { self.remember(l.listing, l.sort); } @@ -1481,6 +1493,10 @@ impl App { let generation = self.stater_gen; // A new listing lets go of the last one's watches on counted folders. let watch = self.counts.as_ref().map(|w| (w.clone(), w.begin())); + // Rows are numbered afresh in each listing. + self.recount_due.clear(); + self.recounted.clear(); + self.recount_at = None; self.stater = Stater::counting(listing, watch, move || hub.send(Msg::Stats(generation))); self.stats_range = (0, 0); } @@ -1851,17 +1867,23 @@ impl App { } /// Folders whose items were counted changed: each is counted again shortly, showing what it - /// had until then. + /// had until then. One counted again less than `RECOUNT_QUIET` ago waits twice as long as + /// it did last time, up to `RECOUNT_MAX_WAIT`, so a folder that never stops changing is + /// counted at most that often. pub fn counts_changed(&mut self) { let Some(w) = self.counts.clone() else { return }; - let rows = w.drain(); - if rows.is_empty() { - return; - } - if let Some(l) = &self.listing { - l.recount(Some(&rows)); + let now = Instant::now(); + for row in w.drain() { + let wait = match self.recounted.get(&row) { + Some(&(last, wait)) if now.duration_since(last) < RECOUNT_QUIET => (wait * 2).min(RECOUNT_MAX_WAIT), + _ => RECOUNT_AFTER, + }; + if let std::collections::hash_map::Entry::Vacant(e) = self.recount_due.entry(row) { + e.insert(now + wait); + self.recounted.insert(row, (now + wait, wait)); + } } - self.recount_at.get_or_insert(Instant::now() + RECOUNT_AFTER); + self.recount_at = self.recount_due.values().min().copied(); } /// Asks for sizes and times of the rows on screen, and a screenful around them, and how @@ -1874,7 +1896,8 @@ impl App { return; } self.stats_range = range; - let ids: Vec = self.rows[range.0..range.1].iter().copied().filter(|&i| l.stat(i) == Stat::Unknown || l.wants_count(i)).collect(); + let watching = self.counts.is_some(); + let ids: Vec = self.rows[range.0..range.1].iter().copied().filter(|&i| l.stat(i) == Stat::Unknown || l.wants_count(i) || (watching && l.wants_watch(i))).collect(); if !ids.is_empty() { st.request(ids); } @@ -12929,6 +12952,46 @@ mod tests { assert_eq!(r.app.loads(), loads, "only the folder that changed is read again"); } + #[test] + fn a_folder_that_keeps_changing_is_counted_again_less_and_less_often() { + let mut r = Rig::new("counts-backoff"); + r.app.counts = Some(Arc::new(gannet_core::counts::Watches::new().unwrap())); + fs::create_dir(r.work().join("busy")).unwrap(); + r.open(r.work()); + assert_eq!(size_cells(&mut r), cells(&[("busy", "Empty")])); + let row = r.app.rows[0]; + let mut waits = Vec::new(); + for n in 1..=6 { + fs::write(r.work().join(format!("busy/{n}")), "").unwrap(); + let end = Instant::now() + Duration::from_secs(10); + // Heard, then counted again once its wait is over. + while !r.app.recount_due.contains_key(&row) { + assert!(Instant::now() < end, "timed out: heard"); + r.app.counts_changed(); + } + waits.push(r.app.recounted[&row].1); + let want = if n == 1 { "1 item".to_string() } else { format!("{n} items") }; + let cell = |a: &App| a.listing.as_ref().map(|l| crate::format::size_cell(l, a.rows[0], false)).unwrap_or_default(); + while cell(&r.app) != want { + assert!(Instant::now() < end, "timed out: counted again"); + if let Ok(m) = r.rx.recv_timeout(Duration::from_millis(10)) { + r.app.on_msg(m); + } + r.app.on_timer(Instant::now()); + } + } + assert_eq!(waits, [RECOUNT_AFTER, RECOUNT_AFTER * 2, RECOUNT_AFTER * 4, RECOUNT_AFTER * 8, RECOUNT_AFTER * 16, RECOUNT_MAX_WAIT], "doubling, up to the most"); + // Quiet for a while, it's back to the first wait. + r.app.recounted.insert(row, (Instant::now() - RECOUNT_QUIET, RECOUNT_MAX_WAIT)); + fs::write(r.work().join("busy/quiet"), "").unwrap(); + let end = Instant::now() + Duration::from_secs(10); + while !r.app.recount_due.contains_key(&row) { + assert!(Instant::now() < end, "timed out: heard after quiet"); + r.app.counts_changed(); + } + assert_eq!(r.app.recounted[&row].1, RECOUNT_AFTER); + } + #[test] fn reading_the_folder_again_keeps_its_counts_showing() { let mut r = Rig::new("counts-reload"); diff --git a/crates/app/src/preview.rs b/crates/app/src/preview.rs index b9f1cc1..bc65b83 100644 --- a/crates/app/src/preview.rs +++ b/crates/app/src/preview.rs @@ -20,7 +20,7 @@ use std::time::{Duration, Instant}; use gannet_core::foldersize::{self, Tally}; use gannet_core::history::Stop; -use gannet_core::listing::{SortSpec, Stat}; +use gannet_core::listing::{SortKey, SortSpec, Stat}; use gannet_core::mime::{self, MimeDb}; use gannet_core::thumbcache; use gannet_core::thumbnailers::Thumbnailers; @@ -2324,7 +2324,8 @@ impl App { let name = path.file_name().map(|n| n.as_encoded_bytes().to_vec()); if name.as_ref().is_some_and(|n| n.first() == Some(&b'.')) && !self.show_hidden { self.show_hidden = true; - self.rederive(false); + // Folders sorted by size go by the items that show. + self.rederive(self.view_sort().key == SortKey::Size); } let dir = path.parent().map_or_else(|| PathBuf::from("/"), Path::to_path_buf); let row = self.listing.as_ref().filter(|l| l.dir == dir && !self.loading).and_then(|l| name.as_ref().and_then(|n| self.rows.iter().position(|&i| *l.key(i) == **n))); diff --git a/crates/core/src/cli.rs b/crates/core/src/cli.rs index e7f70bd..ad4cc6c 100644 --- a/crates/core/src/cli.rs +++ b/crates/core/src/cli.rs @@ -269,7 +269,7 @@ fn load(req: LoadRequest) -> Result { } fn request(dir: PathBuf, sort: SortSpec, show_hidden: bool, trash: Option) -> LoadRequest { - LoadRequest { dir, generation: 0, sort, show_hidden, filter: String::new(), first_row: 0, row_count: 0, slow_read: None, slow_stat: None, trash, recent: false, search: None, search_skips_trash: None } + LoadRequest { dir, generation: 0, sort, show_hidden, filter: String::new(), first_row: 0, row_count: 0, slow_read: None, slow_stat: None, trash, recent: false, search: None, search_skips_trash: None, prior: None } } fn list(env: &mut Env, o: &Opts, report: &mut Report) -> Doc { diff --git a/crates/core/src/counts.rs b/crates/core/src/counts.rs index 68c29ee..d405ecb 100644 --- a/crates/core/src/counts.rs +++ b/crates/core/src/counts.rs @@ -8,7 +8,7 @@ //! read while nothing changes. use std::collections::HashMap; -use std::ffi::CStr; +use std::ffi::{CStr, OsStr, OsString}; use std::mem::MaybeUninit; use std::os::unix::ffi::OsStrExt; use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd}; @@ -39,19 +39,51 @@ impl Count { } } +/// The most entries a count reads. A folder of this many hidden ones isn't read to the end: +/// it says "10,000+ items" either way. +pub const READ_CEILING: u32 = 100_000; + +/// What `count_in` did with an open folder. +pub enum Opened { + /// Counted it. + Counted(Count), + /// Didn't read it, as `opened` said the count it had was still right. + Kept, +} + +/// What a folder was when it was counted: its inode and modified time, which change with any +/// entry added, removed or renamed in it. A folder whose stamp is the same needn't be read again. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Stamp { + pub ino: u64, + pub sec: i64, + pub nsec: u32, +} + +impl Stamp { + pub fn of(fd: BorrowedFd<'_>) -> Option { + let st = rustix::fs::fstat(fd).ok()?; + Some(Self { ino: st.st_ino as u64, sec: st.st_mtime as i64, nsec: st.st_mtime_nsec as u32 }) + } +} + /// Counts the folder `name` in `dir`, with `buf` to read into. The folder is opened first and /// handed to `opened`, to be watched before it's read, so a change during the count isn't -/// missed. Reading stops once more than `CAP` items that aren't hidden are found. -pub fn count_in(dir: BorrowedFd<'_>, name: &CStr, buf: &mut [MaybeUninit], opened: impl FnOnce(BorrowedFd<'_>)) -> Option { +/// missed; it returns false when the folder needn't be read after all. Reading stops once more +/// than `CAP` items that aren't hidden are found, or `READ_CEILING` entries are read. +pub fn count_in(dir: BorrowedFd<'_>, name: &CStr, buf: &mut [MaybeUninit], opened: impl FnOnce(BorrowedFd<'_>) -> bool) -> Option { // O_NONBLOCK and O_DIRECTORY: anything that isn't a folder fails at once, and nothing hangs // opening it. NOFOLLOW isn't set, as a link to a folder is counted as the folder. let fd = rustix::fs::openat(dir, name, OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NONBLOCK | OFlags::CLOEXEC, Mode::empty()).ok()?; - opened(fd.as_fd()); - count_open(&fd, buf) + if !opened(fd.as_fd()) { + return Some(Opened::Kept); + } + count_open(&fd, buf, READ_CEILING).map(Opened::Counted) } -fn count_open(fd: &OwnedFd, buf: &mut [MaybeUninit]) -> Option { +fn count_open(fd: &OwnedFd, buf: &mut [MaybeUninit], ceiling: u32) -> Option { let mut c = Count { all: 0, shown: 0 }; + let mut read = 0; let mut iter = RawDir::new(fd, buf); while let Some(e) = iter.next() { let e = e.ok()?; @@ -59,6 +91,7 @@ fn count_open(fd: &OwnedFd, buf: &mut [MaybeUninit]) -> Option { if n == b"." || n == b".." { continue; } + read += 1; c.all = c.all.saturating_add(1); if n.first() != Some(&b'.') { c.shown += 1; @@ -66,6 +99,11 @@ fn count_open(fd: &OwnedFd, buf: &mut [MaybeUninit]) -> Option { break; } } + // So many hidden entries that what shows can't be told without reading on: over the + // cap, as far as the count goes. + if read >= ceiling { + return Some(Count { all: CAP + 1, shown: CAP + 1 }); + } } c.all = c.all.min(CAP + 1); Some(c) @@ -93,41 +131,82 @@ impl Policy { Self { real, mounts } } - /// Whether a row may be counted: a folder, or a link to one, and not a network place - /// mounted there or one a link points into. A link is resolved by its text alone, so - /// checking it can't hang on the place it points to. - pub fn allows(&self, name: &[u8], link: Option<&Path>) -> bool { + /// Whether a row may be counted: not a network place mounted there, nor one a link leads + /// into, through any number of links. A link is followed a step at a time, by reading it, and + /// each path on the way is checked against the mount table before anything is looked up in + /// it, so nothing here touches a network place, and a dead one can't hang the check. + pub fn allows(&self, name: &[u8]) -> bool { let Some(real) = &self.real else { return false }; - let path = match link { - Some(target) => lexical(&real.join(target)), - None => real.join(std::ffi::OsStr::from_bytes(name)), - }; - fs_type_of(&self.mounts, &path).is_none_or(|t| !uncounted(t)) + self.resolve(real.clone(), Path::new(OsStr::from_bytes(name))).is_some() } -} -fn fs_type_of<'a>(mounts: &'a [Mount], path: &Path) -> Option<&'a str> { - mounts.iter().filter(|m| path.starts_with(&m.point)).max_by_key(|m| m.point.as_os_str().len()).map(|m| m.fs_type.as_str()) + fn counted(&self, path: &Path) -> bool { + fs_type_of(&self.mounts, path).is_none_or(|t| !uncounted(t)) + } + + /// Where `rest` leads from the folder `base`, links followed, or `None` if the way passes + /// through a place that isn't counted, there are more than `MAX_LINKS` links, or a step + /// can't be read. + fn resolve(&self, mut base: PathBuf, rest: &Path) -> Option { + // What's left to walk, last component first. + let mut todo: Vec = Vec::new(); + push_components(&mut todo, &mut base, rest); + let mut links = 0; + while let Some(c) = todo.pop() { + if c == ".." { + base.pop(); + continue; + } + let next = base.join(&c); + if !self.counted(&next) { + return None; + } + match std::fs::read_link(&next) { + Ok(target) => { + links += 1; + if links > MAX_LINKS { + return None; + } + push_components(&mut todo, &mut base, &target); + } + // Not a link (EINVAL): a real step. + Err(e) if e.raw_os_error() == Some(rustix::io::Errno::INVAL.raw_os_error()) => base = next, + Err(_) => return None, + } + } + self.counted(&base).then_some(base) + } } -/// `..` and `.` taken out of a path, by its text. -fn lexical(p: &Path) -> PathBuf { - let mut out = PathBuf::new(); - for c in p.components() { +/// As the kernel allows (ELOOP after this many). +const MAX_LINKS: usize = 40; + +/// Puts `path`'s components on the stack to walk, first on top; an absolute path starts again +/// from the root. +fn push_components(todo: &mut Vec, base: &mut PathBuf, path: &Path) { + let mut parts = Vec::new(); + for c in path.components() { match c { - Component::ParentDir => { - out.pop(); + Component::RootDir => { + *base = PathBuf::from("/"); + parts.clear(); } - Component::CurDir => {} - c => out.push(c), + Component::Normal(n) => parts.push(n.to_os_string()), + Component::ParentDir => parts.push(OsString::from("..")), + Component::CurDir | Component::Prefix(_) => {} } } - out + todo.extend(parts.into_iter().rev()); +} + +fn fs_type_of<'a>(mounts: &'a [Mount], path: &Path) -> Option<&'a str> { + mounts.iter().filter(|m| path.starts_with(&m.point)).max_by_key(|m| m.point.as_os_str().len()).map(|m| m.fs_type.as_str()) } /// How many folders one listing watches at most. Scrolling through a folder of more folders -/// than this still counts each, but only these many are kept up to date until it's read again. -const MAX_WATCHES: usize = 1024; +/// than this still counts each, but those past it aren't kept up to date until they're on screen +/// again with room for a watch, or the folder is read again. +pub const MAX_WATCHES: usize = 1024; /// What a change in a counted folder looks like. A watch goes after its first event, as /// `ONESHOT`, and counting the folder again watches it again, so a busy folder wakes the @@ -166,17 +245,24 @@ impl Watches { } /// Watches an open folder for a row of the listing of `generation`, unless a newer listing - /// has started. Added through `/proc/self/fd`, so no name is looked up. - pub fn add(&self, generation: u64, folder: BorrowedFd<'_>, row: u32) { - let Ok(mut inner) = self.inner.lock() else { return }; + /// has started. Added through `/proc/self/fd`, so no name is looked up. False if it isn't + /// watched: past `MAX_WATCHES`, or the system's limit (ENOSPC), or for an old listing. + pub fn add(&self, generation: u64, folder: BorrowedFd<'_>, row: u32) -> bool { + let Ok(mut inner) = self.inner.lock() else { return false }; if inner.generation != generation || inner.rows.len() >= MAX_WATCHES { - return; + return false; } - let Ok(wd) = inotify::add_watch(&self.fd, format!("/proc/self/fd/{}", folder.as_raw_fd()), MASK) else { return }; + let Ok(wd) = inotify::add_watch(&self.fd, format!("/proc/self/fd/{}", folder.as_raw_fd()), MASK) else { return false }; let rows = inner.rows.entry(wd).or_default(); if !rows.contains(&row) { rows.push(row); } + true + } + + /// Whether another folder could be watched now. + pub fn has_room(&self) -> bool { + self.inner.lock().is_ok_and(|i| i.rows.len() < MAX_WATCHES) } /// The rows whose folders changed since last asked, from everything pending. Never blocks. @@ -239,11 +325,15 @@ mod tests { use super::*; use crate::testutil::Scratch; use std::fs; + use std::os::unix::fs::symlink; fn count(dir: &Path, name: &str) -> Option { let d = fs::File::open(dir).unwrap(); let mut buf = vec![MaybeUninit::uninit(); 32 * 1024]; - count_in(d.as_fd(), &std::ffi::CString::new(name).unwrap(), &mut buf, |_| {}) + match count_in(d.as_fd(), &std::ffi::CString::new(name).unwrap(), &mut buf, |_| true)? { + Opened::Counted(c) => Some(c), + Opened::Kept => None, + } } #[test] @@ -291,18 +381,77 @@ mod tests { #[test] fn network_places_and_what_points_into_them_arent_counted() { - let mounts = vec![mount("/", "ext4"), mount("/home/me/nas", "nfs4"), mount("/run/user/1000/gvfs", "fuse.gvfsd-fuse"), mount("/mnt/win", "fuseblk"), mount("/mnt/auto", "autofs")]; - let home = Policy::new(Some("/home/me".into()), mounts.clone()); - assert!(home.allows(b"Documents", None)); - assert!(!home.allows(b"nas", None), "a share mounted in the folder"); - assert!(!home.allows(b"films", Some(Path::new("nas/films"))), "a link into a share"); - assert!(!home.allows(b"up", Some(Path::new("../me/nas"))), "a link into a share, by way of .."); - assert!(home.allows(b"docs", Some(Path::new("/home/me/Documents")))); - assert!(!Policy::new(Some("/run/user/1000/gvfs/smb-share:server=nas".into()), mounts.clone()).allows(b"photos", None), "inside a GVfs share"); - assert!(!Policy::new(Some("/home/me/nas/films".into()), mounts.clone()).allows(b"x", None), "inside an NFS share"); - assert!(Policy::new(Some("/mnt/win".into()), mounts.clone()).allows(b"x", None), "a local disk through FUSE"); - assert!(!Policy::new(Some("/mnt".into()), mounts.clone()).allows(b"auto", None), "an automount that isn't mounted yet"); - assert!(!Policy::new(None, mounts).allows(b"x", None), "a folder with no real path"); + let s = Scratch::new(); + let root = s.path().to_path_buf(); + let p = |rel: &str| root.join(rel).to_string_lossy().into_owned(); + s.dir("home/Documents"); + s.dir("home/nas/films"); + s.dir("gvfs/share/photos"); + s.dir("win/x"); + s.dir("auto"); + let mounts = vec![mount("/", "ext4"), mount(&p("home/nas"), "nfs4"), mount(&p("gvfs"), "fuse.gvfsd-fuse"), mount(&p("win"), "fuseblk"), mount(&p("auto"), "autofs")]; + let link = |target: &str, at: &str| symlink(target, root.join(at)).unwrap(); + let home = Policy::new(Some(root.join("home")), mounts.clone()); + assert!(home.allows(b"Documents")); + assert!(!home.allows(b"nas"), "a share mounted in the folder"); + link("nas/films", "home/films"); + assert!(!home.allows(b"films"), "a link into a share"); + link("../home/nas", "home/up"); + assert!(!home.allows(b"up"), "a link into a share, by way of .."); + link(&p("home/Documents"), "home/docs"); + assert!(home.allows(b"docs"), "an absolute link to a local folder"); + assert!(!Policy::new(Some(root.join("gvfs/share")), mounts.clone()).allows(b"photos"), "inside a GVfs share"); + assert!(!Policy::new(Some(root.join("home/nas/films")), mounts.clone()).allows(b"x"), "inside an NFS share"); + assert!(Policy::new(Some(root.join("win")), mounts.clone()).allows(b"x"), "a local disk through FUSE"); + assert!(!Policy::new(Some(root.clone()), mounts.clone()).allows(b"auto"), "an automount that isn't mounted yet"); + assert!(!Policy::new(None, mounts).allows(b"x"), "a folder with no real path"); + } + + #[test] + fn links_are_followed_a_step_at_a_time_and_never_into_a_share() { + let s = Scratch::new(); + let root = s.path().to_path_buf(); + s.dir("here"); + s.dir("nas/films"); + s.dir("local/stuff"); + let mounts = vec![mount("/", "ext4"), mount(&root.join("nas").to_string_lossy(), "nfs4")]; + let link = |target: &str, at: &str| symlink(target, root.join(at)).unwrap(); + let here = Policy::new(Some(root.join("here")), mounts); + // A link to a link to the share. + link("../hop", "here/chain"); + link("nas/films", "hop"); + assert!(!here.allows(b"chain"), "a link to a link into a share"); + // A link through a linked folder that's the share. + link("nas", "via"); + link("../via/films", "here/through"); + assert!(!here.allows(b"through"), "a link through a linked folder into a share"); + // Links that stay local are followed to the end. + link("local", "loc"); + link("../loc/stuff", "here/fine"); + assert!(here.allows(b"fine")); + // A loop ends, as the kernel's ELOOP would. + link("loop-b", "here/loop-a"); + link("loop-a", "here/loop-b"); + assert!(!here.allows(b"loop-a")); + // A link to nothing isn't counted. + link("gone", "here/dangling"); + assert!(!here.allows(b"dangling")); + } + + #[test] + fn a_huge_folder_of_hidden_entries_stops_at_the_ceiling() { + let s = Scratch::new(); + let d = s.dir("hidden"); + for i in 0..30 { + fs::File::create(d.join(format!(".{i}"))).unwrap(); + } + fs::File::create(d.join("shown")).unwrap(); + let f = fs::File::open(&d).unwrap(); + let mut buf = vec![MaybeUninit::uninit(); 4096]; + let fd: OwnedFd = f.into(); + assert_eq!(count_open(&fd, &mut buf, 10), Some(Count { all: CAP + 1, shown: CAP + 1 }), "past the ceiling, it says the cap"); + let fd: OwnedFd = fs::File::open(&d).unwrap().into(); + assert_eq!(count_open(&fd, &mut buf, 100), Some(Count { all: 31, shown: 1 })); } #[test] @@ -329,11 +478,11 @@ mod tests { let old = w.begin(); let d = fs::File::open(s.path()).unwrap(); let mut buf = vec![MaybeUninit::uninit(); 4096]; - count_in(d.as_fd(), c"sub", &mut buf, |f| w.add(old, f, 1)).unwrap(); + count_in(d.as_fd(), c"sub", &mut buf, |f| { w.add(old, f, 1); true }).unwrap(); assert_eq!(w.len(), 1); let new = w.begin(); assert!(w.is_empty()); - count_in(d.as_fd(), c"sub", &mut buf, |f| w.add(old, f, 1)).unwrap(); + count_in(d.as_fd(), c"sub", &mut buf, |f| { w.add(old, f, 1); true }).unwrap(); assert!(w.is_empty(), "an old listing's thread can't add to the new one"); count_in(d.as_fd(), c"sub", &mut buf, |f| w.add(new, f, 2)).unwrap(); fs::File::create(sub.join("x")).unwrap(); diff --git a/crates/core/src/listing.rs b/crates/core/src/listing.rs index 5165c9f..f712004 100644 --- a/crates/core/src/listing.rs +++ b/crates/core/src/listing.rs @@ -20,7 +20,7 @@ use std::time::{Duration, Instant}; use rustix::fs::{AtFlags, FileType, RawDir, StatxFlags, statat, statx}; -use crate::counts::{self, Count, Watches}; +use crate::counts::{self, Count, Stamp, Watches}; use crate::mounts::read_mounts; use crate::sort::{natural_cmp, par_sort_by}; use crate::trash::{self, Info, Root, Trashed}; @@ -92,10 +92,29 @@ pub struct Listing { /// A row's count: `None` if it isn't counted, as on a network place, or couldn't be read. A /// stale one is shown until it's counted again, so a recount doesn't blank the cell. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, Default)] struct Counted { count: Option, stale: bool, + /// Its folder is watched, so a change in it marks it stale. + watched: bool, + /// Taken from the last listing of this folder: right if the folder's stamp is the same. + seeded: bool, + /// What the folder was when counted. + stamp: Option, + /// Goes up each time it's marked to count again, so a count that was reading when that + /// happened knows it may have missed the change. + dirty: u32, +} + +/// Test seam: what runs between a folder being opened and being read. +#[cfg(test)] +type CountHook = Box; + +#[cfg(test)] +thread_local! { + /// Test seam: runs between a folder being opened and being read, on the thread counting. + static DURING_COUNT: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } /// What a search found: each row's path, and what was asked. @@ -279,9 +298,13 @@ impl Listing { // In the Trash, the date column is when the item was trashed. let deleted = self.trash.as_ref().and_then(|t| t.info[i as usize].as_ref()).and_then(|inf| inf.deleted); let flags = AtFlags::SYMLINK_NOFOLLOW | AtFlags::NO_AUTOMOUNT; - let got = std::ffi::CString::new(name).ok().and_then(|n| statx(fd.as_fd(), n.as_c_str(), flags, StatxFlags::SIZE | StatxFlags::MTIME).ok()); + let got = std::ffi::CString::new(name).ok().and_then(|n| statx(fd.as_fd(), n.as_c_str(), flags, StatxFlags::SIZE | StatxFlags::MTIME | StatxFlags::INO).ok()); match got { Some(st) => { + // A folder's count taken from the last listing stands if the folder is as it was. + if self.kind(i) == Kind::Dir && self.trash.is_none() { + self.check_seeded(i, Stamp { ino: st.stx_ino, sec: st.stx_mtime.tv_sec, nsec: st.stx_mtime.tv_nsec }); + } // Release pairs with the Acquire in stat(): a reader that sees the size sees the time. m.mtime.store(deleted.unwrap_or(st.stx_mtime.tv_sec), atomic::Ordering::Relaxed); m.size.store(st.stx_size, atomic::Ordering::Release); @@ -342,6 +365,12 @@ impl Listing { self.kind(i).is_dirlike() && self.counts_folders() && self.counts.lock().is_ok_and(|c| c.get(&i).is_none_or(|c| c.stale)) } + /// Whether a row's count is right but its folder isn't watched, as when it was counted for + /// a sort, or there was no room for a watch: on screen, it's worth watching. + pub fn wants_watch(&self, i: u32) -> bool { + self.kind(i).is_dirlike() && self.counts_folders() && self.counts.lock().is_ok_and(|c| c.get(&i).is_some_and(|c| !c.stale && !c.watched && c.count.is_some())) + } + /// Where rows may be counted: nowhere on a network place. Where the folder really is comes /// from the kernel's record of the open folder, and what's mounted from its memory too. fn policy(&self) -> &counts::Policy { @@ -353,27 +382,49 @@ impl Listing { }) } - /// Counts a folder's row if it needs it; true if it did. A count is watched for changes - /// with `watch`, for the listing of its generation. + /// Counts a folder's row if it needs it, or watches it if it needs only that; true if it + /// did either. A count is watched for changes with `watch`, for the listing of its + /// generation, before the folder is read, and a folder only being watched is read again only + /// if it changed since it was counted. fn count_one(&self, i: u32, buf: &mut Vec>, watch: Option<(&Watches, u64)>) -> bool { - if !self.wants_count(i) { + let to_count = self.wants_count(i); + if !to_count && !(watch.is_some_and(|(w, _)| w.has_room()) && self.wants_watch(i)) { return false; } let Some(fd) = self.fd.as_ref() else { return false }; + let (dirty, known) = self.counts.lock().ok().and_then(|c| c.get(&i).map(|c| (c.dirty, c.stamp))).unwrap_or_default(); let name = self.name(i); - let link = if self.kind(i) == Kind::LinkDir { CString::new(name).ok().and_then(|n| rustix::fs::readlinkat(fd.as_fd(), n.as_c_str(), Vec::new()).ok()) } else { None }; - let allowed = (self.kind(i) == Kind::Dir || link.is_some()) && self.policy().allows(name, link.as_deref().map(|l| Path::new(OsStr::from_bytes(l.to_bytes())))); - let count = if allowed { + let (mut watched, mut stamp) = (false, None); + let got = if self.policy().allows(name) { if buf.is_empty() { buf.resize(READ_BUFFER, MaybeUninit::uninit()); } - CString::new(name).ok().and_then(|n| counts::count_in(fd.as_fd(), n.as_c_str(), buf, |f| if let Some((w, generation)) = watch { w.add(generation, f, i) })) + CString::new(name).ok().and_then(|n| { + counts::count_in(fd.as_fd(), n.as_c_str(), buf, |f| { + watched = watch.is_some_and(|(w, generation)| w.add(generation, f, i)); + stamp = Stamp::of(f); + #[cfg(test)] + DURING_COUNT.with(|h| if let Some(h) = h.borrow().as_ref() { h(self, i) }); + // Only watching: the count stands if the folder is as it was. + to_count || stamp.is_none() || stamp != known + }) + }) } else { None }; - if let Ok(mut counts) = self.counts.lock() { - counts.insert(i, Counted { count, stale: false }); + let Ok(mut counts) = self.counts.lock() else { return true }; + let e = counts.entry(i).or_default(); + // Marked to count again while this was reading: the count may have missed that change. + let missed = e.dirty != dirty; + match got { + Some(counts::Opened::Kept) => {} + Some(counts::Opened::Counted(c)) => e.count = Some(c), + None => e.count = None, } + e.stale = missed; + e.watched = watched; + e.seeded = false; + e.stamp = stamp; true } @@ -386,8 +437,9 @@ impl Listing { any } - /// Counts every folder, as sorting by size needs, on several threads, with nothing watched. - /// Stops early if `cancel` gets set. + /// Counts every folder still to count, as sorting by size needs, on several threads, with + /// nothing watched: those that come on screen are watched then. Stops early if `cancel` + /// gets set. pub fn count_all(&self, cancel: &AtomicBool) { if !self.counts_folders() { return; @@ -411,40 +463,62 @@ impl Listing { }); } - /// Takes the counts of the rows given from the last listing of this folder, by name, as - /// stale: each is shown until it's counted again, so reading the folder again doesn't - /// blank them. - pub fn adopt_counts(&self, old: &Listing, ids: &[u32]) { + /// Takes the counts of the last listing of this folder, by name, as seeded: each shows at + /// once, and stands once the row's stat finds its folder as it was when counted, so reading + /// the folder again neither blanks them nor reads every folder again. + pub fn seed_counts(&self, old: &Listing) { if !self.counts_folders() { return; } - let known: HashMap<&[u8], Option> = match old.counts.lock() { - Ok(c) if !c.is_empty() => c.iter().filter(|(i, _)| (**i as usize) < old.len()).map(|(&i, c)| (old.name(i), c.count)).collect(), + let known: HashMap<&[u8], Counted> = match old.counts.lock() { + Ok(c) if !c.is_empty() => c.iter().filter(|(i, c)| (**i as usize) < old.len() && c.count.is_some() && c.stamp.is_some()).map(|(&i, c)| (old.name(i), *c)).collect(), _ => return, }; + if known.is_empty() { + return; + } let Ok(mut counts) = self.counts.lock() else { return }; - for &i in ids { - if let Some(&count) = known.get(self.name(i)) - && self.kind(i).is_dirlike() + for i in 0..self.len() as u32 { + if self.kind(i).is_dirlike() + && let Some(c) = known.get(self.name(i)) { - counts.entry(i).or_insert(Counted { count, stale: true }); + counts.insert(i, Counted { count: c.count, stale: true, watched: false, seeded: true, stamp: c.stamp, dirty: 0 }); } } } + /// A row's stat found its folder like this: a seeded count stands if the folder is as it was + /// when counted, and is counted again if not. + fn check_seeded(&self, i: u32, stamp: Stamp) { + if let Ok(mut counts) = self.counts.lock() + && let Some(c) = counts.get_mut(&i) + && c.seeded + { + c.seeded = false; + c.stale = c.stamp != Some(stamp); + } + } + + /// Its folders aren't watched any more, as when it was put aside for another folder: each + /// is checked again when it's on screen, and read again only if it changed. + pub fn forget_watches(&self) { + if let Ok(mut counts) = self.counts.lock() { + counts.values_mut().for_each(|c| c.watched = false); + } + } + /// Marks the rows given as to count again, or every row counted, keeping what they show - /// until then. + /// until then. A row being counted right now is counted again after. pub fn recount(&self, ids: Option<&[u32]>) { let Ok(mut counts) = self.counts.lock() else { return }; + let mark = |c: &mut Counted| { + c.stale = true; + c.seeded = false; + c.dirty = c.dirty.wrapping_add(1); + }; match ids { - Some(ids) => { - for i in ids { - if let Some(c) = counts.get_mut(i) { - c.stale = true; - } - } - } - None => counts.values_mut().for_each(|c| c.stale = true), + Some(ids) => ids.iter().for_each(|&i| mark(counts.entry(i).or_default())), + None => counts.values_mut().for_each(mark), } } @@ -610,11 +684,23 @@ pub struct LoadRequest { pub recent: bool, /// Search `dir` and below for names containing this, instead of listing it. pub search: Option, + /// The last listing of `dir`, whose folders' counts the new one starts from. + pub prior: Option, /// The home Trash (`$XDG_DATA_HOME/Trash`) and the user's id, so that a search leaves out /// every Trash folder, whose items have to stay paired with their info files. pub search_skips_trash: Option<(PathBuf, u32)>, } +/// A listing a new one of the same folder starts its counts from. +#[derive(Clone)] +pub struct Prior(pub Arc); + +impl std::fmt::Debug for Prior { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Prior({:?})", self.0.dir) + } +} + #[derive(Clone, Debug)] pub struct TrashSpec { /// `$XDG_DATA_HOME/Trash`. @@ -818,6 +904,9 @@ fn load(req: LoadRequest, watch: Option<&Arc>, cancel: &Arc, l.names.shrink_to_fit(); l.slots.shrink_to_fit(); l.meta = l.slots.iter().map(|_| new_meta()).collect(); + if let Some(Prior(p)) = req.prior.as_ref().filter(|p| p.0.dir == l.dir) { + l.seed_counts(p); + } publish_final(Arc::new(l), &req, cancel, sink); } @@ -1278,12 +1367,23 @@ impl Stater { Err(_) => return, }, }; - for chunk in ids.chunks(64) { - let statted = listing.stat_entries(chunk); - if statted | listing.count_entries(chunk, &mut buf, watch.as_ref().map(|(w, g)| (&**w, *g))) { + 'chunks: for chunk in ids.chunks(64) { + let mut any = listing.stat_entries(chunk); + // Newer requests replace this one: the window moved on. Checked between + // folders too, as a big one takes a while to count. + for &i in chunk { + if let Some(newest) = rx.try_iter().last() { + next = Some(newest); + if any { + on_progress(); + } + break 'chunks; + } + any |= listing.count_one(i, &mut buf, watch.as_ref().map(|(w, g)| (&**w, *g))); + } + if any { on_progress(); } - // Newer requests replace this one: the window moved on. if let Some(newest) = rx.try_iter().last() { next = Some(newest); break; @@ -1320,7 +1420,7 @@ mod tests { } fn request(dir: &Path) -> LoadRequest { - LoadRequest { dir: dir.into(), generation: 1, sort: SortSpec::default(), show_hidden: false, filter: String::new(), first_row: 0, row_count: 64, slow_read: None, slow_stat: None, trash: None, recent: false, search: None, search_skips_trash: None } + LoadRequest { dir: dir.into(), generation: 1, sort: SortSpec::default(), show_hidden: false, filter: String::new(), first_row: 0, row_count: 64, slow_read: None, slow_stat: None, trash: None, recent: false, search: None, search_skips_trash: None, prior: None } } /// Runs a load to completion, returning every event in order. @@ -1604,6 +1704,106 @@ mod tests { assert_eq!(row_names(&last(run(r))), ["lots", "many", "few", "file"], "hidden ones too, when they show"); } + fn loaded(dir: &Path, sort: SortSpec, prior: Option>) -> Loaded { + let mut r = request(dir); + r.sort = sort; + r.prior = prior.map(Prior); + last(run(r)) + } + + fn count_now(l: &Listing, name: &str, watch: Option<(&Watches, u64)>) -> bool { + let mut buf = Vec::new(); + l.count_one(l.find(name.as_bytes()).unwrap(), &mut buf, watch) + } + + #[test] + fn a_change_while_a_folder_is_being_read_counts_it_again() { + let s = Scratch::new(); + s.file("sub/a", b""); + let l = loaded(s.path(), SortSpec::default(), None).listing; + let i = l.find(b"sub").unwrap(); + // A change heard between the folder being opened and read: its watch is spent, so the + // count mustn't be taken as the last word. + DURING_COUNT.with(|h| *h.borrow_mut() = Some(Box::new(|l: &Listing, i| l.recount(Some(&[i]))))); + assert!(count_now(&l, "sub", None)); + DURING_COUNT.with(|h| *h.borrow_mut() = None); + assert_eq!(l.items(i, false), Some(1)); + assert!(l.wants_count(i), "still to count again"); + assert!(count_now(&l, "sub", None)); + assert!(!l.wants_count(i), "counted after the change"); + } + + #[test] + fn folders_counted_for_a_sort_are_watched_once_on_screen_without_reading_them_again() { + let s = Scratch::new(); + s.file("kept/a", b""); + s.file("changed/a", b""); + let size = SortSpec { key: SortKey::Size, descending: true }; + let l = loaded(s.path(), size, None).listing; + let (kept, changed) = (l.find(b"kept").unwrap(), l.find(b"changed").unwrap()); + assert!(!l.wants_count(kept) && l.wants_watch(kept), "counted for the sort, not watched"); + let w = Watches::new().unwrap(); + let g = w.begin(); + s.file("changed/b", b""); + assert!(count_now(&l, "kept", Some((&w, g))) && count_now(&l, "changed", Some((&w, g)))); + assert_eq!(w.len(), 2, "both watched now"); + assert!(!l.wants_watch(kept) && !l.wants_count(kept)); + assert_eq!((l.items(kept, false), l.items(changed, false)), (Some(1), Some(2)), "the one that changed since is read again"); + // A change now is heard. + s.file("kept/b", b""); + assert_eq!(w.drain(), [kept]); + } + + #[test] + fn reading_a_folder_again_reads_only_the_folders_that_changed() { + let s = Scratch::new(); + s.file("same/a", b""); + s.file("grew/a", b""); + let size = SortSpec { key: SortKey::Size, descending: true }; + let old = loaded(s.path(), size, None).listing; + s.file("grew/b", b""); + s.file("new/a", b""); + // Read by name order here, so the sort's own counting doesn't race the check. + let mut r = request(s.path()); + r.prior = Some(Prior(old)); + r.row_count = 0; + let l = last(run(r)).listing; + l.stat_all(&AtomicBool::new(false)); + // Which folders a count opens, on this thread. + let read = Arc::new(Mutex::new(Vec::new())); + let r2 = read.clone(); + DURING_COUNT.with(|h| *h.borrow_mut() = Some(Box::new(move |l: &Listing, i| r2.lock().unwrap().push(String::from_utf8_lossy(l.name(i)).into_owned())))); + let mut buf = Vec::new(); + l.count_entries(&(0..l.len() as u32).collect::>(), &mut buf, None); + DURING_COUNT.with(|h| *h.borrow_mut() = None); + let mut read = read.lock().unwrap().clone(); + read.sort(); + assert_eq!(read, ["grew", "new"], "the unchanged folder isn't read again"); + let id = |n: &str| l.find(n.as_bytes()).unwrap(); + assert_eq!((l.items(id("same"), false), l.items(id("grew"), false), l.items(id("new"), false)), (Some(1), Some(2), Some(1))); + } + + #[test] + fn a_seeded_count_stands_only_if_its_folder_is_as_it_was() { + let s = Scratch::new(); + s.file("same/a", b""); + s.file("grew/a", b""); + let old = loaded(s.path(), SortSpec::default(), None).listing; + let mut buf = Vec::new(); + old.count_entries(&(0..old.len() as u32).collect::>(), &mut buf, None); + s.file("grew/b", b""); + let mut r = request(s.path()); + r.prior = Some(Prior(old)); + r.row_count = 0; + let l = last(run(r)).listing; + let id = |n: &str| l.find(n.as_bytes()).unwrap(); + assert_eq!(l.items(id("grew"), false), Some(1), "shown from the last listing at once"); + assert!(l.wants_count(id("same")) && l.wants_count(id("grew")), "until its stat says"); + l.stat_entries(&[id("same"), id("grew")]); + assert!(!l.wants_count(id("same")), "the same folder, unchanged: its count stands"); + assert!(l.wants_count(id("grew")), "changed since: read again"); + } + #[test] fn the_trash_recent_and_search_results_dont_count() { let s = Scratch::new(); diff --git a/crates/core/src/tokens.rs b/crates/core/src/tokens.rs index 5430236..a8df087 100644 --- a/crates/core/src/tokens.rs +++ b/crates/core/src/tokens.rs @@ -1255,6 +1255,15 @@ pub mod motion { /// Quick View: holding an arrow runs through files; only stopping on one this long starts its preview. pub const MOVE_SETTLE: Duration = Duration::from_millis(40); + + /// How long after a folder in the list changes its item count ("8 items") is counted again, so a burst of changes is one count (crates/app/src/app.rs). + pub const RECOUNT_AFTER: Duration = Duration::from_millis(100); + + /// A folder counted again sooner than this after its last count waits twice as long as last time for the next one, up to recount-max-wait; one quiet this long goes back to recount-after. + pub const RECOUNT_QUIET: Duration = Duration::from_millis(1000); + + /// The longest a folder that keeps changing waits to be counted again, so a busy folder's count updates at most this often. + pub const RECOUNT_MAX_WAIT: Duration = Duration::from_millis(2000); } /// Unitless multiples. diff --git a/crates/core/tests/watch_threads.rs b/crates/core/tests/watch_threads.rs index 00b9f8b..30b2a7d 100644 --- a/crates/core/tests/watch_threads.rs +++ b/crates/core/tests/watch_threads.rs @@ -25,7 +25,7 @@ fn a_thousand_loads_leave_one_watch_thread_and_no_more_threads() { let (tx, rx) = mpsc::channel(); for g in 1..=1000u64 { let dir = dirs[g as usize % dirs.len()].clone(); - let req = LoadRequest { dir, generation: g, sort: SortSpec::default(), show_hidden: false, filter: String::new(), first_row: 0, row_count: 64, slow_read: None, slow_stat: None, trash: None, recent: false, search: None, search_skips_trash: None }; + let req = LoadRequest { dir, generation: g, sort: SortSpec::default(), show_hidden: false, filter: String::new(), first_row: 0, row_count: 64, slow_read: None, slow_stat: None, trash: None, recent: false, search: None, search_skips_trash: None, prior: None }; let tx = tx.clone(); spawn_load_watching(req, Some(w.clone()), move |e| { if matches!(&e, LoadEvent::Failed { .. }) || matches!(&e, LoadEvent::Ready(l) if l.settled) { diff --git a/design/tokens.json b/design/tokens.json index 1e14109..79e4bc8 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -1210,6 +1210,21 @@ "name": "move-settle", "value": "40ms", "usage": "Quick View: holding an arrow runs through files; only stopping on one this long starts its preview." + }, + { + "name": "recount-after", + "value": "100ms", + "usage": "How long after a folder in the list changes its item count (\"8 items\") is counted again, so a burst of changes is one count (crates/app/src/app.rs)." + }, + { + "name": "recount-quiet", + "value": "1000ms", + "usage": "A folder counted again sooner than this after its last count waits twice as long as last time for the next one, up to recount-max-wait; one quiet this long goes back to recount-after." + }, + { + "name": "recount-max-wait", + "value": "2000ms", + "usage": "The longest a folder that keeps changing waits to be counted again, so a busy folder's count updates at most this often." } ] }, diff --git a/tests/e2e.py b/tests/e2e.py index 6fd92f0..c0ae64a 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -789,6 +789,12 @@ def a_folders_size_says_how_many_items_it_holds(h): a.shot("folder-counts-by-size-light") (fs / "one/y.txt").unlink() (fs / "eight/0.txt").write_text("") + else: + # Opened sorted by size, every folder was counted for the sort, and each on + # screen is still watched. + assert s["sort"] == "Size", s["sort"] + (fs / "none/new.txt").write_text("") + a.wait(lambda s: sizes(s)["none"] == "1 item", "a folder counted for the sort counted again after a change") a.close() finally: shutil.rmtree(gtk, ignore_errors=True) From 0234a2b4352151e8e036e2492b46a3e0b2d8247e Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 21:59:47 -0700 Subject: [PATCH 4/8] ALI-2598: Keep the recount timings in the code, as they pace work The design README keeps timings that pace work, not what's seen, in the code, so recount-after, recount-quiet and recount-max-wait leave the token file for named constants in app.rs, and the README lists them with the other behaviour values. --- crates/app/src/app.rs | 12 +++++++++--- crates/core/src/tokens.rs | 9 --------- design/README.md | 2 +- design/tokens.json | 15 --------------- 4 files changed, 10 insertions(+), 28 deletions(-) diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index 83fee9b..8f9ab71 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -57,9 +57,15 @@ const SMALL_BUTTON: f32 = size::SMALL_BUTTON; const DOUBLE_CLICK: Duration = motion::DOUBLE_CLICK; const TYPE_AHEAD_RESET: Duration = motion::TYPE_AHEAD_RESET; const HOLD_FOR_LOAD: Duration = motion::HOLD_FOR_LOAD; -const RECOUNT_AFTER: Duration = motion::RECOUNT_AFTER; -const RECOUNT_QUIET: Duration = motion::RECOUNT_QUIET; -const RECOUNT_MAX_WAIT: Duration = motion::RECOUNT_MAX_WAIT; +/// How long after a counted folder changes it's counted again, so a burst of changes is one +/// count. It paces work, so it stays here rather than in the design tokens. +const RECOUNT_AFTER: Duration = Duration::from_millis(100); +/// A folder counted again sooner than this after its last count waits twice as long as last +/// time for the next; one quiet this long goes back to `RECOUNT_AFTER`. +const RECOUNT_QUIET: Duration = Duration::from_millis(1000); +/// The longest a folder that keeps changing waits to be counted again, so a busy folder's count +/// updates at most this often. +const RECOUNT_MAX_WAIT: Duration = Duration::from_millis(2000); const JOB_SHOW_AFTER: Duration = motion::JOB_SHOW_AFTER; const UNDO_DEPTH: usize = 20; pub(crate) const DIALOG_GUARD: Duration = motion::DIALOG_GUARD; diff --git a/crates/core/src/tokens.rs b/crates/core/src/tokens.rs index a8df087..5430236 100644 --- a/crates/core/src/tokens.rs +++ b/crates/core/src/tokens.rs @@ -1255,15 +1255,6 @@ pub mod motion { /// Quick View: holding an arrow runs through files; only stopping on one this long starts its preview. pub const MOVE_SETTLE: Duration = Duration::from_millis(40); - - /// How long after a folder in the list changes its item count ("8 items") is counted again, so a burst of changes is one count (crates/app/src/app.rs). - pub const RECOUNT_AFTER: Duration = Duration::from_millis(100); - - /// A folder counted again sooner than this after its last count waits twice as long as last time for the next one, up to recount-max-wait; one quiet this long goes back to recount-after. - pub const RECOUNT_QUIET: Duration = Duration::from_millis(1000); - - /// The longest a folder that keeps changing waits to be counted again, so a busy folder's count updates at most this often. - pub const RECOUNT_MAX_WAIT: Duration = Duration::from_millis(2000); } /// Unitless multiples. diff --git a/design/README.md b/design/README.md index 84f2956..a22089c 100644 --- a/design/README.md +++ b/design/README.md @@ -19,7 +19,7 @@ 2. Run `design/build` from anywhere in the repo. It needs only Cargo. 3. Commit `tokens.json` and `crates/core/src/tokens.rs` together. A colour changes in `crates/core/src/theme.rs`, not here: change the derivation, then copy what it gives into the tokens (the test says which theme differs). -In the code, use the constants (`self.px(size::ROW)`, `radius::CONTROL`, `motion::DOUBLE_CLICK`) instead of a literal value. A size made from others stays a sum (`self.px(spacing::SPACE_14 * 2.0)`), so it rounds as it did. The `space-*` steps are the scale for paddings and gaps; a size with a meaning of its own gets its own token. Behaviour stays in the code: how far a key, the wheel or a drag's or menu's autoscroll moves, Quick View's pan, zoom, seek and volume steps, how far the pointer moves before a press becomes a drag, and timings that pace work rather than what's seen (a drag's grace period, how often the rubber band scrolls, how long Quick View waits for a document's reports to catch up). So do nudges of a device pixel (a text field's 1 px caret and inset, the caret's scroll slack, a code span's padding) and the white of a PDF page. +In the code, use the constants (`self.px(size::ROW)`, `radius::CONTROL`, `motion::DOUBLE_CLICK`) instead of a literal value. A size made from others stays a sum (`self.px(spacing::SPACE_14 * 2.0)`), so it rounds as it did. The `space-*` steps are the scale for paddings and gaps; a size with a meaning of its own gets its own token. Behaviour stays in the code: how far a key, the wheel or a drag's or menu's autoscroll moves, Quick View's pan, zoom, seek and volume steps, how far the pointer moves before a press becomes a drag, and timings that pace work rather than what's seen (a drag's grace period, how often the rubber band scrolls, how long Quick View waits for a document's reports to catch up, and how soon and how often a folder that changed has its items counted again). So do nudges of a device pixel (a text field's 1 px caret and inset, the caret's scroll slack, a code span's padding) and the white of a PDF page. ## The check diff --git a/design/tokens.json b/design/tokens.json index 79e4bc8..1e14109 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -1210,21 +1210,6 @@ "name": "move-settle", "value": "40ms", "usage": "Quick View: holding an arrow runs through files; only stopping on one this long starts its preview." - }, - { - "name": "recount-after", - "value": "100ms", - "usage": "How long after a folder in the list changes its item count (\"8 items\") is counted again, so a burst of changes is one count (crates/app/src/app.rs)." - }, - { - "name": "recount-quiet", - "value": "1000ms", - "usage": "A folder counted again sooner than this after its last count waits twice as long as last time for the next one, up to recount-max-wait; one quiet this long goes back to recount-after." - }, - { - "name": "recount-max-wait", - "value": "2000ms", - "usage": "The longest a folder that keeps changing waits to be counted again, so a busy folder's count updates at most this often." } ] }, From 92fb568e0391c8d237eb15e6c619c02e3cb825de Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 22:21:37 -0700 Subject: [PATCH 5/8] ALI-2598: Sort by the items that show, free watches of folders that go - A sort by size goes by the items that show, so showing hidden files during a load sorts again, and a folder shown again from the cache sorts again if hidden files were shown or hidden since its order was kept. - A watched folder deleted, or its disk unmounted, says only IGNORED: that frees its place and counts its row again. - A watch the system won't add (its limit, or no /proc) isn't tried again on every scroll, only once a watch has been let go of, or on a new listing. - A folder read only as far as the 100,000-entry ceiling says how many that show it found, "3+ items", and sorts by that, rather than "10,000+". - A stamp carries the folder's disk, and is trusted only once its modified time is 2 s old, for disks that keep times to the second or two. A count without one is still shown from the last listing, and read again. - A link to a folder whose count came from the last listing is opened to check its target's stamp, and read only if that changed. - The rename field is as narrow as the name beside a wide count. - Counting every folder for a sort checks for a cancel between folders. --- README.md | 5 +- crates/app/src/app.rs | 84 +++++++++++++++-- crates/app/src/format.rs | 26 ++++-- crates/app/src/paint.rs | 8 +- crates/core/src/counts.rs | 183 +++++++++++++++++++++++++++++++------ crates/core/src/listing.rs | 138 ++++++++++++++++++++++++---- tests/e2e.py | 8 ++ 7 files changed, 384 insertions(+), 68 deletions(-) diff --git a/README.md b/README.md index 7c5c11b..6c588d5 100644 --- a/README.md +++ b/README.md @@ -154,8 +154,9 @@ and Save dialogs from other apps read and save the same orders. The orders are k `$XDG_STATE_HOME/gannet/sorts`, which is `~/.local/state/gannet/sorts` by default. A folder's Size says how many items it holds: "8 items", "1 item", "Empty", or "10,000+ items", -where counting stops (also after reading 100,000 entries, mostly hidden ones). Hidden items count -only while hidden files show. Only folders on screen are counted, on a thread of their own after +where counting stops. Hidden items count only while hidden files show. A folder of more than +100,000 entries, nearly all hidden, is read only that far: it says how many that show it found, +as "3+ items", and sorts by that. Only folders on screen are counted, on a thread of their own after the rows show, so opening a folder is no slower. Each folder on screen is watched once counted, so a change in it counts it again, a moment later; one that keeps changing is counted at most every 2 seconds. Sorting by size counts every folder, fullest first, without watching them; each diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index 8f9ab71..66d4536 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -96,7 +96,8 @@ pub enum Msg { /// The folder showing isn't the one at its path any more: the answer to `App::check_folder`. NotTheSame(PathBuf), Stats(u64), - Derived { generation: u64, listing: Arc, sorted: Arc>, rows: Vec, sort: SortSpec }, + /// `sorted_hidden` is the show-hidden setting it was sorted again with, if it was. + Derived { generation: u64, listing: Arc, sorted: Arc>, rows: Vec, sort: SortSpec, sorted_hidden: Option }, Font(PathBuf, u32), PrimaryFont(PathBuf, u32), /// What fontconfig chose for one of the preview's document fonts. @@ -799,6 +800,11 @@ pub struct App { recounted: HashMap, /// A re-sort is on its way, so a lighter request mustn't replace it. resort_pending: bool, + /// Whether hidden files showed when `sorted` was sorted, as a sort by size goes by them. + sorted_hidden: bool, + /// How wide the rename field was last drawn, narrower than a name's room when the row's + /// count is wide, so clicks and the screen reader find it where it is. + pub(crate) rename_room: Option, /// A change arrived during a load, so another load follows it. reload_after_load: bool, stater_gen: u64, @@ -842,6 +848,8 @@ struct Cached { listing: Arc, sorted: Arc>, sort: SortSpec, + /// Whether hidden files showed when it was sorted, which a sort by size goes by. + hidden: bool, } /// The folder showing, gone: deleted, or moved away, perhaps to a Trash. The window stays on @@ -1005,6 +1013,8 @@ impl App { recount_due: HashMap::new(), recounted: HashMap::new(), resort_pending: false, + sorted_hidden: false, + rename_room: None, reload_after_load: false, stater_gen: 0, first_load: true, @@ -1239,7 +1249,10 @@ impl App { } fn show_cached(&mut self, c: Cached) { - let same_sort = c.sort == self.view_sort(); + // Folders sorted by size go by the items that show, so hidden files shown or hidden + // since it was sorted sort it again. + let same_sort = c.sort == self.view_sort() && (c.sort.key != SortKey::Size || c.hidden == self.show_hidden); + self.sorted_hidden = c.hidden; self.listing = Some(c.listing.clone()); self.sorted = c.sorted; self.rows = self.choosable(&c.listing, visible_rows(&c.listing, &self.sorted, self.show_hidden, &self.filter)); @@ -1399,6 +1412,7 @@ impl App { let (keep_cursor, keep_anchor) = (name_at(self.cursor, &self.rows), name_at(self.anchor, &self.rows)); self.listing = Some(l.listing.clone()); self.sorted = Arc::new(l.sorted); + self.sorted_hidden = self.req_hidden; self.rows = self.choosable(&l.listing, l.rows); self.selected = vec![0; l.listing.len().div_ceil(64)]; self.sel_count = 0; @@ -1462,7 +1476,8 @@ impl App { if l.sort != self.view_sort() { self.rederive(true); } else if self.req_hidden != self.show_hidden || self.req_filter != self.filter { - self.rederive(false); + // Folders sorted by size go by the items that show. + self.rederive(self.req_hidden != self.show_hidden && self.view_sort().key == SortKey::Size); } self.clamp_scroll(); if l.settled && l.listing.complete { @@ -1484,7 +1499,7 @@ impl App { return; } self.cache.retain(|c| c.listing.dir != listing.dir); - self.cache.push(Cached { listing, sorted: self.sorted.clone(), sort }); + self.cache.push(Cached { listing, sorted: self.sorted.clone(), sort, hidden: self.sorted_hidden }); while self.cache.len() > CACHE_ENTRIES || self.cache.iter().map(|c| c.listing.len()).sum::() > CACHE_TOTAL_ROWS { if self.cache.len() <= 1 { break; @@ -1554,7 +1569,7 @@ impl App { None => rows, }; if !cancel.load(Ordering::Relaxed) { - hub.send(Msg::Derived { generation, listing: l, sorted, rows, sort }); + hub.send(Msg::Derived { generation, listing: l, sorted, rows, sort, sorted_hidden: resort.then_some(hidden) }); } }); if spawned.is_err() { @@ -1690,11 +1705,14 @@ impl App { // One that was stopped may be back on screen. self.request_thumbnails(); } - Msg::Derived { generation, listing, sorted, rows, sort } => { + Msg::Derived { generation, listing, sorted, rows, sort, sorted_hidden } => { let current = self.listing.as_ref().is_some_and(|l| Arc::ptr_eq(l, &listing)); if generation == self.derive_gen && current { self.resort_pending = false; self.sorted = sorted; + if let Some(h) = sorted_hidden { + self.sorted_hidden = h; + } self.remember(listing, sort); self.apply_rows(rows); } @@ -1902,8 +1920,8 @@ impl App { return; } self.stats_range = range; - let watching = self.counts.is_some(); - let ids: Vec = self.rows[range.0..range.1].iter().copied().filter(|&i| l.stat(i) == Stat::Unknown || l.wants_count(i) || (watching && l.wants_watch(i))).collect(); + let freed = self.counts.as_ref().map(|w| w.freed()); + let ids: Vec = self.rows[range.0..range.1].iter().copied().filter(|&i| l.stat(i) == Stat::Unknown || l.wants_count(i) || freed.is_some_and(|f| l.wants_watch(i, f))).collect(); if !ids.is_empty() { st.request(ids); } @@ -2927,6 +2945,7 @@ impl App { // about the last can't land in it. if e != self.edit { self.edit_gen += 1; + self.rename_room = None; } self.edit = e; if !matches!(self.edit, Edit::None) { @@ -12934,6 +12953,55 @@ mod tests { assert_eq!(r.row_names(), ["b", "a", "c", "small.txt", "big.bin"]); } + /// Folders whose order by size depends on hidden files: `many` 2 + 1 hidden, `few` 1, + /// `lots` 4 hidden. + fn hidden_sized(r: &Rig) { + for (f, names) in [("many", &["a", "b", ".c"][..]), ("few", &["a"][..]), ("lots", &[".a", ".b", ".c", ".d"][..])] { + fs::create_dir(r.work().join(f)).unwrap(); + for n in names { + fs::write(r.work().join(f).join(n), "").unwrap(); + } + } + } + + fn settled(a: &App) -> bool { + !a.loading && !a.resort_pending && a.rows.len() == 3 + } + + #[test] + fn showing_hidden_files_during_a_load_sorts_by_size_again() { + let mut r = Rig::new("counts-hidden-load"); + hidden_sized(&r); + r.open(r.work()); + r.app.action(Action::SortBy(SortKey::Size)); + r.pump_until("sorted", |a| a.sort.key == SortKey::Size && settled(a)); + assert_eq!(r.row_names(), ["many", "few", "lots"]); + // Read again, and hidden files shown before that's done. + r.app.reload(); + r.app.show_hidden = true; + r.pump_until("read and sorted again", settled); + r.pump_until("sorted by what shows now", |a| settled(a) && a.sorted_hidden); + assert_eq!(r.row_names(), ["lots", "many", "few"]); + } + + #[test] + fn a_folder_shown_again_sorts_by_size_again_if_hidden_files_changed_meanwhile() { + let mut r = Rig::new("counts-hidden-cache"); + hidden_sized(&r); + r.open(r.work()); + r.app.action(Action::SortBy(SortKey::Size)); + r.pump_until("sorted", |a| a.sort.key == SortKey::Size && settled(a)); + assert_eq!(r.row_names(), ["many", "few", "lots"]); + r.open(r.work().join("few")); + r.app.action(Action::ToggleHidden); + // Back, from what was kept of it: sorted again at once, not only once it's read again. + r.app.go(Stop { dir: r.work(), cursor_name: None, search: None }); + assert!(r.app.resort_pending, "the kept order was for hidden files hidden"); + let work = r.work(); + r.pump_until("shown again, and sorted", |a| a.dir == work && settled(a) && a.sorted_hidden); + assert_eq!(r.row_names(), ["lots", "many", "few"]); + } + #[test] fn a_change_in_a_counted_folder_counts_it_again_without_reading_the_folder_showing() { let mut r = Rig::new("counts-watch"); diff --git a/crates/app/src/format.rs b/crates/app/src/format.rs index a45a1b3..2197391 100644 --- a/crates/app/src/format.rs +++ b/crates/app/src/format.rs @@ -41,11 +41,12 @@ fn grouped(n: usize) -> String { } /// How many items a folder holds: `Empty`, `1 item`, `8 items`, or `10,000+ items` past the -/// most that's counted. -pub fn items(n: u32) -> String { +/// most that's counted. With `more`, reading stopped first, so it's at least `n`: `3+ items`. +pub fn items(n: u32, more: bool) -> String { match n { - 0 => "Empty".into(), n if n > CAP => format!("{}+ items", grouped(CAP as usize)), + n if more => format!("{}+ items", grouped(n as usize)), + 0 => "Empty".into(), n => count(n as usize, "item", "items"), } } @@ -55,7 +56,7 @@ pub fn items(n: u32) -> String { /// and for good for a folder on a network place. pub fn size_cell(l: &Listing, id: u32, show_hidden: bool) -> String { if l.kind(id).is_dirlike() { - return l.items(id, show_hidden).map(items).unwrap_or_default(); + return l.items_more(id, show_hidden).map(|(n, more)| items(n, more)).unwrap_or_default(); } match l.stat(id) { Stat::Known { size: bytes, .. } => size(bytes), @@ -89,11 +90,16 @@ mod tests { #[test] fn folder_counts_read_well() { - assert_eq!(items(0), "Empty"); - assert_eq!(items(1), "1 item"); - assert_eq!(items(8), "8 items"); - assert_eq!(items(1234), "1,234 items"); - assert_eq!(items(CAP), "10,000 items"); - assert_eq!(items(CAP + 1), "10,000+ items"); + assert_eq!(items(0, false), "Empty"); + assert_eq!(items(1, false), "1 item"); + assert_eq!(items(8, false), "8 items"); + assert_eq!(items(1234, false), "1,234 items"); + assert_eq!(items(CAP, false), "10,000 items"); + assert_eq!(items(CAP + 1, false), "10,000+ items"); + // Reading stopped before the count of those that show was known. + assert_eq!(items(3, true), "3+ items"); + assert_eq!(items(1, true), "1+ items"); + assert_eq!(items(0, true), "0+ items"); + assert_eq!(items(CAP + 1, true), "10,000+ items"); } } diff --git a/crates/app/src/paint.rs b/crates/app/src/paint.rs index 704614a..019e880 100644 --- a/crates/app/src/paint.rs +++ b/crates/app/src/paint.rs @@ -317,7 +317,9 @@ impl App { let first = (self.scroll / l.row_h.max(1) as f64) as usize; let offset = (self.scroll - first as f64 * l.row_h as f64) as i32; let y = area.y + (row as i32 - first as i32) * l.row_h - offset; - Some(Rect::new(name_x - self.px(spacing::SPACE_4), y + 1, name_max(self) + self.px(spacing::SPACE_8), box_h)) + // The width the field was last drawn at, which a wide count beside it narrows. + let w = self.rename_room.map_or(name_max(self), |r| r.min(name_max(self))); + Some(Rect::new(name_x - self.px(spacing::SPACE_4), y + 1, w + self.px(spacing::SPACE_8), box_h)) } _ => None, } @@ -653,7 +655,9 @@ impl App { { let f = field.clone(); let box_h = (row_h - self.px(spacing::SPACE_2)).max(1); - self.paint_field(c, Rect::new(name_x - self.px(spacing::SPACE_4), y + 1, name_max as i32 + self.px(spacing::SPACE_8), box_h), &f, true); + // As narrow as the name beside a wide count is, so it doesn't cover it. + self.rename_room = Some(row_name_max as i32); + self.paint_field(c, Rect::new(name_x - self.px(spacing::SPACE_4), y + 1, row_name_max as i32 + self.px(spacing::SPACE_8), box_h), &f, true); } else { self.text.draw_fitted(c, &shown, name_x as f32, by, row_name_max, if is_cut { dim } else { fg }); } diff --git a/crates/core/src/counts.rs b/crates/core/src/counts.rs index d405ecb..e01bd1b 100644 --- a/crates/core/src/counts.rs +++ b/crates/core/src/counts.rs @@ -30,17 +30,30 @@ pub const CAP: u32 = 10_000; pub struct Count { pub all: u32, pub shown: u32, + /// Reading stopped at `READ_CEILING` before the cap: there are at least `shown` that + /// aren't hidden, and maybe more. + pub more: bool, } impl Count { + pub fn new(all: u32, shown: u32) -> Self { + Self { all, shown, more: false } + } + /// The count the list shows, by the show-hidden setting. pub fn items(self, show_hidden: bool) -> u32 { if show_hidden { self.all } else { self.shown } } + + /// Whether there may be more than `items` says: "3+ items". + pub fn more(self, show_hidden: bool) -> bool { + self.more && !show_hidden && self.shown <= CAP + } } -/// The most entries a count reads. A folder of this many hidden ones isn't read to the end: -/// it says "10,000+ items" either way. +/// The most entries a count reads. A folder of this many, mostly hidden, isn't read to the end: +/// with hidden files showing it says "10,000+ items", and without, how many that aren't hidden +/// it found, as "3+ items". pub const READ_CEILING: u32 = 100_000; /// What `count_in` did with an open folder. @@ -51,19 +64,32 @@ pub enum Opened { Kept, } -/// What a folder was when it was counted: its inode and modified time, which change with any -/// entry added, removed or renamed in it. A folder whose stamp is the same needn't be read again. +/// What a folder was when it was counted: its disk, inode and modified time, which changes with +/// any entry added, removed or renamed in it. A folder whose stamp is the same needn't be read +/// again. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Stamp { + pub dev: u64, pub ino: u64, pub sec: i64, pub nsec: u32, } +/// How much older than now a folder's modified time must be for its stamp to be trusted. Some +/// disks keep times only to the second or two (vfat, ext3), so a change soon after a count +/// can leave the time as it was. +pub const STAMP_SETTLE_SECS: i64 = 2; + impl Stamp { + /// The stamp of an open folder, if it can be trusted now. pub fn of(fd: BorrowedFd<'_>) -> Option { let st = rustix::fs::fstat(fd).ok()?; - Some(Self { ino: st.st_ino as u64, sec: st.st_mtime as i64, nsec: st.st_mtime_nsec as u32 }) + Self::taken(Self { dev: st.st_dev as u64, ino: st.st_ino as u64, sec: st.st_mtime as i64, nsec: st.st_mtime_nsec as u32 }, crate::time::now()) + } + + /// The stamp, if its time is old enough at `now` (seconds) to be sure a later change moves it. + pub fn taken(self, now: i64) -> Option { + (now - self.sec >= STAMP_SETTLE_SECS).then_some(self) } } @@ -82,7 +108,7 @@ pub fn count_in(dir: BorrowedFd<'_>, name: &CStr, buf: &mut [MaybeUninit], o } fn count_open(fd: &OwnedFd, buf: &mut [MaybeUninit], ceiling: u32) -> Option { - let mut c = Count { all: 0, shown: 0 }; + let mut c = Count::new(0, 0); let mut read = 0; let mut iter = RawDir::new(fd, buf); while let Some(e) = iter.next() { @@ -99,10 +125,10 @@ fn count_open(fd: &OwnedFd, buf: &mut [MaybeUninit], ceiling: u32) -> Option break; } } - // So many hidden entries that what shows can't be told without reading on: over the - // cap, as far as the count goes. + // So many entries, mostly hidden, that how many show can't be told without reading on: + // at least what's been seen. if read >= ceiling { - return Some(Count { all: CAP + 1, shown: CAP + 1 }); + return Some(Count { all: CAP + 1, shown: c.shown, more: true }); } } c.all = c.all.min(CAP + 1); @@ -226,6 +252,22 @@ struct Inner { generation: u64, /// Each watch, and the rows it's for: two rows can be one folder, as a link to it is. rows: HashMap>, + /// Goes up each time watches go, so a row whose watch couldn't be added knows when to try + /// again. + freed: u64, + #[cfg(test)] + fail_adds: bool, +} + +/// What `Watches::add` did. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Added { + Watched, + /// The listing has `MAX_WATCHES`, or the system wouldn't add it (ENOSPC, or no /proc): it + /// may when watches are let go of. + Failed, + /// For a listing that's been replaced. + Old, } impl Watches { @@ -241,23 +283,43 @@ impl Watches { let _ = inotify::remove_watch(&self.fd, wd); } inner.generation += 1; + inner.freed += 1; inner.generation } /// Watches an open folder for a row of the listing of `generation`, unless a newer listing - /// has started. Added through `/proc/self/fd`, so no name is looked up. False if it isn't - /// watched: past `MAX_WATCHES`, or the system's limit (ENOSPC), or for an old listing. - pub fn add(&self, generation: u64, folder: BorrowedFd<'_>, row: u32) -> bool { - let Ok(mut inner) = self.inner.lock() else { return false }; - if inner.generation != generation || inner.rows.len() >= MAX_WATCHES { - return false; + /// has started. Added through `/proc/self/fd`, so no name is looked up. + pub fn add(&self, generation: u64, folder: BorrowedFd<'_>, row: u32) -> Added { + let Ok(mut inner) = self.inner.lock() else { return Added::Failed }; + if inner.generation != generation { + return Added::Old; + } + #[cfg(test)] + if inner.fail_adds { + return Added::Failed; } - let Ok(wd) = inotify::add_watch(&self.fd, format!("/proc/self/fd/{}", folder.as_raw_fd()), MASK) else { return false }; + if inner.rows.len() >= MAX_WATCHES { + return Added::Failed; + } + let Ok(wd) = inotify::add_watch(&self.fd, format!("/proc/self/fd/{}", folder.as_raw_fd()), MASK) else { return Added::Failed }; let rows = inner.rows.entry(wd).or_default(); if !rows.contains(&row) { rows.push(row); } - true + Added::Watched + } + + /// Goes up each time watches are let go of: a row whose watch failed tries again once it has. + pub fn freed(&self) -> u64 { + self.inner.lock().map_or(0, |i| i.freed) + } + + /// Test seam: makes every add fail, as the system's limit would. + #[cfg(test)] + pub(crate) fn fail_adds(&self, fail: bool) { + if let Ok(mut i) = self.inner.lock() { + i.fail_adds = fail; + } } /// Whether another folder could be watched now. @@ -274,9 +336,12 @@ impl Watches { match reader.next() { Ok(ev) => { let mut take = |ev: &inotify::Event<'_>| { + // A folder deleted, or its disk unmounted, says only that its watch is + // gone (IGNORED): that frees its place, and counts it again. After a + // change, the watch has gone already, and its IGNORED finds nothing. if ev.events().contains(ReadFlags::QUEUE_OVERFLOW) { wds.push(-1); - } else if !ev.events().contains(ReadFlags::IGNORED) { + } else { wds.push(ev.wd()); } }; @@ -299,8 +364,11 @@ impl Watches { // A watch fires once, so it's gone; counting again watches it again. if let Some(rows) = inner.rows.remove(&wd) { out.extend(rows); + inner.freed += 1; } } + out.sort_unstable(); + out.dedup(); out } @@ -343,8 +411,8 @@ mod tests { s.file("f/.b", b""); s.dir("f/sub"); s.dir("empty"); - assert_eq!(count(s.path(), "f"), Some(Count { all: 3, shown: 2 })); - assert_eq!(count(s.path(), "empty"), Some(Count { all: 0, shown: 0 })); + assert_eq!(count(s.path(), "f"), Some(Count::new(3, 2))); + assert_eq!(count(s.path(), "empty"), Some(Count::new(0, 0))); assert_eq!(count(s.path(), "f").unwrap().items(false), 2); assert_eq!(count(s.path(), "f").unwrap().items(true), 3); } @@ -364,7 +432,7 @@ mod tests { for i in 0..CAP + 5 { fs::File::create(big.join(i.to_string())).unwrap(); } - assert_eq!(count(s.path(), "big"), Some(Count { all: CAP + 1, shown: CAP + 1 })); + assert_eq!(count(s.path(), "big"), Some(Count::new(CAP + 1, CAP + 1))); } #[test] @@ -372,7 +440,7 @@ mod tests { let s = Scratch::new(); s.file("real/x", b""); std::os::unix::fs::symlink(s.path().join("real"), s.path().join("link")).unwrap(); - assert_eq!(count(s.path(), "link"), Some(Count { all: 1, shown: 1 })); + assert_eq!(count(s.path(), "link"), Some(Count::new(1, 1))); } fn mount(point: &str, fs_type: &str) -> Mount { @@ -445,13 +513,14 @@ mod tests { for i in 0..30 { fs::File::create(d.join(format!(".{i}"))).unwrap(); } - fs::File::create(d.join("shown")).unwrap(); - let f = fs::File::open(&d).unwrap(); let mut buf = vec![MaybeUninit::uninit(); 4096]; - let fd: OwnedFd = f.into(); - assert_eq!(count_open(&fd, &mut buf, 10), Some(Count { all: CAP + 1, shown: CAP + 1 }), "past the ceiling, it says the cap"); let fd: OwnedFd = fs::File::open(&d).unwrap().into(); - assert_eq!(count_open(&fd, &mut buf, 100), Some(Count { all: 31, shown: 1 })); + let c = count_open(&fd, &mut buf, 10).unwrap(); + assert_eq!(c, Count { all: CAP + 1, shown: 0, more: true }, "past the ceiling: what showed so far, and maybe more"); + assert!((c.items(false), c.more(false)) == (0, true) && (c.items(true), c.more(true)) == (CAP + 1, false), "with hidden ones showing, over the cap"); + fs::File::create(d.join("shown")).unwrap(); + let fd: OwnedFd = fs::File::open(&d).unwrap().into(); + assert_eq!(count_open(&fd, &mut buf, 100), Some(Count::new(31, 1))); } #[test] @@ -462,7 +531,7 @@ mod tests { let g = w.begin(); let d = fs::File::open(s.path()).unwrap(); let mut buf = vec![MaybeUninit::uninit(); 4096]; - count_in(d.as_fd(), c"sub", &mut buf, |f| w.add(g, f, 7)).unwrap(); + count_in(d.as_fd(), c"sub", &mut buf, |f| w.add(g, f, 7) == Added::Watched).unwrap(); assert_eq!(w.drain(), Vec::::new(), "counting isn't a change"); fs::File::create(sub.join("new")).unwrap(); assert_eq!(w.drain(), [7]); @@ -470,6 +539,62 @@ mod tests { assert_eq!(w.drain(), Vec::::new(), "a watch fires once, until counted again"); } + #[test] + fn a_counted_folder_deleted_frees_its_watch_and_counts_again() { + let s = Scratch::new(); + let w = Watches::new().unwrap(); + let g = w.begin(); + let d = fs::File::open(s.path()).unwrap(); + let mut buf = vec![MaybeUninit::uninit(); 4096]; + // More times than there are watches: each deleted folder's place is freed. + for n in 0..MAX_WATCHES as u32 + 10 { + fs::create_dir(s.path().join("gone")).unwrap(); + count_in(d.as_fd(), c"gone", &mut buf, |f| { + assert_eq!(w.add(g, f, n), Added::Watched, "round {n}"); + true + }) + .unwrap(); + fs::remove_dir(s.path().join("gone")).unwrap(); + // The kernel lets go of the folder, and says so, once nothing holds it, which on a + // busy machine can be a moment later. + let end = std::time::Instant::now() + std::time::Duration::from_secs(5); + let mut heard = w.drain(); + while heard.is_empty() && std::time::Instant::now() < end { + std::thread::sleep(std::time::Duration::from_millis(1)); + heard = w.drain(); + } + assert_eq!(heard, [n], "deleted: counted again"); + assert!(w.is_empty()); + } + } + + #[test] + fn a_failed_watch_says_so_and_freeing_one_says_to_try_again() { + let s = Scratch::new(); + s.dir("a"); + let w = Watches::new().unwrap(); + let g = w.begin(); + let d = fs::File::open(s.path()).unwrap(); + let mut buf = vec![MaybeUninit::uninit(); 4096]; + w.fail_adds(true); + count_in(d.as_fd(), c"a", &mut buf, |f| w.add(g, f, 1) == Added::Failed).unwrap(); + w.fail_adds(false); + let before = w.freed(); + count_in(d.as_fd(), c"a", &mut buf, |f| w.add(g, f, 1) == Added::Watched).unwrap(); + assert_eq!(w.freed(), before, "adding frees nothing"); + fs::File::create(s.path().join("a/x")).unwrap(); + assert_eq!(w.drain(), [1]); + assert!(w.freed() > before, "a watch let go of"); + } + + #[test] + fn a_stamp_is_trusted_only_once_its_time_has_settled() { + let st = Stamp { dev: 1, ino: 2, sec: 1000, nsec: 0 }; + assert_eq!(st.taken(1000), None, "just changed: a disk with coarse times could miss the next change"); + assert_eq!(st.taken(1001), None); + assert_eq!(st.taken(1000 + STAMP_SETTLE_SECS), Some(st)); + } + #[test] fn a_new_listing_lets_go_of_the_old_ones_watches() { let s = Scratch::new(); @@ -484,7 +609,7 @@ mod tests { assert!(w.is_empty()); count_in(d.as_fd(), c"sub", &mut buf, |f| { w.add(old, f, 1); true }).unwrap(); assert!(w.is_empty(), "an old listing's thread can't add to the new one"); - count_in(d.as_fd(), c"sub", &mut buf, |f| w.add(new, f, 2)).unwrap(); + count_in(d.as_fd(), c"sub", &mut buf, |f| w.add(new, f, 2) == Added::Watched).unwrap(); fs::File::create(sub.join("x")).unwrap(); assert_eq!(w.drain(), [2]); } diff --git a/crates/core/src/listing.rs b/crates/core/src/listing.rs index f712004..ac1d208 100644 --- a/crates/core/src/listing.rs +++ b/crates/core/src/listing.rs @@ -98,6 +98,9 @@ struct Counted { stale: bool, /// Its folder is watched, so a change in it marks it stale. watched: bool, + /// Its watch couldn't be added, when `Watches::freed` was this: it's tried again only once + /// a watch has been let go of since. + watch_failed: Option, /// Taken from the last listing of this folder: right if the folder's stamp is the same. seeded: bool, /// What the folder was when counted. @@ -303,7 +306,7 @@ impl Listing { Some(st) => { // A folder's count taken from the last listing stands if the folder is as it was. if self.kind(i) == Kind::Dir && self.trash.is_none() { - self.check_seeded(i, Stamp { ino: st.stx_ino, sec: st.stx_mtime.tv_sec, nsec: st.stx_mtime.tv_nsec }); + self.check_seeded(i, Stamp { dev: libc::makedev(st.stx_dev_major, st.stx_dev_minor), ino: st.stx_ino, sec: st.stx_mtime.tv_sec, nsec: st.stx_mtime.tv_nsec }); } // Release pairs with the Acquire in stat(): a reader that sees the size sees the time. m.mtime.store(deleted.unwrap_or(st.stx_mtime.tv_sec), atomic::Ordering::Relaxed); @@ -356,8 +359,15 @@ impl Listing { /// up to `counts::CAP`, or more than that. `None` until it's counted, and for good on a /// network place. pub fn items(&self, i: u32, show_hidden: bool) -> Option { + self.items_more(i, show_hidden).map(|(n, _)| n) + } + + /// As `items`, and whether there may be more than that: a folder of so many hidden entries + /// that reading stopped before the count of those that show was known. + pub fn items_more(&self, i: u32, show_hidden: bool) -> Option<(u32, bool)> { let counts = self.counts.lock().ok()?; - Some(counts.get(&i)?.count?.items(show_hidden)) + let c = counts.get(&i)?.count?; + Some((c.items(show_hidden), c.more(show_hidden))) } /// Whether a row is a folder still to count, or to count again. @@ -366,9 +376,10 @@ impl Listing { } /// Whether a row's count is right but its folder isn't watched, as when it was counted for - /// a sort, or there was no room for a watch: on screen, it's worth watching. - pub fn wants_watch(&self, i: u32) -> bool { - self.kind(i).is_dirlike() && self.counts_folders() && self.counts.lock().is_ok_and(|c| c.get(&i).is_some_and(|c| !c.stale && !c.watched && c.count.is_some())) + /// a sort: on screen, it's worth watching. One whose watch failed waits until `freed`, from + /// `Watches::freed`, says a watch has been let go of since. + pub fn wants_watch(&self, i: u32, freed: u64) -> bool { + self.kind(i).is_dirlike() && self.counts_folders() && self.counts.lock().is_ok_and(|c| c.get(&i).is_some_and(|c| !c.stale && !c.watched && c.count.is_some() && c.watch_failed != Some(freed))) } /// Where rows may be counted: nowhere on a network place. Where the folder really is comes @@ -384,29 +395,38 @@ impl Listing { /// Counts a folder's row if it needs it, or watches it if it needs only that; true if it /// did either. A count is watched for changes with `watch`, for the listing of its - /// generation, before the folder is read, and a folder only being watched is read again only + /// generation, before the folder is read. A folder only being watched, or with a count from + /// the last listing (as a link to a folder's is, whose stat is the link's), is read again only /// if it changed since it was counted. fn count_one(&self, i: u32, buf: &mut Vec>, watch: Option<(&Watches, u64)>) -> bool { let to_count = self.wants_count(i); - if !to_count && !(watch.is_some_and(|(w, _)| w.has_room()) && self.wants_watch(i)) { + if !to_count && !watch.is_some_and(|(w, _)| self.wants_watch(i, w.freed())) { return false; } let Some(fd) = self.fd.as_ref() else { return false }; - let (dirty, known) = self.counts.lock().ok().and_then(|c| c.get(&i).map(|c| (c.dirty, c.stamp))).unwrap_or_default(); + let (dirty, known, seeded) = self.counts.lock().ok().and_then(|c| c.get(&i).map(|c| (c.dirty, c.stamp, c.seeded))).unwrap_or_default(); + let trust = !to_count || seeded; let name = self.name(i); - let (mut watched, mut stamp) = (false, None); + let (mut watched, mut failed, mut stamp) = (false, None, None); let got = if self.policy().allows(name) { if buf.is_empty() { buf.resize(READ_BUFFER, MaybeUninit::uninit()); } CString::new(name).ok().and_then(|n| { counts::count_in(fd.as_fd(), n.as_c_str(), buf, |f| { - watched = watch.is_some_and(|(w, generation)| w.add(generation, f, i)); + if let Some((w, generation)) = watch { + match w.add(generation, f, i) { + counts::Added::Watched => watched = true, + counts::Added::Failed => failed = Some(w.freed()), + counts::Added::Old => {} + } + } stamp = Stamp::of(f); #[cfg(test)] DURING_COUNT.with(|h| if let Some(h) = h.borrow().as_ref() { h(self, i) }); - // Only watching: the count stands if the folder is as it was. - to_count || stamp.is_none() || stamp != known + // Only watching, or counted for the last listing: the count stands if the + // folder is as it was. + !(trust && stamp.is_some() && stamp == known) }) }) } else { @@ -423,6 +443,7 @@ impl Listing { } e.stale = missed; e.watched = watched; + e.watch_failed = failed; e.seeded = false; e.stamp = stamp; true @@ -456,7 +477,13 @@ impl Listing { if start >= dirs.len() { return; } - self.count_entries(&dirs[start..(start + 64).min(dirs.len())], &mut buf, None); + // Checked between folders too, as a big one takes a while to read. + for &i in &dirs[start..(start + 64).min(dirs.len())] { + if cancel.load(atomic::Ordering::Relaxed) { + return; + } + self.count_one(i, &mut buf, None); + } } }); } @@ -471,7 +498,7 @@ impl Listing { return; } let known: HashMap<&[u8], Counted> = match old.counts.lock() { - Ok(c) if !c.is_empty() => c.iter().filter(|(i, c)| (**i as usize) < old.len() && c.count.is_some() && c.stamp.is_some()).map(|(&i, c)| (old.name(i), *c)).collect(), + Ok(c) if !c.is_empty() => c.iter().filter(|(i, c)| (**i as usize) < old.len() && c.count.is_some()).map(|(&i, c)| (old.name(i), *c)).collect(), _ => return, }; if known.is_empty() { @@ -482,7 +509,8 @@ impl Listing { if self.kind(i).is_dirlike() && let Some(c) = known.get(self.name(i)) { - counts.insert(i, Counted { count: c.count, stale: true, watched: false, seeded: true, stamp: c.stamp, dirty: 0 }); + // One with no stamp it can trust is shown, and read again. + counts.insert(i, Counted { count: c.count, stale: true, seeded: c.stamp.is_some(), stamp: c.stamp, ..Counted::default() }); } } } @@ -1711,6 +1739,13 @@ mod tests { last(run(r)) } + /// Sets a folder's modified time well back, so its stamp is trusted at once. Always the same + /// time, so a folder changed and settled again looks unchanged to its stamp. + fn settle(dir: &Path) { + let t = std::time::UNIX_EPOCH + Duration::from_secs(1_000_000_000); + fs::File::open(dir).unwrap().set_modified(t).unwrap(); + } + fn count_now(l: &Listing, name: &str, watch: Option<(&Watches, u64)>) -> bool { let mut buf = Vec::new(); l.count_one(l.find(name.as_bytes()).unwrap(), &mut buf, watch) @@ -1738,16 +1773,18 @@ mod tests { let s = Scratch::new(); s.file("kept/a", b""); s.file("changed/a", b""); + settle(&s.path().join("kept")); + settle(&s.path().join("changed")); let size = SortSpec { key: SortKey::Size, descending: true }; let l = loaded(s.path(), size, None).listing; let (kept, changed) = (l.find(b"kept").unwrap(), l.find(b"changed").unwrap()); - assert!(!l.wants_count(kept) && l.wants_watch(kept), "counted for the sort, not watched"); + assert!(!l.wants_count(kept) && l.wants_watch(kept, 0), "counted for the sort, not watched"); let w = Watches::new().unwrap(); let g = w.begin(); s.file("changed/b", b""); assert!(count_now(&l, "kept", Some((&w, g))) && count_now(&l, "changed", Some((&w, g)))); assert_eq!(w.len(), 2, "both watched now"); - assert!(!l.wants_watch(kept) && !l.wants_count(kept)); + assert!(!l.wants_watch(kept, w.freed()) && !l.wants_count(kept)); assert_eq!((l.items(kept, false), l.items(changed, false)), (Some(1), Some(2)), "the one that changed since is read again"); // A change now is heard. s.file("kept/b", b""); @@ -1759,6 +1796,8 @@ mod tests { let s = Scratch::new(); s.file("same/a", b""); s.file("grew/a", b""); + settle(&s.path().join("same")); + settle(&s.path().join("grew")); let size = SortSpec { key: SortKey::Size, descending: true }; let old = loaded(s.path(), size, None).listing; s.file("grew/b", b""); @@ -1788,6 +1827,8 @@ mod tests { let s = Scratch::new(); s.file("same/a", b""); s.file("grew/a", b""); + settle(&s.path().join("same")); + settle(&s.path().join("grew")); let old = loaded(s.path(), SortSpec::default(), None).listing; let mut buf = Vec::new(); old.count_entries(&(0..old.len() as u32).collect::>(), &mut buf, None); @@ -1804,6 +1845,69 @@ mod tests { assert!(l.wants_count(id("grew")), "changed since: read again"); } + #[test] + fn a_folder_just_changed_has_no_stamp_and_is_read_again() { + let s = Scratch::new(); + s.file("fresh/a", b""); + let old = loaded(s.path(), SortSpec::default(), None).listing; + let mut buf = Vec::new(); + old.count_entries(&(0..old.len() as u32).collect::>(), &mut buf, None); + let mut r = request(s.path()); + r.prior = Some(Prior(old)); + r.row_count = 0; + let l = last(run(r)).listing; + assert_eq!(l.items(0, false), Some(1), "shown from the last listing"); + l.stat_entries(&[0]); + assert!(l.wants_count(0), "but its time was too new to trust, so it's read again"); + } + + #[test] + fn a_link_to_a_folder_keeps_its_count_on_a_reload_without_reading_it() { + let s = Scratch::new(); + s.file("real/a", b""); + settle(&s.path().join("real")); + let here = s.dir("here"); + std::os::unix::fs::symlink("../real", here.join("link")).unwrap(); + let old = loaded(&here, SortSpec::default(), None).listing; + assert!(count_now(&old, "link", None)); + let mut r = request(&here); + r.prior = Some(Prior(old)); + r.row_count = 0; + let l = last(run(r)).listing; + l.stat_all(&AtomicBool::new(false)); + // A file added with the folder's time put back: a read would see it, and the count + // taken on trust from its stamp doesn't. + s.file("real/b", b""); + settle(&s.path().join("real")); + let mut buf = Vec::new(); + assert!(l.count_entries(&[0], &mut buf, None)); + assert_eq!(l.items(0, false), Some(1), "opened to check its stamp, not read"); + assert!(!l.wants_count(0)); + } + + #[test] + fn a_failed_watch_isnt_tried_again_until_one_is_let_go_of() { + let s = Scratch::new(); + s.file("a/x", b""); + s.file("b/x", b""); + settle(&s.path().join("a")); + let l = loaded(s.path(), SortSpec::default(), None).listing; + let w = Watches::new().unwrap(); + let g = w.begin(); + w.fail_adds(true); + assert!(count_now(&l, "a", Some((&w, g)))); + w.fail_adds(false); + let a = l.find(b"a").unwrap(); + assert!(!l.wants_watch(a, w.freed()), "not tried again on every scroll"); + // Another folder's watch goes, which frees a place. + assert!(count_now(&l, "b", Some((&w, g)))); + fs::File::create(s.path().join("b/y")).unwrap(); + assert_eq!(w.drain(), [l.find(b"b").unwrap()]); + assert!(l.wants_watch(a, w.freed()), "tried again now"); + assert!(count_now(&l, "a", Some((&w, g)))); + assert_eq!(w.len(), 1); + } + #[test] fn the_trash_recent_and_search_results_dont_count() { let s = Scratch::new(); diff --git a/tests/e2e.py b/tests/e2e.py index c0ae64a..153189b 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -772,6 +772,14 @@ def a_folders_size_says_how_many_items_it_holds(h): s = a.wait(lambda s: sizes(s) == want, "each folder's count") assert (s["base"] == 0xfafafa) == (theme == "light"), f"{theme}: {s['base']:06x}" a.shot(f"folder-counts-{theme}") + # Renaming the folder beside the wide count: the field stops short of it. + a.type("Every") + a.wait(lambda s: s["cursor"] == s["names"].index(big.name), "on the long name") + a.key("F2") + a.wait(lambda s: s["edit"].startswith("rename:"), "renaming") + a.shot(f"folder-counts-rename-{theme}") + a.key("Escape") + a.wait(lambda s: s["edit"] == "none", "rename put away") if theme == "light": # A change in a folder shown counts it again, by itself. (fs / "one/y.txt").write_text("") From d0eb52ba03be7f8c5767c94892ad16e9bc31a169 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 22:38:44 -0700 Subject: [PATCH 6/8] ALI-2598: Tidy the count's edges: the ceiling, the rename field, stamps - "N+ items" only when an entry follows the 100,000th: a folder of exactly that many is counted whole. - The rename field beside a wide count keeps at least a target's width or four letters, and covers the count while it's open if there's no room beside it. The e2e checks it at 480 px wide and twice the scale. - The 1,024-watch limit counts only new watches, so a link to a folder already watched isn't refused at the limit. - A stamp carries the folder's changed time (ctime) as well, which rsync -t, tar -p and touch -r can't set back, and is trusted once both times are 2 s old. - A count that fails for want of file descriptors, or is interrupted, keeps what it showed and is tried again; no permission or nothing there stays blank. --- README.md | 8 ++- crates/app/src/main.rs | 3 +- crates/app/src/paint.rs | 12 ++-- crates/core/src/counts.rs | 115 ++++++++++++++++++++++++++++--------- crates/core/src/listing.rs | 66 +++++++++++++++------ tests/e2e.py | 18 ++++++ 6 files changed, 171 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index 6c588d5..bd0b0e1 100644 --- a/README.md +++ b/README.md @@ -161,11 +161,15 @@ the rows show, so opening a folder is no slower. Each folder on screen is watche so a change in it counts it again, a moment later; one that keeps changing is counted at most every 2 seconds. Sorting by size counts every folder, fullest first, without watching them; each is watched when it comes on screen, and read again then only if it changed. Reading a folder -again keeps the counts it had and reads again only the folders that changed. A folder of more +again keeps the counts it had and reads again only the folders that changed. A folder counts as +unchanged when its disk, inode, and modified and changed times (mtime and ctime) are as they +were, and both times were at least 2 seconds old when it was counted, for disks that keep times +only to the second; a program can set the modified time back, but not the changed time. A folder of more than 1,024 folders watches the first 1,024 it shows; past that, or past the system's limit on watches, a count isn't kept up to date until there's room for a watch when it's on screen again, or the folder is read again. A count wider than the Size column, as "10,000+ items" is, reaches -to its left, and the name beside it is cut short of it. Folders on network places (SMB, SFTP, FTP, +to its left, and the name beside it is cut short of it; a rename field there keeps room to type, +covering the count if it must. Folders on network places (SMB, SFTP, FTP, NFS, WebDAV and other FUSE mounts), and links that lead into one, aren't counted, as each count would be a round trip, and their Size stays blank. diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 34eeb14..3c01cef 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -890,7 +890,8 @@ mod bench { (0..m.items.len()).map(|i| crate::canvas::Rect::new(r.x, r.y + a.px(gannet_core::tokens::spacing::SPACE_4) + i as i32 * row, r.w, row)).collect() }); format!( - "{{\"large\":{},\"nav\":{},\"crumbs\":{},\"row_h\":{},\"header\":{},\"places\":{},\"ejects\":{},\"closes\":{},\"menu\":{},\"gone\":{}}}", + "{{\"name_field\":{},\"large\":{},\"nav\":{},\"crumbs\":{},\"row_h\":{},\"header\":{},\"places\":{},\"ejects\":{},\"closes\":{},\"menu\":{},\"gone\":{}}}", + a.name_field_rect().map_or_else(|| "null".to_string(), rect), a.large_targets, rects((0..3).map(|i| a.nav_rect(i)).collect()), rects(crumbs), diff --git a/crates/app/src/paint.rs b/crates/app/src/paint.rs index 019e880..6a9765e 100644 --- a/crates/app/src/paint.rs +++ b/crates/app/src/paint.rs @@ -318,7 +318,7 @@ impl App { let offset = (self.scroll - first as f64 * l.row_h as f64) as i32; let y = area.y + (row as i32 - first as i32) * l.row_h - offset; // The width the field was last drawn at, which a wide count beside it narrows. - let w = self.rename_room.map_or(name_max(self), |r| r.min(name_max(self))); + let w = self.rename_room.unwrap_or_else(|| name_max(self).max(self.px(size::TARGET))); Some(Rect::new(name_x - self.px(spacing::SPACE_4), y + 1, w + self.px(spacing::SPACE_8), box_h)) } _ => None, @@ -655,9 +655,13 @@ impl App { { let f = field.clone(); let box_h = (row_h - self.px(spacing::SPACE_2)).max(1); - // As narrow as the name beside a wide count is, so it doesn't cover it. - self.rename_room = Some(row_name_max as i32); - self.paint_field(c, Rect::new(name_x - self.px(spacing::SPACE_4), y + 1, row_name_max as i32 + self.px(spacing::SPACE_8), box_h), &f, true); + // As narrow as the name beside a wide count is, so it doesn't cover it, but never + // narrower than a target or a few letters: with no room beside the count, it + // covers the count while it's open. + let least = (self.px(size::TARGET) as f32).max(self.text.measure("MMMM")); + let room = (row_name_max.max(least) as i32).min(name_max as i32).max(least as i32); + self.rename_room = Some(room); + self.paint_field(c, Rect::new(name_x - self.px(spacing::SPACE_4), y + 1, room + self.px(spacing::SPACE_8), box_h), &f, true); } else { self.text.draw_fitted(c, &shown, name_x as f32, by, row_name_max, if is_cut { dim } else { fg }); } diff --git a/crates/core/src/counts.rs b/crates/core/src/counts.rs index e01bd1b..e4a0138 100644 --- a/crates/core/src/counts.rs +++ b/crates/core/src/counts.rs @@ -64,15 +64,18 @@ pub enum Opened { Kept, } -/// What a folder was when it was counted: its disk, inode and modified time, which changes with -/// any entry added, removed or renamed in it. A folder whose stamp is the same needn't be read -/// again. +/// What a folder was when it was counted: its disk, inode, and modified and changed times, which +/// move with any entry added, removed or renamed in it. The changed time (ctime) is there as a +/// program can set the modified time back (`rsync -t`, `tar -p`, `touch -r`), but not that. A +/// folder whose stamp is the same needn't be read again. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Stamp { pub dev: u64, pub ino: u64, pub sec: i64, pub nsec: u32, + pub ctime_sec: i64, + pub ctime_nsec: u32, } /// How much older than now a folder's modified time must be for its stamp to be trusted. Some @@ -81,15 +84,18 @@ pub struct Stamp { pub const STAMP_SETTLE_SECS: i64 = 2; impl Stamp { - /// The stamp of an open folder, if it can be trusted now. - pub fn of(fd: BorrowedFd<'_>) -> Option { + /// The stamp of an open folder, if it can be trusted now: both its times at least `settle` + /// seconds old, normally `STAMP_SETTLE_SECS`. + pub fn of(fd: BorrowedFd<'_>, settle: i64) -> Option { let st = rustix::fs::fstat(fd).ok()?; - Self::taken(Self { dev: st.st_dev as u64, ino: st.st_ino as u64, sec: st.st_mtime as i64, nsec: st.st_mtime_nsec as u32 }, crate::time::now()) + let stamp = Self { dev: st.st_dev as u64, ino: st.st_ino as u64, sec: st.st_mtime as i64, nsec: st.st_mtime_nsec as u32, ctime_sec: st.st_ctime as i64, ctime_nsec: st.st_ctime_nsec as u32 }; + stamp.taken(crate::time::now(), settle) } - /// The stamp, if its time is old enough at `now` (seconds) to be sure a later change moves it. - pub fn taken(self, now: i64) -> Option { - (now - self.sec >= STAMP_SETTLE_SECS).then_some(self) + /// The stamp, if both its times are at least `settle` seconds old at `now`, to be sure a + /// later change moves them. + pub fn taken(self, now: i64, settle: i64) -> Option { + (now - self.sec.max(self.ctime_sec) >= settle).then_some(self) } } @@ -97,26 +103,37 @@ impl Stamp { /// handed to `opened`, to be watched before it's read, so a change during the count isn't /// missed; it returns false when the folder needn't be read after all. Reading stops once more /// than `CAP` items that aren't hidden are found, or `READ_CEILING` entries are read. -pub fn count_in(dir: BorrowedFd<'_>, name: &CStr, buf: &mut [MaybeUninit], opened: impl FnOnce(BorrowedFd<'_>) -> bool) -> Option { +pub fn count_in(dir: BorrowedFd<'_>, name: &CStr, buf: &mut [MaybeUninit], opened: impl FnOnce(BorrowedFd<'_>) -> bool) -> Result { // O_NONBLOCK and O_DIRECTORY: anything that isn't a folder fails at once, and nothing hangs // opening it. NOFOLLOW isn't set, as a link to a folder is counted as the folder. - let fd = rustix::fs::openat(dir, name, OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NONBLOCK | OFlags::CLOEXEC, Mode::empty()).ok()?; + let fd = rustix::fs::openat(dir, name, OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NONBLOCK | OFlags::CLOEXEC, Mode::empty())?; if !opened(fd.as_fd()) { - return Some(Opened::Kept); + return Ok(Opened::Kept); } count_open(&fd, buf, READ_CEILING).map(Opened::Counted) } -fn count_open(fd: &OwnedFd, buf: &mut [MaybeUninit], ceiling: u32) -> Option { +/// Whether a count that failed this way could work if tried again: out of file descriptors, or +/// interrupted. Anything else, as no permission or nothing there, stays failed. +pub fn transient(e: Errno) -> bool { + matches!(e, Errno::MFILE | Errno::NFILE | Errno::AGAIN | Errno::INTR | Errno::NOMEM) +} + +fn count_open(fd: &OwnedFd, buf: &mut [MaybeUninit], ceiling: u32) -> Result { let mut c = Count::new(0, 0); let mut read = 0; let mut iter = RawDir::new(fd, buf); while let Some(e) = iter.next() { - let e = e.ok()?; + let e = e?; let n = e.file_name().to_bytes(); if n == b"." || n == b".." { continue; } + // So many entries, mostly hidden, that how many show can't be told without reading on, + // and here's one more: at least what's been seen. + if read >= ceiling { + return Ok(Count { all: CAP + 1, shown: c.shown, more: true }); + } read += 1; c.all = c.all.saturating_add(1); if n.first() != Some(&b'.') { @@ -125,14 +142,9 @@ fn count_open(fd: &OwnedFd, buf: &mut [MaybeUninit], ceiling: u32) -> Option break; } } - // So many entries, mostly hidden, that how many show can't be told without reading on: - // at least what's been seen. - if read >= ceiling { - return Some(Count { all: CAP + 1, shown: c.shown, more: true }); - } } c.all = c.all.min(CAP + 1); - Some(c) + Ok(c) } /// Whether folders on this kind of filesystem go uncounted: network shares, where each count @@ -298,10 +310,14 @@ impl Watches { if inner.fail_adds { return Added::Failed; } - if inner.rows.len() >= MAX_WATCHES { + let full = inner.rows.len() >= MAX_WATCHES; + let Ok(wd) = inotify::add_watch(&self.fd, format!("/proc/self/fd/{}", folder.as_raw_fd()), MASK) else { return Added::Failed }; + // A folder already watched, as through a link to it, takes no more room: only a new + // watch counts against the limit. + if full && !inner.rows.contains_key(&wd) { + let _ = inotify::remove_watch(&self.fd, wd); return Added::Failed; } - let Ok(wd) = inotify::add_watch(&self.fd, format!("/proc/self/fd/{}", folder.as_raw_fd()), MASK) else { return Added::Failed }; let rows = inner.rows.entry(wd).or_default(); if !rows.contains(&row) { rows.push(row); @@ -398,7 +414,7 @@ mod tests { fn count(dir: &Path, name: &str) -> Option { let d = fs::File::open(dir).unwrap(); let mut buf = vec![MaybeUninit::uninit(); 32 * 1024]; - match count_in(d.as_fd(), &std::ffi::CString::new(name).unwrap(), &mut buf, |_| true)? { + match count_in(d.as_fd(), &std::ffi::CString::new(name).unwrap(), &mut buf, |_| true).ok()? { Opened::Counted(c) => Some(c), Opened::Kept => None, } @@ -516,11 +532,14 @@ mod tests { let mut buf = vec![MaybeUninit::uninit(); 4096]; let fd: OwnedFd = fs::File::open(&d).unwrap().into(); let c = count_open(&fd, &mut buf, 10).unwrap(); + // Exactly as many as the ceiling: all read, nothing more to guess. + let fd30: OwnedFd = fs::File::open(&d).unwrap().into(); + assert_eq!(count_open(&fd30, &mut buf, 30), Ok(Count::new(30, 0)), "exactly the ceiling isn't \"0+\""); assert_eq!(c, Count { all: CAP + 1, shown: 0, more: true }, "past the ceiling: what showed so far, and maybe more"); assert!((c.items(false), c.more(false)) == (0, true) && (c.items(true), c.more(true)) == (CAP + 1, false), "with hidden ones showing, over the cap"); fs::File::create(d.join("shown")).unwrap(); let fd: OwnedFd = fs::File::open(&d).unwrap().into(); - assert_eq!(count_open(&fd, &mut buf, 100), Some(Count::new(31, 1))); + assert_eq!(count_open(&fd, &mut buf, 100), Ok(Count::new(31, 1))); } #[test] @@ -587,12 +606,52 @@ mod tests { assert!(w.freed() > before, "a watch let go of"); } + #[test] + fn a_folder_already_watched_takes_no_more_room_at_the_limit() { + let s = Scratch::new(); + let w = Watches::new().unwrap(); + let g = w.begin(); + let d = fs::File::open(s.path()).unwrap(); + let mut buf = vec![MaybeUninit::uninit(); 4096]; + for n in 0..MAX_WATCHES as u32 { + let name = std::ffi::CString::new(format!("d{n}")).unwrap(); + fs::create_dir(s.path().join(format!("d{n}"))).unwrap(); + count_in(d.as_fd(), &name, &mut buf, |f| w.add(g, f, n) == Added::Watched).unwrap(); + } + assert_eq!(w.len(), MAX_WATCHES); + // A link to a folder already watched is the same watch. + symlink("d0", s.path().join("link")).unwrap(); + count_in(d.as_fd(), c"link", &mut buf, |f| { + assert_eq!(w.add(g, f, 5000), Added::Watched); + true + }) + .unwrap(); + // A new folder isn't. + fs::create_dir(s.path().join("new")).unwrap(); + count_in(d.as_fd(), c"new", &mut buf, |f| { + assert_eq!(w.add(g, f, 5001), Added::Failed); + true + }) + .unwrap(); + assert_eq!(w.len(), MAX_WATCHES, "and its watch was taken off again"); + } + + #[test] + fn transient_failures_are_told_apart() { + assert!(transient(Errno::MFILE) && transient(Errno::NFILE) && transient(Errno::AGAIN) && transient(Errno::INTR)); + assert!(!transient(Errno::ACCESS) && !transient(Errno::NOENT) && !transient(Errno::NOTDIR)); + } + #[test] fn a_stamp_is_trusted_only_once_its_time_has_settled() { - let st = Stamp { dev: 1, ino: 2, sec: 1000, nsec: 0 }; - assert_eq!(st.taken(1000), None, "just changed: a disk with coarse times could miss the next change"); - assert_eq!(st.taken(1001), None); - assert_eq!(st.taken(1000 + STAMP_SETTLE_SECS), Some(st)); + let st = Stamp { dev: 1, ino: 2, sec: 1000, nsec: 0, ctime_sec: 1000, ctime_nsec: 0 }; + assert_eq!(st.taken(1000, STAMP_SETTLE_SECS), None, "just changed: a disk with coarse times could miss the next change"); + assert_eq!(st.taken(1001, STAMP_SETTLE_SECS), None); + assert_eq!(st.taken(1000 + STAMP_SETTLE_SECS, STAMP_SETTLE_SECS), Some(st)); + // Its modified time set back, as rsync -t does: its changed time still says it's new. + let set_back = Stamp { sec: 10, ..st }; + assert_eq!(set_back.taken(1001, STAMP_SETTLE_SECS), None); + assert_ne!(set_back, Stamp { ctime_sec: 1005, ..set_back }, "and a later change differs, whatever the modified time says"); } #[test] diff --git a/crates/core/src/listing.rs b/crates/core/src/listing.rs index ac1d208..1bed556 100644 --- a/crates/core/src/listing.rs +++ b/crates/core/src/listing.rs @@ -114,10 +114,17 @@ struct Counted { #[cfg(test)] type CountHook = Box; +/// Test seam: folders whose stamps are trusted however new their times are, as a test can't +/// set a folder's changed time back. +#[cfg(test)] +static TRUSTED_AT_ONCE: Mutex> = Mutex::new(Vec::new()); + #[cfg(test)] thread_local! { /// Test seam: runs between a folder being opened and being read, on the thread counting. static DURING_COUNT: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + /// Test seam: how many folders this thread has read to count. + static READS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// What a search found: each row's path, and what was asked. @@ -301,12 +308,12 @@ impl Listing { // In the Trash, the date column is when the item was trashed. let deleted = self.trash.as_ref().and_then(|t| t.info[i as usize].as_ref()).and_then(|inf| inf.deleted); let flags = AtFlags::SYMLINK_NOFOLLOW | AtFlags::NO_AUTOMOUNT; - let got = std::ffi::CString::new(name).ok().and_then(|n| statx(fd.as_fd(), n.as_c_str(), flags, StatxFlags::SIZE | StatxFlags::MTIME | StatxFlags::INO).ok()); + let got = std::ffi::CString::new(name).ok().and_then(|n| statx(fd.as_fd(), n.as_c_str(), flags, StatxFlags::SIZE | StatxFlags::MTIME | StatxFlags::CTIME | StatxFlags::INO).ok()); match got { Some(st) => { // A folder's count taken from the last listing stands if the folder is as it was. if self.kind(i) == Kind::Dir && self.trash.is_none() { - self.check_seeded(i, Stamp { dev: libc::makedev(st.stx_dev_major, st.stx_dev_minor), ino: st.stx_ino, sec: st.stx_mtime.tv_sec, nsec: st.stx_mtime.tv_nsec }); + self.check_seeded(i, Stamp { dev: libc::makedev(st.stx_dev_major, st.stx_dev_minor), ino: st.stx_ino, sec: st.stx_mtime.tv_sec, nsec: st.stx_mtime.tv_nsec, ctime_sec: st.stx_ctime.tv_sec, ctime_nsec: st.stx_ctime.tv_nsec }); } // Release pairs with the Acquire in stat(): a reader that sees the size sees the time. m.mtime.store(deleted.unwrap_or(st.stx_mtime.tv_sec), atomic::Ordering::Relaxed); @@ -393,6 +400,15 @@ impl Listing { }) } + /// How old a folder's times must be for its stamp to be trusted. + fn stamp_settle(&self) -> i64 { + #[cfg(test)] + if TRUSTED_AT_ONCE.lock().is_ok_and(|d| d.iter().any(|d| self.dir.starts_with(d))) { + return 0; + } + counts::STAMP_SETTLE_SECS + } + /// Counts a folder's row if it needs it, or watches it if it needs only that; true if it /// did either. A count is watched for changes with `watch`, for the listing of its /// generation, before the folder is read. A folder only being watched, or with a count from @@ -412,7 +428,7 @@ impl Listing { if buf.is_empty() { buf.resize(READ_BUFFER, MaybeUninit::uninit()); } - CString::new(name).ok().and_then(|n| { + CString::new(name).map_err(|_| rustix::io::Errno::INVAL).and_then(|n| { counts::count_in(fd.as_fd(), n.as_c_str(), buf, |f| { if let Some((w, generation)) = watch { match w.add(generation, f, i) { @@ -421,7 +437,7 @@ impl Listing { counts::Added::Old => {} } } - stamp = Stamp::of(f); + stamp = Stamp::of(f, self.stamp_settle()); #[cfg(test)] DURING_COUNT.with(|h| if let Some(h) = h.borrow().as_ref() { h(self, i) }); // Only watching, or counted for the last listing: the count stands if the @@ -430,18 +446,26 @@ impl Listing { }) }) } else { - None + Err(rustix::io::Errno::PERM) }; let Ok(mut counts) = self.counts.lock() else { return true }; let e = counts.entry(i).or_default(); // Marked to count again while this was reading: the count may have missed that change. let missed = e.dirty != dirty; + // Out of file descriptors, or interrupted: what it showed stays, and it's tried again on + // the next pass. No permission, or nothing there, leaves it blank. + let retry = matches!(got, Err(err) if counts::transient(err)); match got { - Some(counts::Opened::Kept) => {} - Some(counts::Opened::Counted(c)) => e.count = Some(c), - None => e.count = None, + Ok(counts::Opened::Kept) => {} + Ok(counts::Opened::Counted(c)) => { + #[cfg(test)] + READS.with(|r| r.set(r.get() + 1)); + e.count = Some(c); + } + Err(_) if retry => {} + Err(_) => e.count = None, } - e.stale = missed; + e.stale = missed || retry; e.watched = watched; e.watch_failed = failed; e.seeded = false; @@ -1739,9 +1763,11 @@ mod tests { last(run(r)) } - /// Sets a folder's modified time well back, so its stamp is trusted at once. Always the same - /// time, so a folder changed and settled again looks unchanged to its stamp. + /// Makes a folder's stamp trusted at once: the listing of its parent takes it as settled, + /// and its modified time goes back, always to the same time, so a folder changed and settled + /// again looks unchanged by that. fn settle(dir: &Path) { + TRUSTED_AT_ONCE.lock().unwrap().push(dir.parent().unwrap().to_path_buf()); let t = std::time::UNIX_EPOCH + Duration::from_secs(1_000_000_000); fs::File::open(dir).unwrap().set_modified(t).unwrap(); } @@ -1875,14 +1901,22 @@ mod tests { r.row_count = 0; let l = last(run(r)).listing; l.stat_all(&AtomicBool::new(false)); - // A file added with the folder's time put back: a read would see it, and the count - // taken on trust from its stamp doesn't. - s.file("real/b", b""); - settle(&s.path().join("real")); let mut buf = Vec::new(); + let reads = READS.with(|r| r.get()); assert!(l.count_entries(&[0], &mut buf, None)); - assert_eq!(l.items(0, false), Some(1), "opened to check its stamp, not read"); + assert_eq!(READS.with(|r| r.get()), reads, "opened to check its target's stamp, not read"); + assert_eq!(l.items(0, false), Some(1)); assert!(!l.wants_count(0)); + // A file added with the folder's modified time put back, as rsync -t would: its changed + // time still moves, so it's read again. + let mut r = request(&here); + r.prior = Some(Prior(l)); + r.row_count = 0; + let l = last(run(r)).listing; + s.file("real/b", b""); + settle(&s.path().join("real")); + assert!(l.count_entries(&[0], &mut buf, None)); + assert_eq!(l.items(0, false), Some(2), "its changed time gave it away"); } #[test] diff --git a/tests/e2e.py b/tests/e2e.py index 153189b..4b05978 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -798,6 +798,24 @@ def a_folders_size_says_how_many_items_it_holds(h): (fs / "one/y.txt").unlink() (fs / "eight/0.txt").write_text("") else: + # 480 px wide at twice the scale: no room beside the count, so the rename field + # covers it rather than vanish. + try: + a.sway("output * mode 960x800") + a.sway("output * scale 2") + a.wait(lambda s: s["targets"]["row_h"] >= 2 * ROW, "at twice the scale") + a.type("Every") + a.key("F2") + s = a.wait(lambda s: s["edit"].startswith("rename:") and s["targets"]["name_field"], "renaming, narrow") + x, y, w, fh = s["targets"]["name_field"] + assert w >= 2 * 44, s["targets"]["name_field"] + a.shot("folder-counts-rename-narrow-dark") + a.key("Escape") + a.wait(lambda s: s["edit"] == "none", "rename put away") + finally: + a.sway("output * scale 1") + a.sway("output * mode 1280x800") + a.wait(lambda s: s["targets"]["row_h"] == ROW, "back to one") # Opened sorted by size, every folder was counted for the sort, and each on # screen is still watched. assert s["sort"] == "Size", s["sort"] From e4314901d1276f3e84968ce0144f88a027068377 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 22:44:50 -0700 Subject: [PATCH 7/8] ALI-2598: A rename field covering a row's count hides the count while it's open --- crates/app/src/paint.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/app/src/paint.rs b/crates/app/src/paint.rs index 6a9765e..0f2319f 100644 --- a/crates/app/src/paint.rs +++ b/crates/app/src/paint.rs @@ -648,6 +648,8 @@ impl App { c.rrect(Rect::new(bx - pad, by - pad, b + pad * 2, b + pad * 2), b / 2 + pad, row_bg); self.icons.draw(c, crate::icons::Icon::Scissors, bx, by, b, fg); } + // Whether the rename field covers this row's count, which then isn't drawn over it. + let mut covered = false; // Search results can have several rows of one name. if let Edit::Rename { name: editing, field, path, .. } = &self.edit && editing.as_slice() == name @@ -661,6 +663,7 @@ impl App { let least = (self.px(size::TARGET) as f32).max(self.text.measure("MMMM")); let room = (row_name_max.max(least) as i32).min(name_max as i32).max(least as i32); self.rename_room = Some(room); + covered = (name_x + room + self.px(spacing::SPACE_4)) as f32 > size_left; self.paint_field(c, Rect::new(name_x - self.px(spacing::SPACE_4), y + 1, room + self.px(spacing::SPACE_8), box_h), &f, true); } else { self.text.draw_fitted(c, &shown, name_x as f32, by, row_name_max, if is_cut { dim } else { fg }); @@ -671,7 +674,7 @@ impl App { let shown = if listing.search().is_some() { self.search_location(folder) } else { crate::app::home_location(folder, home.as_deref()) }; self.text.draw_fitted(c, &shown, ox as f32, by, ow as f32, dim); } - if !size_text.is_empty() { + if !size_text.is_empty() && !covered { self.text.draw_str(c, &size_text, size_left, by, dim); } match listing.stat(id) { From 41190ab7c2e14c60b72b5e54c524b6a355a6243b Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 22:50:29 -0700 Subject: [PATCH 8/8] ALI-2598: Count folders where the path bar looks, sharing its list of filesystems counts::uncounted now asks complete::avoided_fs, so both avoid the same network, autofs and FUSE (but not fuseblk) mounts, which adds sshfs and afs to what isn't counted. The root is always counted, even as a container's fuse-overlayfs, as the path bar's suggestions treat it. --- crates/core/src/counts.rs | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/crates/core/src/counts.rs b/crates/core/src/counts.rs index e4a0138..57820fc 100644 --- a/crates/core/src/counts.rs +++ b/crates/core/src/counts.rs @@ -147,12 +147,12 @@ fn count_open(fd: &OwnedFd, buf: &mut [MaybeUninit], ceiling: u32) -> Result Ok(c) } -/// Whether folders on this kind of filesystem go uncounted: network shares, where each count -/// is a round trip, and anything through FUSE but a local disk's (`fuseblk`, as ntfs-3g is), -/// as GVfs, sshfs and rclone are all FUSE. An automount point that isn't mounted yet is -/// `autofs`, and counting it would mount it. +/// Whether folders on this kind of filesystem go uncounted: the same ones the path bar's +/// suggestions never look into (`complete::avoided_fs`): network shares, where each count is a +/// round trip, anything through FUSE but a local disk's (`fuseblk`), and autofs, where a look +/// inside mounts a share. pub fn uncounted(fs_type: &str) -> bool { - fs_type == "autofs" || (crate::mounts::inodes_may_change(fs_type) && fs_type != "fuseblk") + crate::complete::avoided_fs(fs_type) } /// Where a folder's rows may be counted: the folder's real path and what's mounted, read once @@ -165,7 +165,7 @@ pub struct Policy { impl Policy { pub fn new(real: Option, mounts: Vec) -> Self { - let real = real.filter(|r| fs_type_of(&mounts, r).is_none_or(|t| !uncounted(t))); + let real = real.filter(|r| counted_in(&mounts, r)); Self { real, mounts } } @@ -179,7 +179,7 @@ impl Policy { } fn counted(&self, path: &Path) -> bool { - fs_type_of(&self.mounts, path).is_none_or(|t| !uncounted(t)) + counted_in(&self.mounts, path) } /// Where `rest` leads from the folder `base`, links followed, or `None` if the way passes @@ -237,10 +237,13 @@ fn push_components(todo: &mut Vec, base: &mut PathBuf, path: &Path) { todo.extend(parts.into_iter().rev()); } -fn fs_type_of<'a>(mounts: &'a [Mount], path: &Path) -> Option<&'a str> { - mounts.iter().filter(|m| path.starts_with(&m.point)).max_by_key(|m| m.point.as_os_str().len()).map(|m| m.fs_type.as_str()) +/// Whether `path` is on a filesystem that's counted. `/` always is, even as a container's +/// fuse-overlayfs root, as the path bar's suggestions treat it. +fn counted_in(mounts: &[Mount], path: &Path) -> bool { + mounts.iter().filter(|m| path.starts_with(&m.point)).max_by_key(|m| m.point.as_os_str().len()).is_none_or(|m| m.point == Path::new("/") || !uncounted(&m.fs_type)) } + /// How many folders one listing watches at most. Scrolling through a folder of more folders /// than this still counts each, but those past it aren't kept up to date until they're on screen /// again with room for a watch, or the folder is read again. @@ -489,6 +492,9 @@ mod tests { assert!(Policy::new(Some(root.join("win")), mounts.clone()).allows(b"x"), "a local disk through FUSE"); assert!(!Policy::new(Some(root.clone()), mounts.clone()).allows(b"auto"), "an automount that isn't mounted yet"); assert!(!Policy::new(None, mounts).allows(b"x"), "a folder with no real path"); + // The same kinds the path bar's suggestions avoid, and never the root. + assert!(uncounted("sshfs") && uncounted("afs") && uncounted("fuse.rclone") && !uncounted("fuseblk") && !uncounted("ext4")); + assert!(Policy::new(Some(root.join("home")), vec![mount("/", "fuse.fuse-overlayfs")]).allows(b"Documents"), "a container's root through FUSE is still counted"); } #[test]