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