diff --git a/README.md b/README.md index b19f1d4..8a43533 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,26 @@ 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. 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 +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 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; 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. + ## 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 2eeced5..377f094 100644 --- a/crates/app/src/a11y.rs +++ b/crates/app/src/a11y.rs @@ -334,6 +334,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. @@ -382,7 +384,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 } } @@ -413,14 +415,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(), @@ -849,7 +851,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 acbd218..7681e27 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -59,6 +59,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; +/// 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; @@ -91,7 +100,8 @@ pub enum Msg { /// The folders in a parent typed in the path bar: the answer to `App::list_folders`. PathFolders(Box), 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. @@ -828,8 +838,23 @@ 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 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, + /// 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, @@ -873,6 +898,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 @@ -1037,7 +1064,13 @@ impl App { mods_now: Mods::default(), has_keyboard: false, watch: None, + counts: None, + recount_at: None, + 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, @@ -1273,11 +1306,17 @@ 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)); self.selected = vec![0; c.listing.len().div_ceil(64)]; + // 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(); @@ -1326,6 +1365,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(); @@ -1350,6 +1392,16 @@ 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) { + 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(); + } self.band_on_timer(now); self.side_scroll_on_timer(now); self.preview_on_timer(now); @@ -1369,7 +1421,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) { @@ -1417,6 +1469,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; @@ -1480,12 +1533,13 @@ 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 { self.remember(l.listing, l.sort); } - self.clamp_scroll(); self.stats_range = (0, 0); self.request_stats(); self.invalidate_all(); @@ -1502,7 +1556,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; @@ -1515,7 +1569,13 @@ 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())); + // 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); } @@ -1559,14 +1619,14 @@ 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), 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() { @@ -1703,11 +1763,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); } @@ -1885,19 +1948,47 @@ 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. 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 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 = self.recount_due.values().min().copied(); + } + + /// 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 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); } @@ -2431,7 +2522,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(); @@ -2931,6 +3023,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) { @@ -13364,6 +13457,183 @@ 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"]); + } + + /// 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"); + 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 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"); + 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}; @@ -13371,7 +13641,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"); @@ -13381,16 +13651,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..2197391 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,42 @@ 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. With `more`, reading stopped first, so it's at least `n`: `3+ items`. +pub fn items(n: u32, more: bool) -> String { + match n { + 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"), + } +} + +/// 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_more(id, show_hidden).map(|(n, more)| items(n, more)).unwrap_or_default(); + } + match l.stat(id) { + Stat::Known { size: bytes, .. } => size(bytes), + _ => String::new(), + } } #[cfg(test)] @@ -56,4 +87,19 @@ 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, 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/main.rs b/crates/app/src/main.rs index e4084c7..7fa54e7 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -246,6 +246,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())); @@ -459,6 +461,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 @@ -477,6 +483,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); @@ -505,6 +512,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(); } @@ -743,6 +753,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 { @@ -762,6 +774,7 @@ mod bench { loads_stamped: 0, search_stamped: None, thumbs_stamped: (0, 0), + counts_stamped: (0, 0), } } @@ -781,6 +794,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(); @@ -866,7 +891,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), @@ -890,11 +916,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\":{},\"menu_off\":{},\"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\":{},\"format\":{},\"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\":{},\"menu_off\":{},\"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\":{},\"format\":{},\"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 481b478..59563e8 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}; @@ -318,7 +318,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.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, } @@ -627,6 +629,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); @@ -641,6 +649,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 @@ -648,9 +658,16 @@ 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, 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); + 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, 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) @@ -658,13 +675,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() && !covered { + 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/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 new file mode 100644 index 0000000..57820fc --- /dev/null +++ b/crates/core/src/counts.rs @@ -0,0 +1,681 @@ +//! 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, OsStr, OsString}; +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, + /// 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, 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. +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 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 +/// 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: 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()?; + 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 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) + } +} + +/// 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; 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) -> 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())?; + if !opened(fd.as_fd()) { + return Ok(Opened::Kept); + } + count_open(&fd, buf, READ_CEILING).map(Opened::Counted) +} + +/// 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?; + 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'.') { + c.shown += 1; + if c.shown > CAP { + break; + } + } + } + c.all = c.all.min(CAP + 1); + Ok(c) +} + +/// 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 { + 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 +/// 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| counted_in(&mounts, r)); + Self { real, mounts } + } + + /// 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 }; + self.resolve(real.clone(), Path::new(OsStr::from_bytes(name))).is_some() + } + + fn counted(&self, path: &Path) -> bool { + counted_in(&self.mounts, path) + } + + /// 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) + } +} + +/// 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::RootDir => { + *base = PathBuf::from("/"); + parts.clear(); + } + Component::Normal(n) => parts.push(n.to_os_string()), + Component::ParentDir => parts.push(OsString::from("..")), + Component::CurDir | Component::Prefix(_) => {} + } + } + todo.extend(parts.into_iter().rev()); +} + +/// 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. +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 +/// 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>, + /// 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 { + 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.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. + 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 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 rows = inner.rows.entry(wd).or_default(); + if !rows.contains(&row) { + rows.push(row); + } + 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. + 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. + 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<'_>| { + // 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 { + 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); + inner.freed += 1; + } + } + out.sort_unstable(); + out.dedup(); + 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; + 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]; + match count_in(d.as_fd(), &std::ffi::CString::new(name).unwrap(), &mut buf, |_| true).ok()? { + Opened::Counted(c) => Some(c), + Opened::Kept => None, + } + } + + #[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::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); + } + + #[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::new(CAP + 1, 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::new(1, 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 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"); + // 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] + 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(); + } + 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), Ok(Count::new(31, 1))); + } + + #[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) == 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]); + fs::File::create(sub.join("newer")).unwrap(); + 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_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, 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] + 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); 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); 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) == Added::Watched).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 360aac5..fb65ea0 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -9,6 +9,7 @@ pub mod bus; pub mod cli; pub mod clipboard; pub mod complete; +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..1bed556 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, Stamp, Watches}; use crate::mounts::read_mounts; use crate::sort::{natural_cmp, par_sort_by}; use crate::trash::{self, Info, Root, Trashed}; @@ -81,6 +83,48 @@ 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, Default)] +struct Counted { + count: Option, + 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. + 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; + +/// 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. @@ -264,9 +308,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::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, 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); m.size.store(st.stx_size, atomic::Ordering::Release); @@ -308,6 +356,224 @@ 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 { + 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()?; + 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. + 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)) + } + + /// Whether a row's count is right but its folder isn't watched, as when it was counted for + /// 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 + /// 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) + }) + } + + /// 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 + /// 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, _)| self.wants_watch(i, w.freed())) { + return false; + } + let Some(fd) = self.fd.as_ref() else { return false }; + 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 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).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) { + counts::Added::Watched => watched = true, + counts::Added::Failed => failed = Some(w.freed()), + counts::Added::Old => {} + } + } + 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 + // folder is as it was. + !(trust && stamp.is_some() && stamp == known) + }) + }) + } else { + 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 { + 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 || retry; + e.watched = watched; + e.watch_failed = failed; + e.seeded = false; + e.stamp = stamp; + 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 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; + } + 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; + } + // 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); + } + } + }); + } + }); + } + + /// 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], 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()).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 0..self.len() as u32 { + if self.kind(i).is_dirlike() + && let Some(c) = known.get(self.name(i)) + { + // 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() }); + } + } + } + + /// 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. 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) => ids.iter().for_each(|&i| mark(counts.entry(i).or_default())), + None => counts.values_mut().for_each(mark), + } + } + fn snapshot(&self) -> Listing { Listing { dir: self.dir.clone(), @@ -321,6 +587,8 @@ impl Listing { trash: self.trash.clone(), recent: self.recent.clone(), search: self.search.clone(), + counts: Default::default(), + policy: OnceLock::new(), } } } @@ -355,21 +623,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 +655,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 }; @@ -461,11 +736,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`. @@ -606,7 +893,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); @@ -669,6 +956,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); } @@ -752,7 +1042,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 +1119,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 +1223,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 +1318,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 +1340,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 +1398,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, @@ -1115,11 +1419,23 @@ impl Stater { Err(_) => return, }, }; - for chunk in ids.chunks(64) { - if listing.stat_entries(chunk) { + '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; @@ -1156,7 +1472,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. @@ -1392,6 +1708,248 @@ 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"); + } + + 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)) + } + + /// 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(); + } + + 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""); + 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, 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, 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""); + 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""); + 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""); + 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""); + 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); + 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 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)); + let mut buf = Vec::new(); + let reads = READS.with(|r| r.get()); + assert!(l.count_entries(&[0], &mut buf, None)); + 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] + 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(); + 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/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/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/tests/e2e.py b/tests/e2e.py index 4721f82..f7369f8 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -847,6 +847,85 @@ 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}") + # 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("") + 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("") + 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"] + (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) + + @check def theme_follows_swaps_and_works_without_any(h): fs = fresh_fs() @@ -2717,10 +2796,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.