app: a trail from /, and typeahead filtering

- The trail always starts at /. Directories above the scanned root are
  dimmer; clicking one widens the scan to there, reusing the tree already
  measured, with the current view kept until the wider tree lands. g goes
  to the whole disk. The Home | Whole disk switch is gone.
- / filters: as you type, only matches keep their colour (the directories
  holding them step back less); Enter lays out only the matches at their
  size, with the largest selected; Escape clears. The search runs off the
  UI thread, newest keystroke wins, and an early Enter applies on arrival.
This commit is contained in:
Tobi Lutke
2026-09-24 16:51:31 -05:00
parent 23b9e5d21b
commit c11c86f50f
6 changed files with 515 additions and 167 deletions
+15 -7
View File
@@ -51,8 +51,9 @@ disktree --help # options: apparent size, follow links, skip hidden, …
- **Top:** the scan totals, then what is measured — **Size**, **Files** or
**Age**, **Hidden files**, **Apparent size**, and the depth drawn.
- **Trail:** the path as a clickable trail, and the
legend.
- **Trail:** the path from `/`, and the legend. Everything below the scanned
root is a place to go; everything above it is dimmer, and clicking it
widens the scan to there (see below).
- **Mosaic:** colour is the *kind* of data — code, agent scratch,
toolchains, synced files, git, media, documents, caches — at one muted
level, lighter with depth. A diagonal hatch is space that can be had back
@@ -120,13 +121,13 @@ and shows how much free space was actually gained.
| `[` `]` | draw fewer or more levels at once |
| `-` `=` `0` | magnify, shrink, reset the view |
| `ctrl =` `ctrl -` `ctrl 0` | interface zoom |
| `/` | find an entry by name |
| `/` | filter by name: only matches keep their colour; `enter` shows only them, `esc` clears |
| `c` | review the marked list |
| `t` | rank by size or by file count |
| `d` | disk usage or apparent size |
| `i` | include or skip hidden entries |
| `r` | scan again |
| `g` | home directory or the whole disk |
| `g` | the whole disk |
| `p` | show or hide the selection line |
| `?` | every key |
| `q` | quit |
@@ -150,9 +151,16 @@ and removes duplicate hardlinks.
## The whole disk
**~ Home | / Whole disk** in the top bar, `g`, `disktree --disk`, or
the launcher's *Scan the whole disk* action scans the disk your home
directory lives on — `/` on Omarchy.
Click `/` (or any directory above the scanned root) in the trail, press
`g`, run `disktree --disk`, or use the launcher's *Scan the whole disk*
action. `g` and `--disk` scan the disk your home directory lives on — `/`
on Omarchy.
Widening is memoized: the tree already measured is handed to the wider walk
and reused where it is reached, so going from `~` to `/` reads only what is
outside `~` (on this machine, seconds instead of a full rescan). The current
view stays on screen until the wider tree lands, which then opens with the
directory you came from selected. Going back down is just navigation.
A scan stays on one volume, and a volume is the mount *source*, not the
device number: btrfs gives each subvolume its own `st_dev`, so `/home`,
+2
View File
@@ -186,6 +186,8 @@ fn parse_args() -> Result<Args> {
};
// Store the depth as the initial view setting rather than a scan option: it
// is a display choice the run-time `[` and `]` keys also change.
// Canonical, so a later widening recognises this tree in the wider walk.
let root = root.canonicalize().unwrap_or(root);
let metadata = std::fs::metadata(&root)
.with_context(|| format!("cannot read {}", root.display()))?;
anyhow::ensure!(metadata.is_dir(), "{} is not a directory", root.display());
+260 -69
View File
@@ -7,20 +7,22 @@
use std::cell::Cell;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};
use disktree_core::filter::{Keep, Matches, filter};
use disktree_core::insights::{Candidate, worth_a_look};
use disktree_core::removal::{
Plan, RemovalEvent, RemovalHandle, RemovalMode, Target, TrashBackend,
detect_trash_backend, plan,
};
use disktree_core::scan::{ScanHandle, ScanOptions, ScanSnapshot};
use disktree_core::scan::{Known, ScanHandle, ScanOptions, ScanSnapshot};
use disktree_core::space::{
SpaceInfo, device_for, space_info, volume_root_for,
};
use disktree_core::tree::{Metric, Node, path_of};
use disktree_core::treemap::{
LayoutOptions, Rect, Tile, TileKind, hit, layout,
LayoutOptions, Rect, Tile, TileKind, hit, layout_filtered,
};
use gpui_kit::{
Context, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent,
@@ -45,13 +47,14 @@ pub enum ColorMode {
Age,
}
/// What is scanned, as the trail's switch names it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Scope {
/// The home directory.
Home,
/// The whole disk the home directory lives on.
Disk,
/// One step of the trail.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Crumb {
/// A directory above the scanned root: going there scans only what is
/// new at that level.
Above(PathBuf),
/// A directory in the tree, by crumbs from the scanned root.
Tree(Vec<usize>),
}
/// The side panel's width in rem: default and limits. In rem, so interface
@@ -265,6 +268,8 @@ struct LayoutKey {
width: f32,
height: f32,
options: LayoutOptions,
/// Bumped whenever the applied filter changes.
filter: u64,
}
/// Result of the removal run, summarised for the final screen.
@@ -282,7 +287,7 @@ pub struct Disktree {
pub root_path: PathBuf,
pub home: Option<PathBuf>,
pub options: ScanOptions,
pub tree: Option<Rc<Node>>,
pub tree: Option<Arc<Node>>,
pub scan: Option<ScanHandle>,
pub scan_epoch: u64,
pub progress: ScanSnapshot,
@@ -336,6 +341,18 @@ pub struct Disktree {
pub find: String,
pub find_open: bool,
/// What the find text matches in the directory on screen, recomputed
/// on every keystroke. While typing it only dims what does not match.
pub matches: Option<Arc<Matches>>,
/// Enter was pressed: the mosaic lays out only the matches.
pub filter_applied: bool,
filter_epoch: u64,
/// Bumped per keystroke; only the newest search's result is kept.
find_epoch: u64,
/// A search is running off the UI thread.
pub finding: bool,
/// Enter was pressed before the search finished: apply on arrival.
apply_pending: bool,
pub show_help: bool,
pub show_selection: bool,
pub focus: FocusHandle,
@@ -355,6 +372,9 @@ pub struct Disktree {
/// The side panel's width, in rem; dragged from its left edge.
pub panel_rems: f32,
pub scan_started: Option<Instant>,
/// Where the scan in flight is rooted. Differs from `root_path` while
/// widening, when the old tree stays on screen until the wider one lands.
pub scan_root: PathBuf,
pub scan_elapsed: Option<Duration>,
/// Unix seconds when the tree landed: the "now" ages are measured from.
pub scanned_at: i64,
@@ -416,6 +436,12 @@ impl Disktree {
notice: None,
find: String::new(),
find_open: false,
matches: None,
filter_applied: false,
filter_epoch: 0,
find_epoch: 0,
finding: false,
apply_pending: false,
show_help: false,
show_selection: true,
focus: cx.focus_handle(),
@@ -427,6 +453,7 @@ impl Disktree {
disk_root: None,
panel_rems: PANEL_REMS,
scan_started: None,
scan_root: PathBuf::new(),
scan_elapsed: None,
scanned_at: now_seconds(),
};
@@ -456,31 +483,16 @@ impl Disktree {
) -> Self {
let mut app = Self::new(root_path, options, depth, cx);
app.marks.refresh(&app.root_path, &tree, app.options.metric);
app.tree = Some(Rc::new(tree));
app.tree = Some(Arc::new(tree));
app.cache = None;
app.refresh_insights();
app.select_largest(cx);
app
}
/// Which scope the current root is, if it is one of the two.
pub fn scope(&self) -> Option<Scope> {
if self.home.as_deref() == Some(self.root_path.as_path()) {
Some(Scope::Home)
} else if self.disk_root.as_deref() == Some(self.root_path.as_path()) {
Some(Scope::Disk)
} else {
None
}
}
/// Scan a different root: the home directory, the whole disk, or any
/// directory. Marks are kept; a mark outside the new root is shown as
/// kept back, never removed.
/// Scan a different root from scratch. Marks are kept; a mark outside
/// the new root is shown as kept back, never removed.
pub fn set_root(&mut self, root: PathBuf, cx: &mut Context<'_, Self>) {
if root == self.root_path && self.tree.is_some() {
return;
}
self.space = space_info(&root).ok();
self.device = device_for(&root);
self.root_path = root;
@@ -488,14 +500,52 @@ impl Disktree {
self.start_scan(cx);
}
/// Switch to a scope.
pub fn set_scope(&mut self, scope: Scope, cx: &mut Context<'_, Self>) {
let root = match scope {
Scope::Home => self.home.clone(),
Scope::Disk => self.disk_root.clone(),
/// Go up to `above`, a directory containing the scanned root.
///
/// Memoized: the tree already measured is handed to the walk and reused
/// where it is reached, so only what is new at the wider level is read,
/// and the current view stays on screen until the wider tree lands.
pub fn widen_to(&mut self, above: PathBuf, cx: &mut Context<'_, Self>) {
let Some(tree) = self.tree.clone() else {
self.set_root(above, cx);
return;
};
if let Some(root) = root {
self.set_root(root, cx);
if !self.root_path.starts_with(&above) || self.root_path == above {
return;
}
if let Some(scan) = &self.scan {
scan.cancel();
}
self.scan_epoch += 1;
let epoch = self.scan_epoch;
self.progress = ScanSnapshot::default();
self.scan_error = None;
self.scan_started = Some(Instant::now());
self.scan_elapsed = None;
self.scan_root.clone_from(&above);
let known = Known {
path: self.root_path.clone(),
tree,
};
self.scan = Some(ScanHandle::spawn_with(
above,
self.options.clone(),
Some(known),
));
Self::poll_scan(epoch, cx);
cx.notify();
}
/// `g`: the whole disk. Widens when the disk is above the scanned root,
/// and goes to its top when it already is the root.
pub fn go_to_disk(&mut self, cx: &mut Context<'_, Self>) {
let Some(disk) = self.disk_root.clone() else {
return;
};
if disk == self.root_path {
self.go_to(Vec::new(), cx);
} else {
self.widen_to(disk, cx);
}
}
@@ -562,8 +612,10 @@ impl Disktree {
self.cache = None;
self.insights.clear();
self.git.clear();
self.clear_filter();
self.scan_started = Some(Instant::now());
self.scan_elapsed = None;
self.scan_root.clone_from(&self.root_path);
self.scan = Some(ScanHandle::spawn(
self.root_path.clone(),
self.options.clone(),
@@ -610,13 +662,33 @@ impl Disktree {
};
match outcome {
Ok(node) => {
// A widening scan lands on a new root: move the view up to it,
// with the directory it came from selected.
let came_from = (self.scan_root != self.root_path)
.then(|| self.root_path.clone());
if came_from.is_some() {
self.clear_filter();
self.root_path.clone_from(&self.scan_root);
self.space = space_info(&self.root_path).ok();
self.device = device_for(&self.root_path);
}
let metric = self.options.metric;
self.marks.refresh(&self.root_path, &node, metric);
self.tree = Some(Rc::new(node));
self.tree = Some(Arc::new(node));
self.cache = None;
self.refresh_insights();
self.scan_elapsed =
self.scan_started.map(|started| started.elapsed());
if let Some(from) = came_from {
let crumbs = self.crumbs_for_path(&from);
self.crumbs.clear();
self.view = View::default();
self.transition = None;
self.forget_hover();
self.selected = crumbs.and_then(|crumbs| {
crumbs.first().map(|&top| vec![top])
});
}
self.keep_selection_valid();
self.select_largest(cx);
}
@@ -704,11 +776,19 @@ impl Disktree {
}
/// Breadcrumb labels from the scanned root to the current directory.
pub fn breadcrumbs(&self) -> Vec<(String, Vec<usize>)> {
let mut trail = vec![(
display_path(&self.root_path, self.home.as_deref()),
Vec::new(),
)];
/// The trail, from `/`: the directories above the scanned root, which
/// widen the scan, then the root and the path into the tree.
pub fn breadcrumbs(&self) -> Vec<(String, Crumb)> {
let mut trail: Vec<(String, Crumb)> = self
.root_path
.ancestors()
.skip(1)
.collect::<Vec<_>>()
.into_iter()
.rev()
.map(|path| (crumb_label(path), Crumb::Above(path.to_path_buf())))
.collect();
trail.push((crumb_label(&self.root_path), Crumb::Tree(Vec::new())));
let Some(tree) = &self.tree else {
return trail;
};
@@ -720,7 +800,7 @@ impl Disktree {
break;
};
crumbs.push(index);
trail.push((node.name.to_string(), crumbs.clone()));
trail.push((node.name.to_string(), Crumb::Tree(crumbs.clone())));
}
trail
}
@@ -1157,6 +1237,12 @@ impl Disktree {
(now - node.map_or(now, |n| n.modified)) / 86_400;
crate::palette::age_bucket(days)
});
let filtered = match self.matches.as_deref().map(|m| m.keep(crumbs))
{
None | Some(Some(Keep::Whole)) => Filtered::Shown,
Some(Some(Keep::Partial { .. })) => Filtered::Holds,
Some(None) => Filtered::Out,
};
let is_marked = marked.contains(crumbs);
let is_covered = covered.contains(crumbs);
decorations.push(TileDeco {
@@ -1165,6 +1251,7 @@ impl Disktree {
category,
age_bucket,
reclaimable: node.is_some_and(|n| n.reclaim.is_some()),
filtered,
unreadable: node.is_some_and(|n| n.read_error),
marked: is_marked,
covered: is_covered,
@@ -1196,6 +1283,7 @@ impl Disktree {
.header
.map(|header| self.animated_rect(header)),
depth: tile.depth,
dim: filtered == Filtered::Out,
marked: is_marked || is_covered,
size_text: crate::widgets::short_value(node, metric),
});
@@ -1205,6 +1293,7 @@ impl Disktree {
rect: self.animated_rect(tile.rect),
header: None,
depth: tile.depth,
dim: self.matches.is_some(),
marked: false,
size_text: String::new(),
}),
@@ -1255,12 +1344,22 @@ impl Disktree {
// relationship to the label inside it.
self.layout_options.header = HEADER_REMS * self.rem;
self.layout_options.header_inner = HEADER_INNER_REMS * self.rem;
// A filter is about the directory it was typed in: above it, it
// would hide everything beside that directory, so it lapses.
if self
.matches
.as_ref()
.is_some_and(|matches| !self.crumbs.starts_with(&matches.base))
{
self.clear_filter();
}
let area = self.treemap_size.get();
let key = LayoutKey {
crumbs: self.crumbs.clone(),
width: area.width.as_f32().round(),
height: area.height.as_f32().round(),
options: self.layout_options.clone(),
filter: self.filter_epoch,
};
if key.width < 1.0 || key.height < 1.0 {
return None;
@@ -1270,12 +1369,15 @@ impl Disktree {
let tree = self.tree.clone()?;
let node = tree.resolve(&self.crumbs)?;
let rect = Rect::new(0.0, 0.0, key.width, key.height);
let tiles = layout(
let filter =
self.matches.as_deref().filter(|_| self.filter_applied);
let tiles = layout_filtered(
node,
&key.crumbs,
rect,
self.options.metric,
&key.options,
filter,
);
self.cache = Some(LayoutCache { key, tiles });
}
@@ -1372,7 +1474,7 @@ impl Disktree {
if let Some(tree) = &self.tree {
let mut tree = (**tree).clone();
disktree_core::tree::aggregate(&mut tree, self.options.metric);
self.tree = Some(Rc::new(tree));
self.tree = Some(Arc::new(tree));
let metric = self.options.metric;
self.marks.refresh(
&self.root_path,
@@ -1382,6 +1484,7 @@ impl Disktree {
}
// Children are ordered by the metric, so every crumb moved.
self.refresh_insights();
self.clear_filter();
self.cache = None;
cx.notify();
}
@@ -1579,22 +1682,98 @@ impl Disktree {
}
/// Descend to a path found by the search field.
pub fn jump_to_match(&mut self, cx: &mut Context<'_, Self>) {
let needle = self.find.trim().to_lowercase();
if needle.is_empty() {
/// Recompute what the find text matches in the directory on screen.
///
/// Off the UI thread: a whole disk is millions of names, a few hundred
/// milliseconds to search, and typing must not wait for it. Each
/// keystroke supersedes the search before it.
pub fn refresh_matches(&mut self, cx: &Context<'_, Self>) {
self.find_epoch += 1;
let epoch = self.find_epoch;
let needle = self.find.clone();
let Some(tree) =
self.tree.clone().filter(|_| !needle.trim().is_empty())
else {
self.matches = None;
self.filter_applied = false;
self.finding = false;
self.filter_epoch += 1;
return;
};
self.finding = true;
let base = self.crumbs.clone();
let task = cx.background_executor().spawn(async move {
tree.resolve(&base)
.and_then(|node| filter(node, &base, &needle))
});
cx.spawn(async move |this, cx| {
let found = task.await;
let _ = this.update(cx, |this, cx| {
if epoch != this.find_epoch {
return;
}
this.finding = false;
this.matches = found.map(Arc::new);
this.filter_epoch += 1;
if std::mem::take(&mut this.apply_pending) {
this.apply_filter(cx);
}
cx.notify();
});
})
.detach();
}
/// Enter in the find field: lay out only the matches, with the largest
/// selected so Space marks it.
pub fn apply_filter(&mut self, cx: &mut Context<'_, Self>) {
self.find_open = false;
if self.finding {
self.apply_pending = true;
return;
}
let Some(tree) = self.tree.clone() else {
let Some(matches) = self.matches.clone() else {
return;
};
let Some((crumbs, _)) = tree.find(&needle) else {
self.notice =
Some((format!("no entry matches {needle}"), Status::Warning));
if matches.count == 0 {
self.notice = Some((
format!("nothing here matches {}", matches.needle),
Status::Warning,
));
cx.notify();
return;
};
self.reveal(crumbs, cx);
}
self.filter_applied = true;
self.filter_epoch += 1;
self.view = View::IDENTITY;
self.transition = None;
self.forget_hover();
self.pointer_active = false;
let tree = self.tree.clone();
self.selected = matches
.keep
.iter()
.filter(|(_, keep)| **keep == Keep::Whole)
.filter_map(|(crumbs, _)| {
let node = tree.as_deref()?.resolve(crumbs)?;
Some((node.bytes, crumbs))
})
.max_by_key(|(bytes, _)| *bytes)
.map(|(_, crumbs)| crumbs.clone());
self.notice = None;
cx.notify();
}
/// Drop the find text and the filter with it.
pub fn clear_filter(&mut self) {
self.find_epoch += 1;
self.finding = false;
self.apply_pending = false;
self.find.clear();
self.find_open = false;
self.matches = None;
self.filter_applied = false;
self.filter_epoch += 1;
}
// ── input ───────────────────────────────────────────────────────────
@@ -1641,16 +1820,11 @@ impl Disktree {
// tree, and Escape always means "give the keyboard back".
if self.screen == Screen::Explore && self.find_open {
match key {
"escape" => {
self.find_open = false;
self.find.clear();
}
"enter" => {
self.find_open = false;
self.jump_to_match(cx);
}
"escape" => self.clear_filter(),
"enter" => self.apply_filter(cx),
"backspace" => {
self.find.pop();
self.refresh_matches(cx);
}
_ => {
// Some platforms report only `key` for a character and
@@ -1663,6 +1837,7 @@ impl Disktree {
.unwrap_or(event.keystroke.key.as_str());
if !control && typed.chars().count() == 1 {
self.find.push_str(typed);
self.refresh_matches(cx);
}
}
}
@@ -1737,6 +1912,8 @@ impl Disktree {
self.move_selection(Direction::Down, cx);
}
"backspace" | "u" if !control => self.ascend(cx),
// A filter is the first thing Escape takes away.
"escape" if self.matches.is_some() => self.clear_filter(),
"escape" => {
if self.selected.is_some() {
self.selected = None;
@@ -1785,14 +1962,7 @@ impl Disktree {
self.set_mode((self.mode_index() + 1) % 3, cx);
}
"r" if !control => self.start_scan(cx),
"g" if !control => {
let next = if self.scope() == Some(Scope::Disk) {
Scope::Home
} else {
Scope::Disk
};
self.set_scope(next, cx);
}
"g" if !control => self.go_to_disk(cx),
"i" if !control => {
self.options.include_hidden = !self.options.include_hidden;
self.start_scan(cx);
@@ -2057,6 +2227,8 @@ pub struct Label {
pub header: Option<Rect>,
/// Nesting depth in this view: the first level is set in bold.
pub depth: u32,
/// Filtered out while typing: drawn quietly.
pub dim: bool,
pub marked: bool,
pub size_text: String,
}
@@ -2070,6 +2242,14 @@ const HEADER_REMS: f32 = 1.375;
/// Height of the slim label row a deeper open directory keeps, in rem.
const HEADER_INNER_REMS: f32 = 1.0;
/// A trail step's label: the directory's own name, or `/` for the root.
fn crumb_label(path: &Path) -> String {
path.file_name().map_or_else(
|| path.display().to_string(),
|name| name.to_string_lossy().into_owned(),
)
}
/// Now, in Unix seconds.
pub fn now_seconds() -> i64 {
std::time::SystemTime::now()
@@ -2083,6 +2263,17 @@ pub fn now_seconds() -> i64 {
const LABEL_MIN_W_REMS: f32 = 3.375;
const LABEL_MIN_H_REMS: f32 = 0.9375;
/// How a tile stands against the find text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Filtered {
/// It matches, is inside a match, or nothing is being found.
Shown,
/// It holds matches: its fill steps back, its name stays readable.
Holds,
/// Nothing in it matches.
Out,
}
/// Where keyboard focus should go once a window is available.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FocusTarget {
+124 -30
View File
@@ -383,28 +383,74 @@ fn hovering_reports_the_tile_under_the_pointer(cx: &mut TestAppContext) {
}
#[gpui_kit::test]
fn typing_in_the_find_field_jumps_to_a_match(cx: &mut TestAppContext) {
fn typing_filters_live_and_enter_shows_only_the_matches(
cx: &mut TestAppContext,
) {
cx.update(gpui_omarchy::init);
let temp = fixture();
let (view, cx) = view_over(temp.path(), cx);
draw(cx);
let names_drawn = |view: &Entity<Disktree>, cx: &mut Window| {
update(view, cx, |app, _| {
let tiles = app.layout().map(<[Tile]>::to_vec).unwrap_or_default();
tiles
.iter()
.filter_map(|tile| app.node_at(tile.crumbs()))
.map(|node| node.name.to_string())
.collect::<Vec<_>>()
})
};
press(cx, "/");
assert!(read(&view, cx, |app| app.find_open));
cx.simulate_input("deeper");
cx.simulate_input("BLOB");
// The search runs off the UI thread; let it land.
cx.run_until_parked();
draw(cx);
assert_eq!(read(&view, cx, |app| app.find.clone()), "deeper");
press(cx, "enter");
let (open, crumbs, selected) = read(&view, cx, |app| {
(app.find_open, app.crumbs.clone(), app.selected.clone())
// Live: two matches, nothing hidden yet, the rest only dimmed.
let (count, applied, keep_filtered) = read(&view, cx, |app| {
let matches = app.matches.as_deref().expect("matching as it is typed");
let keep = app.tree().and_then(|tree| {
tree.children
.iter()
.position(|child| &*child.name == "keep")
});
(
matches.count,
app.filter_applied,
keep.is_some_and(|index| matches.keep(&[index]).is_none()),
)
});
assert!(!open);
assert_eq!(crumbs, vec![1], "the matched entry's parent is drawn");
// junk holds blob.bin (largest first) and then deeper, so the match sits at
// the second index: the find jumps to the entry, not to its rank.
assert_eq!(selected, Some(vec![1, 1]));
assert_eq!(count, 2, "junk/blob.bin and .cache/blob.bin");
assert!(!applied);
assert!(keep_filtered, "keep holds no blob");
// Dimmed, not hidden: a non-match is still drawn while typing.
assert!(names_drawn(&view, cx).contains(&"deeper".to_string()));
// Enter: only the matches, and the largest selected for marking.
press(cx, "enter");
let drawn = names_drawn(&view, cx);
assert!(read(&view, cx, |app| app.filter_applied));
assert!(
!drawn.iter().any(|name| name == "keep" || name == "deeper"),
"{drawn:?}"
);
assert_eq!(
drawn.iter().filter(|name| *name == "blob.bin").count(),
2,
"{drawn:?}"
);
let selected = read(&view, cx, |app| {
app.selected
.as_deref()
.and_then(|crumbs| app.path_at(crumbs))
});
assert_eq!(selected, Some(temp.path().join(".cache/blob.bin")));
// Escape gives everything back.
press(cx, "escape");
assert!(read(&view, cx, |app| app.matches.is_none()
&& !app.filter_applied));
assert!(names_drawn(&view, cx).contains(&"deeper".to_string()));
}
#[gpui_kit::test]
@@ -883,31 +929,79 @@ fn dragging_the_panel_edge_resizes_it_within_its_limits(
}
#[gpui_kit::test]
fn g_switches_between_the_home_directory_and_the_whole_disk(
fn widening_reuses_the_tree_it_has_and_reads_only_the_rest(
cx: &mut TestAppContext,
) {
use crate::state::Scope;
use crate::state::Crumb;
cx.update(gpui_omarchy::init);
let temp = fixture();
let (view, cx) = view_over(temp.path(), cx);
// Stand-ins: the fixture is "home", a directory in it is "the disk".
let disk = temp.path().join("junk");
let inner = temp.path().join("junk");
let (view, cx) = view_over(&inner, cx);
update(&view, cx, |app, _| {
app.home = Some(temp.path().to_path_buf());
app.disk_root = Some(disk.clone());
app.disk_root = Some(temp.path().to_path_buf());
});
assert_eq!(read(&view, cx, Disktree::scope), Some(Scope::Home));
let before = read(&view, cx, |app| app.tree().map(|tree| tree.files));
// The trail runs from "/", and the scanned root sits under its parents.
let trail = read(&view, cx, Disktree::breadcrumbs);
assert_eq!(trail[0].0, "/");
assert!(
trail.contains(&(
temp.path()
.file_name()
.unwrap()
.to_string_lossy()
.into_owned(),
Crumb::Above(temp.path().to_path_buf())
))
);
// Written after the first scan: a memoized subtree cannot see it.
std::fs::write(inner.join("late.bin"), vec![0_u8; 4096]).expect("write");
press(cx, "g");
assert_eq!(read(&view, cx, |app| app.root_path.clone()), disk);
assert!(read(&view, cx, |app| app.scan.is_some()), "a new scan runs");
// The old tree stays on screen while the wider one is read.
assert!(read(&view, cx, |app| app.tree().is_some()));
finish_scan(&view, cx);
assert_eq!(read(&view, cx, Disktree::scope), Some(Scope::Disk));
let top = read(&view, cx, |app| app.tree().map(|tree| tree.bytes));
assert!(top.is_some_and(|bytes| bytes > 0));
assert_eq!(read(&view, cx, |app| app.root_path.clone()), temp.path());
let (reused, rest, selected) = read(&view, cx, |app| {
let tree = app.tree().expect("the wider tree");
let junk = tree.child_named("junk").map(|node| node.files);
let selected = app
.selected
.as_deref()
.and_then(|crumbs| app.node_at(crumbs))
.map(|node| node.name.to_string());
(junk, tree.child_named("keep").is_some(), selected)
});
assert_eq!(reused, before, "junk was reused, not walked again");
assert!(rest, "what is outside it was walked");
assert_eq!(selected.as_deref(), Some("junk"), "where you came from");
}
press(cx, "g");
finish_scan(&view, cx);
assert_eq!(read(&view, cx, Disktree::scope), Some(Scope::Home));
#[gpui_kit::test]
fn enter_before_the_search_lands_applies_it_when_it_does(
cx: &mut TestAppContext,
) {
cx.update(gpui_omarchy::init);
let temp = fixture();
let (view, cx) = view_over(temp.path(), cx);
draw(cx);
press(cx, "/");
cx.simulate_input("blob");
cx.simulate_keystrokes("enter");
cx.run_until_parked();
draw(cx);
let (applied, count, open) = read(&view, cx, |app| {
(
app.filter_applied,
app.matches.as_deref().map(|matches| matches.count),
app.find_open,
)
});
assert!(applied, "Enter was not lost to a search in flight");
assert_eq!(count, Some(2));
assert!(!open);
}
+22 -4
View File
@@ -24,7 +24,7 @@ use gpui_omarchy::{ActiveTheme, Theme};
use disktree_core::classify::Category;
use crate::palette;
use crate::state::{Disktree, Label, View};
use crate::state::{Disktree, Filtered, Label, View};
/// How one tile should be drawn, resolved before the paint callback runs so
/// that painting never has to look anything up.
@@ -40,6 +40,8 @@ pub struct TileDeco {
pub age_bucket: Option<usize>,
/// Its space can be had back: hatched.
pub reclaimable: bool,
/// How it stands against the find text.
pub filtered: Filtered,
/// Part of it could not be read: flagged in its corner.
pub unreadable: bool,
pub marked: bool,
@@ -159,6 +161,8 @@ struct Colors {
/// Fills per age bucket, then per depth.
age: Vec<[Hsla; DEPTHS]>,
marked_fill: Hsla,
/// The surface a filtered-out fill steps back toward.
inset: Hsla,
}
/// Depth steps a fill distinguishes; deeper clamps.
@@ -220,6 +224,7 @@ impl Colors {
})
.collect(),
marked_fill: palette::mix(theme.inset, theme.danger, 0.16),
inset: theme.inset,
}
}
@@ -228,9 +233,16 @@ impl Colors {
return self.marked_fill;
}
let depth = (tile.depth as usize).min(DEPTHS - 1);
match tile.age_bucket {
let fill = match tile.age_bucket {
Some(bucket) => self.age[bucket.min(self.age.len() - 1)][depth],
None => self.fill[category_index(tile.category)][depth],
};
// Only what matches keeps its colour; a directory holding matches
// steps back less, so the way to them stays readable.
match tile.filtered {
Filtered::Shown => fill,
Filtered::Holds => palette::mix(fill, self.inset, 0.55),
Filtered::Out => palette::mix(fill, self.inset, 0.82),
}
}
@@ -275,7 +287,8 @@ fn paint_tiles(
// "can it go", the colour "what is it". Everything inside a
// reclaimable directory is reclaimable too, so only the outermost
// one needs painting; its children repaint their own fill and hatch.
if tile.reclaimable && !tile.marked {
if tile.reclaimable && !tile.marked && tile.filtered == Filtered::Shown
{
window.paint_quad(quad(
quad_bounds,
Corners::default(),
@@ -288,7 +301,10 @@ fn paint_tiles(
// A top-level directory carries a thin strip of its colour, so the
// first level of structure reads before any detail.
if tile.depth == 0 && tile.age_bucket.is_none() {
if tile.depth == 0
&& tile.age_bucket.is_none()
&& tile.filtered != Filtered::Out
{
let strip = Bounds::new(
quad_bounds.origin,
Size::new(
@@ -415,6 +431,8 @@ fn paint_labels(
);
let color = if label.marked {
colors.marked_label
} else if label.dim {
colors.label_dim
} else {
colors.label(label.depth)
};
+92 -57
View File
@@ -27,7 +27,7 @@ use gpui_kit::prelude::FluentBuilder as _;
use crate::palette;
use crate::state::{
ColorMode, Disktree, PANEL_REMS, Scope, Screen, panel_width,
ColorMode, Crumb, Disktree, PANEL_REMS, Screen, panel_width,
};
use crate::treemap_view::{self, Mosaic};
use crate::ui::{icon, size, space, text};
@@ -35,7 +35,7 @@ use crate::widgets;
/// Width, in rem, at which the header holds title, settings and totals on one
/// line. Narrower, the totals move into the status bar.
const HEADER_WIDE_REMS: f32 = 86.0;
const HEADER_WIDE_REMS: f32 = 74.0;
/// How many marks the review screen lists. Everything above the cap is still
/// removed; the list only stops being exhaustive, which it says out loud.
@@ -303,10 +303,7 @@ fn top_bar(
.py(space::MD)
.border_b_1()
.border_color(theme.divider())
.child(logo(theme))
// What is scanned sits with the name: the totals beside it are
// totals of this choice.
.child(scope_switch(app, window, cx));
.child(logo(theme));
if wide {
let value = |text: String| text;
row = row
@@ -523,8 +520,10 @@ fn trail_and_legend(
.items_center()
.gap(space::XXS)
.flex_shrink_0();
for (index, (label, path)) in trail.into_iter().enumerate() {
if index > 0 {
let widening = app.scan.is_some() && app.scan_root != app.root_path;
for (index, (label, step)) in trail.into_iter().enumerate() {
// The root is its own separator: "/" then "home", not "/ / home".
if index > 1 {
crumbs = crumbs.child(
div()
.text_color(theme.secondary.opacity(0.5))
@@ -533,11 +532,31 @@ fn trail_and_legend(
);
}
let id = ElementId::Name(SharedString::from(format!("crumb-{index}")));
crumbs = crumbs.child(
widgets::crumb(id, label, index == last, cx).on_click(
cx.listener(move |this, _, _, cx| this.go_to(path.clone(), cx)),
),
);
let crumb = match step {
// Above the scan: dimmer, and a click widens the scan to there.
Crumb::Above(path) => {
let pending = widening && app.scan_root == path;
with_tooltip(
widgets::crumb(id, label, false, cx)
.text_color(if pending {
palette::highlight(theme)
} else {
theme.secondary.opacity(0.7)
})
.on_click(cx.listener(move |this, _, _, cx| {
this.widen_to(path.clone(), cx);
})),
"Scan from here · what is below is reused",
)
.into_any_element()
}
Crumb::Tree(path) => widgets::crumb(id, label, index == last, cx)
.on_click(cx.listener(move |this, _, _, cx| {
this.go_to(path.clone(), cx);
}))
.into_any_element(),
};
crumbs = crumbs.child(crumb);
}
let mut row = div()
@@ -554,45 +573,6 @@ fn trail_and_legend(
row.child(div().flex_1()).child(legend(app, theme, cx))
}
/// What is scanned: the home directory or the whole disk it lives on. A
/// root given on the command line is neither, and selects nothing.
fn scope_switch(
app: &Disktree,
window: &mut Window,
cx: &mut Context<'_, Disktree>,
) -> impl IntoElement {
let entity = cx.entity().downgrade();
let focus = app.focus.clone();
let disk = app.disk_root.as_deref().map_or_else(
|| "/ Whole disk".to_string(),
|root| format!("{} Whole disk", root.display()),
);
with_tooltip(
button_group(
"scope",
vec![
ChoiceItem::new("home", "~ Home"),
ChoiceItem::new("disk", disk),
],
app.scope().map(|scope| usize::from(scope == Scope::Disk)),
move |index, window, cx| {
let _ = entity.update(cx, |this, cx| {
this.set_scope(
if index == 1 { Scope::Disk } else { Scope::Home },
cx,
);
});
window.focus(&focus, cx);
},
window,
cx,
)
.flex_shrink_0()
.p(space::XXS),
"What to scan · g switches",
)
}
/// The key to the colours: the categories, or the age ramp in age mode.
/// Clipped from the trailing end when the row runs out of room.
fn legend(app: &Disktree, theme: &Theme, cx: &App) -> Div {
@@ -1393,7 +1373,7 @@ fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div {
("\u{232b}", "up"),
("c", "review"),
("hjkl", "move"),
("/", "find"),
("/", "filter"),
("[ ]", "depth"),
("t", "mode"),
("0", "reset"),
@@ -1536,6 +1516,31 @@ fn scanning_panel(app: &Disktree, theme: &Theme, cx: &gpui_kit::App) -> Div {
}
fn find_field(app: &Disktree, theme: &Theme) -> Div {
// What the text matches, said beside it as it is typed, and what Enter
// and Escape will do with it.
let (summary, hint) = match app.matches.as_deref() {
_ if app.finding && app.matches.is_none() => {
("searching…".to_string(), "")
}
None => (String::new(), "type to filter"),
Some(matches) if matches.count == 0 => {
("no matches".to_string(), "esc clears")
}
Some(matches) => (
format!(
"{} match{} · {}",
widgets::human_count(matches.count as u64),
if matches.count == 1 { "" } else { "es" },
human_bytes(matches.bytes)
),
if app.filter_applied {
"esc clears"
} else {
"enter shows only these"
},
),
};
let highlight = palette::highlight(theme);
div()
.flex()
.flex_row()
@@ -1543,9 +1548,12 @@ fn find_field(app: &Disktree, theme: &Theme) -> Div {
.gap(space::SM)
.px(space::SM)
.py(space::XS)
.min_w_0()
.border_1()
.border_color(if app.find_open {
theme.accent
} else if app.filter_applied {
highlight
} else {
theme.control_border()
})
@@ -1554,15 +1562,39 @@ fn find_field(app: &Disktree, theme: &Theme) -> Div {
.child(
gpui_omarchy::icon(gpui_omarchy::IconName::Search)
.size(icon::SM)
.text_color(theme.secondary),
.text_color(if app.filter_applied {
highlight
} else {
theme.secondary
}),
)
.child(if app.find.is_empty() {
div()
.text_color(theme.secondary.opacity(0.7))
.child("Find by name")
.child("Filter by name")
} else {
div().text_color(theme.bright).child(app.find.clone())
})
.when(!summary.is_empty(), |this| {
this.child(
div()
.text_size(text::CAPTION)
.text_color(if app.filter_applied {
highlight
} else {
theme.secondary
})
.whitespace_nowrap()
.child(summary),
)
})
.child(
div()
.text_size(text::CAPTION)
.text_color(theme.secondary.opacity(0.6))
.whitespace_nowrap()
.child(hint),
)
}
fn short_name(path: &std::path::Path) -> String {
@@ -2495,11 +2527,14 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div {
("[ / ]", "Draw fewer or more levels at once"),
("- / = / 0", "Magnify, shrink, or reset the view"),
("ctrl = / - / 0", "Interface zoom"),
("/", "Find an entry by name"),
(
"/",
"Filter by name: only matches keep their colour; enter shows only them",
),
("c", "Review the marked list"),
("t", "Size, files or age: what areas and colours say"),
("r", "Scan again from the same root"),
("g", "Scan the home directory or the whole disk"),
("g", "The whole disk; click any directory above to widen"),
("d", "Disk usage or apparent size"),
("i", "Include or skip hidden entries"),
("p", "Show or hide the selection line"),