Skip to content

A treemap for finding and removing what fills your disk, for Omarchy. Rust + GPUI.

Rust

Back and forward through the directories visited

Mathias Bogaertdb843bb4f8cb
diff --git a/README.md b/README.md
index e1c1580..7ef2df9 100644
--- a/README.md
+++ b/README.md
@@ -99,7 +99,9 @@ Scroll to magnify toward the pointer. The wheel magnifies until the directory
under the pointer fills the view, and the next notch goes into it — one
continuous motion, with the directory's contents growing into place. Scroll the
other way to come back out. Enter goes into the selected directory at any
-depth, and Backspace or Escape goes up one level. `+` and `-` magnify without
+depth, and Backspace or Escape goes up one level. `<` and `>`, beside the
+Size / Files / Age switch, go back and forward through the directories visited,
+as do `alt ←` `alt →` and the mouse's side buttons. `+` and `-` magnify without
going in; `0` resets.
### Removing
@@ -124,6 +126,7 @@ and shows how much free space was actually gained.
| `ctrl`-click | mark without moving the selection |
| `enter` | open that directory, at any depth |
| `⌫` / `esc` | go up one directory |
+| `alt ←` `alt →` | back and forward through where you have been |
| `←` `↑` `↓` `→` | move between tiles at this level |
| `tab` | next largest sibling |
| scroll | zoom toward a directory, then go into it |
diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs
index 6a2212a..5c9c163 100644
--- a/crates/disktree-app/src/state.rs
+++ b/crates/disktree-app/src/state.rs
@@ -26,8 +26,8 @@ use disktree_core::treemap::{
};
use gpui_kit::{
Context, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent,
- MouseMoveEvent, Pixels, Point, Render, ScrollDelta, ScrollWheelEvent, Size,
- Window, px, size,
+ MouseMoveEvent, NavigationDirection, Pixels, Point, Render, ScrollDelta,
+ ScrollWheelEvent, Size, Window, px, size,
};
use gpui_omarchy::Status;
use rustc_hash::{FxHashMap, FxHashSet};
@@ -297,6 +297,20 @@ struct LayoutKey {
filter: u64,
}
+/// Directories left behind and come back from, for `<` and `>`.
+///
+/// Kept as absolute paths, not crumbs: a re-scan or a widening renumbers the
+/// tree, and crumbs would then silently point at other directories.
+#[derive(Clone, Debug, Default)]
+pub struct History {
+ pub back: Vec<PathBuf>,
+ pub forward: Vec<PathBuf>,
+}
+
+/// How many directories back is remembered. Far more than anyone clicks
+/// through, and small enough that pruning after a scan costs nothing.
+const HISTORY_DEPTH: usize = 100;
+
/// Result of the removal run, summarised for the final screen.
#[derive(Clone, Debug, Default)]
pub struct RunSummary {
@@ -323,6 +337,10 @@ pub struct Disktree {
pub crumbs: Vec<usize>,
pub selected: Option<Vec<usize>>,
pub hovered: Option<Vec<usize>>,
+ pub history: History,
+ /// The history button under the pointer, `true` for `<`: its card is
+ /// drawn below it for as long as it is.
+ pub history_hover: Option<bool>,
/// The pointer moved more recently than the keyboard navigated. Then the
/// tile under the pointer is what Space, X and Enter act on; after an
/// arrow or Tab it is the keyboard selection again.
@@ -430,6 +448,8 @@ impl Disktree {
crumbs: Vec::new(),
selected: None,
hovered: None,
+ history: History::default(),
+ history_hover: None,
pointer_active: false,
view: View::default(),
transition: None,
@@ -551,6 +571,7 @@ impl Disktree {
self.scan_started = Some(Instant::now());
self.scan_elapsed = None;
self.scan_root.clone_from(&above);
+ self.remember();
let known = Known {
path: self.root_path.clone(),
tree,
@@ -632,6 +653,10 @@ impl Disktree {
let epoch = self.scan_epoch;
self.progress = ScanSnapshot::default();
self.scan_error = None;
+ // A new scan starts at its root; where it was is one `<` away.
+ if !self.crumbs.is_empty() {
+ self.remember();
+ }
self.tree = None;
self.crumbs.clear();
self.selected = None;
@@ -718,6 +743,7 @@ impl Disktree {
});
}
self.keep_selection_valid();
+ self.prune_history();
self.select_largest(cx);
}
Err(error) => self.scan_error = Some(error.to_string()),
@@ -988,6 +1014,7 @@ impl Disktree {
if !node.is_dir() || node.children.is_empty() {
return;
}
+ self.remember();
self.selected = Some(target.clone());
self.crumbs = target;
self.forget_hover();
@@ -1040,18 +1067,27 @@ impl Disktree {
/// Ascend to the parent directory, keeping the directory we came from in
/// view so the motion reads as zooming out.
pub fn ascend(&mut self, cx: &mut Context<'_, Self>) {
- let Some(parent_crumbs) = self.parent_crumbs() else {
- return;
- };
+ if let Some(parent_crumbs) = self.parent_crumbs() {
+ self.ascend_to(parent_crumbs, cx);
+ }
+ }
+
+ /// Make `ancestor`, a directory above the current root, the root.
+ ///
+ /// The directory we leave shrinks back into its tile when that tile is
+ /// drawn at the new level; from further up it is too small to track, and
+ /// the new level simply lands.
+ fn ascend_to(&mut self, ancestor: Vec<usize>, cx: &mut Context<'_, Self>) {
+ self.remember();
// The region we are looking at now, and where it sits in the layout
// we are going back to.
let area = self.treemap_size.get();
let child_crumbs = self.crumbs.clone();
let src = self.view.visible_base(area);
- self.crumbs.clone_from(&parent_crumbs);
+ self.crumbs.clone_from(&ancestor);
self.forget_hover();
self.cache = None;
- self.selected = Some(parent_crumbs);
+ self.selected = Some(ancestor);
self.view = View::IDENTITY;
self.transition = self
.tile_body(&child_crumbs)
@@ -1075,6 +1111,10 @@ impl Disktree {
/// it lands immediately, the way selecting a folder does.
pub fn go_to(&mut self, crumbs: Vec<usize>, cx: &mut Context<'_, Self>) {
self.crumb_menu = None;
+ // A reveal in the directory on screen goes nowhere.
+ if crumbs != self.crumbs {
+ self.remember();
+ }
self.crumbs.clone_from(&crumbs);
self.selected = Some(crumbs);
self.forget_hover();
@@ -1084,6 +1124,117 @@ impl Disktree {
cx.notify();
}
+ /// Note the directory on screen as one to come back to, before leaving
+ /// it. A new departure ends whatever was ahead, as in a browser.
+ fn remember(&mut self) {
+ if self.tree.is_none() {
+ return;
+ }
+ let here = self.current_path();
+ if self.history.back.last() != Some(&here) {
+ self.history.back.push(here);
+ }
+ if self.history.back.len() > HISTORY_DEPTH {
+ self.history.back.remove(0);
+ }
+ self.history.forward.clear();
+ }
+
+ /// Drop what a new tree no longer holds: a removed directory, or one
+ /// outside a new root. What is left always resolves, so `<` and `>` are
+ /// enabled exactly when they would go somewhere.
+ fn prune_history(&mut self) {
+ let mut history = std::mem::take(&mut self.history);
+ history
+ .back
+ .retain(|path| self.crumbs_for_path(path).is_some());
+ history
+ .forward
+ .retain(|path| self.crumbs_for_path(path).is_some());
+ self.history = history;
+ }
+
+ /// Whether `<` would go anywhere: what drives its button's disabled state.
+ pub fn can_go_back(&self) -> bool {
+ self.history_target(true).is_some()
+ }
+
+ /// Whether `>` would go anywhere.
+ pub fn can_go_forward(&self) -> bool {
+ self.history_target(false).is_some()
+ }
+
+ /// `<`: the directory on screen before this one.
+ pub fn go_back(&mut self, cx: &mut Context<'_, Self>) {
+ self.step_history(true, cx);
+ }
+
+ /// `>`: undo a `<`.
+ pub fn go_forward(&mut self, cx: &mut Context<'_, Self>) {
+ self.step_history(false, cx);
+ }
+
+ /// Where `<` (or `>`) would go, and its place on that stack: the newest
+ /// entry that is somewhere else. An entry can be where we already are,
+ /// after a widening that was superseded; it is skipped rather than spend
+ /// a click on nothing. Every other entry resolves, being pruned whenever
+ /// a tree lands.
+ pub fn history_target(&self, back: bool) -> Option<(usize, Vec<usize>)> {
+ self.tree.as_ref()?;
+ let stack = if back {
+ &self.history.back
+ } else {
+ &self.history.forward
+ };
+ stack.iter().enumerate().rev().find_map(|(at, path)| {
+ self.crumbs_for_path(path)
+ .filter(|crumbs| *crumbs != self.crumbs)
+ .map(|crumbs| (at, crumbs))
+ })
+ }
+
+ fn step_history(&mut self, back: bool, cx: &mut Context<'_, Self>) {
+ let Some((at, target)) = self.history_target(back) else {
+ return;
+ };
+ let here = self.current_path();
+ let mut history = std::mem::take(&mut self.history);
+ let (from, to) = if back {
+ (&mut history.back, &mut history.forward)
+ } else {
+ (&mut history.forward, &mut history.back)
+ };
+ from.truncate(at);
+ to.push(here);
+ // The move is an ordinary one, animation and all; it records itself
+ // like any other, so the stacks are put back afterwards.
+ self.travel(target, cx);
+ self.history = history;
+ cx.notify();
+ }
+
+ /// Go to `target` with the motion that fits: grow into a directory
+ /// below, shrink back out to one above, or land on one beside.
+ fn travel(&mut self, target: Vec<usize>, cx: &mut Context<'_, Self>) {
+ let enterable = self
+ .node_at(&target)
+ .is_some_and(|node| node.is_dir() && !node.children.is_empty());
+ if target.len() > self.crumbs.len()
+ && target.starts_with(&self.crumbs)
+ && enterable
+ {
+ let from =
+ self.tile_body(&target).map(|rect| self.view.project(rect));
+ self.enter(target, from, cx);
+ } else if target.len() < self.crumbs.len()
+ && self.crumbs.starts_with(&target)
+ {
+ self.ascend_to(target, cx);
+ } else {
+ self.go_to(target, cx);
+ }
+ }
+
/// Show `crumbs` in its directory, selected: what a "worth a look" row
/// or a found name does.
pub fn reveal(&mut self, crumbs: Vec<usize>, cx: &mut Context<'_, Self>) {
@@ -1962,6 +2113,7 @@ impl Disktree {
let key = event.keystroke.key.as_str();
let control = event.keystroke.modifiers.control;
let shift = event.keystroke.modifiers.shift;
+ let alt = event.keystroke.modifiers.alt;
// The alert dialog owns Enter and Escape while it is open; a key that
// bubbles up to here must not also act on the screen behind it.
@@ -2012,6 +2164,9 @@ impl Disktree {
}
match self.screen {
+ // Alt-arrows are history in every browser and file manager.
+ Screen::Explore if alt && key == "left" => self.go_back(cx),
+ Screen::Explore if alt && key == "right" => self.go_forward(cx),
Screen::Explore => self.on_explore_key(key, control, shift, cx),
Screen::Review => self.on_review_key(key, cx),
Screen::Running => {
@@ -2271,6 +2426,12 @@ impl Disktree {
self.toggle_mark(&crumbs, cx);
}
}
+ MouseButton::Navigate(NavigationDirection::Back) => {
+ self.go_back(cx);
+ }
+ MouseButton::Navigate(NavigationDirection::Forward) => {
+ self.go_forward(cx);
+ }
_ => {}
}
}
diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rs
index 946b06a..ce7052f 100644
--- a/crates/disktree-app/src/tests.rs
+++ b/crates/disktree-app/src/tests.rs
@@ -1165,3 +1165,86 @@ fn marking_a_directory_marks_everything_inside_it(cx: &mut TestAppContext) {
update(&view, cx, |app, cx| app.toggle_mark(&junk, cx));
assert!(read(&view, cx, |app| app.marks.is_empty()));
}
+
+/// `<` and `>` retrace the directories visited, are disabled when there is
+/// nowhere to go, and a fresh move ends what was ahead.
+#[gpui_kit::test]
+fn back_and_forward_retrace_where_you_have_been(cx: &mut TestAppContext) {
+ use gpui_kit::Modifiers;
+
+ cx.update(gpui_omarchy::init);
+ let temp = fixture();
+ let (view, cx) = view_over(temp.path(), cx);
+ cx.simulate_resize(gpui_kit::size(px(1400.), px(900.)));
+ draw(cx);
+ let can = |view: &Entity<Disktree>, cx: &Window| {
+ read(view, cx, |app| (app.can_go_back(), app.can_go_forward()))
+ };
+ assert_eq!(can(&view, cx), (false, false), "nowhere to go yet");
+
+ let (junk, deeper, keep) = update(&view, cx, |app, cx| {
+ let junk = child_crumbs(app, &[], "junk");
+ let deeper = child_crumbs(app, &junk, "deeper");
+ let keep = child_crumbs(app, &[], "keep");
+ app.select(Some(deeper.clone()), cx);
+ app.descend(cx);
+ (junk, deeper, keep)
+ });
+ draw(cx);
+ assert_eq!(can(&view, cx), (true, false));
+
+ // Hovering `<` shows the card for where it goes, as hovering a tile
+ // does: here, the scanned root. It hangs below the button, never on it.
+ let back = cx
+ .debug_bounds("history-back")
+ .expect("the button is drawn");
+ cx.simulate_mouse_move(back.center(), None, Modifiers::none());
+ draw(cx);
+ let card = cx.debug_bounds("history-tip").expect("the card is shown");
+ assert!(card.top() >= back.bottom(), "{card:?} covers {back:?}");
+ assert_eq!(
+ read(&view, cx, |app| app.history_target(true)),
+ Some((0, Vec::new()))
+ );
+
+ let click = |cx: &mut Window, selector: &'static str| {
+ let bounds = cx.debug_bounds(selector).expect("the button is drawn");
+ cx.simulate_click(bounds.center(), Modifiers::none());
+ draw(cx);
+ };
+ click(cx, "history-back");
+ assert_eq!(
+ read(&view, cx, |app| app.crumbs.clone()),
+ Vec::<usize>::new()
+ );
+ assert_eq!(can(&view, cx), (false, true), "back at the start");
+
+ click(cx, "history-forward");
+ assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper);
+ assert_eq!(can(&view, cx), (true, false));
+
+ // Up a level is a move of its own, and the keys retrace it too.
+ press(cx, "backspace");
+ assert_eq!(read(&view, cx, |app| app.crumbs.clone()), junk);
+ press(cx, "alt-left");
+ assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper);
+ press(cx, "alt-left");
+ assert_eq!(
+ read(&view, cx, |app| app.crumbs.clone()),
+ Vec::<usize>::new()
+ );
+ press(cx, "alt-right");
+ assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper);
+
+ // Going somewhere new from the middle of the history drops what was
+ // ahead of it, as in a browser.
+ press(cx, "alt-left");
+ update(&view, cx, |app, cx| app.go_to(keep, cx));
+ draw(cx);
+ assert_eq!(can(&view, cx), (true, false), "the forward trail is gone");
+ press(cx, "alt-left");
+ assert_eq!(
+ read(&view, cx, |app| app.crumbs.clone()),
+ Vec::<usize>::new()
+ );
+}
diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs
index ca7b193..2f785a8 100644
--- a/crates/disktree-app/src/views.rs
+++ b/crates/disktree-app/src/views.rs
@@ -688,6 +688,84 @@ fn view_settings(
};
let theme = cx.omarchy().clone();
+ // Back and forward through the directories visited, beside the choices
+ // that change how the one on screen is drawn.
+ let travel = |id: &'static str,
+ label: &'static str,
+ enabled: bool,
+ back: bool,
+ go: fn(&mut Disktree, &mut Context<'_, Disktree>),
+ cx: &mut Context<'_, Disktree>| {
+ let shown = app.history_hover == Some(back);
+ div()
+ .id(ElementId::Name(format!("{id}-hover").into()))
+ .debug_selector(move || id.into())
+ .relative()
+ .on_hover(cx.listener(move |this, hovered: &bool, _, cx| {
+ // Leaving one button can be reported after entering the
+ // other; only the button that owns the card takes it away.
+ if *hovered {
+ this.history_hover = Some(back);
+ } else if this.history_hover == Some(back) {
+ this.history_hover = None;
+ }
+ cx.notify();
+ }))
+ .child(
+ button(id, label, ButtonVariant::Secondary, cx)
+ .tab_stop(false)
+ .disabled(!enabled)
+ // Borderless: glyphs on the bar, not controls in a
+ // frame. Hover keeps the fill but not the outline it
+ // would add.
+ .hover(|style| {
+ style
+ .bg(theme.hover_fill())
+ .border_color(theme.foreground.opacity(0.))
+ })
+ .on_click(cx.listener(move |this, _, window, cx| {
+ go(this, cx);
+ window.focus(&this.focus, cx);
+ })),
+ )
+ .when(shown, |this| {
+ // Anchored to a holder pinned at the button's bottom edge, so
+ // the card hangs below it and never covers it; deferred so it
+ // paints over the mosaic.
+ this.child(
+ div().absolute().top_full().left_0().child(
+ deferred(
+ anchored()
+ .snap_to_window_with_margin(px(8.))
+ .offset(gpui_kit::point(px(0.), px(4.)))
+ .child(history_card(app, back, cx)),
+ )
+ .with_priority(2),
+ ),
+ )
+ })
+ };
+ let history = div()
+ .flex()
+ .flex_row()
+ .items_center()
+ .child(travel(
+ "history-back",
+ "<",
+ app.can_go_back(),
+ true,
+ Disktree::go_back,
+ cx,
+ ))
+ .child(travel(
+ "history-forward",
+ ">",
+ app.can_go_forward(),
+ false,
+ Disktree::go_forward,
+ cx,
+ ));
+
let depth = app.layout_options.max_depth;
let stepper = |id: &'static str,
label: &'static str,
@@ -727,6 +805,7 @@ fn view_settings(
.items_center()
.gap(space::SM)
.flex_shrink_0()
+ .child(history)
.child(mode)
.child(hidden)
.child(apparent)
@@ -2592,37 +2671,80 @@ pub fn cursor_tooltip(
anchor_y + gap
};
- // The same surface treatment as Omarchy's tooltip, square and bordered,
- // so an anchored surface of this app does not drift from the system's.
- // Translucent so the mosaic stays visible underneath it.
- let theme = cx.omarchy();
Some(
- div()
+ card_surface(cx)
.absolute()
.left(px(x))
.top(px(y))
- .w(size::TOOLTIP)
- .flex()
- .flex_col()
- .gap(space::XS)
- .px(space::SM)
- .py(space::SM)
- .border_1()
- .border_color(theme.control_border())
- .bg(theme.background.opacity(0.93))
- .text_color(theme.foreground)
- .font_family(theme.font.clone())
- .text_size(text::CAPTION)
.child(content),
)
}
+/// The same surface treatment as Omarchy's tooltip, square and bordered,
+/// so an anchored surface of this app does not drift from the system's.
+/// Translucent so the mosaic stays visible underneath it.
+fn card_surface(cx: &gpui_kit::App) -> Div {
+ let theme = cx.omarchy();
+ div()
+ .w(size::TOOLTIP)
+ .flex()
+ .flex_col()
+ .gap(space::XS)
+ .px(space::SM)
+ .py(space::SM)
+ .border_1()
+ .border_color(theme.control_border())
+ .bg(theme.background.opacity(0.93))
+ .text_color(theme.foreground)
+ .font_family(theme.font.clone())
+ .text_size(text::CAPTION)
+}
+
+/// The card under `<` or `>` while it is hovered: what hovering a tile
+/// shows, for the directory the button goes to, so where it leads is known
+/// before going. Drawn by the app rather than as a tooltip, which GPUI puts
+/// at the pointer, over the button itself.
+fn history_card(app: &Disktree, back: bool, cx: &gpui_kit::App) -> Div {
+ let (label, keys) = if back {
+ ("Back", "alt \u{2190} back")
+ } else {
+ ("Forward", "alt \u{2192} forward")
+ };
+ let card = app
+ .history_target(back)
+ .and_then(|(_, crumbs)| node_card(app, &crumbs, keys, cx));
+ card_surface(cx)
+ .debug_selector(|| "history-tip".into())
+ .map(|surface| match card {
+ Some(card) => surface.child(card),
+ // Nowhere to go: the button is disabled; say what it is for.
+ None => surface.child(format!("{label} \u{00b7} {keys}")),
+ })
+}
+
/// The tooltip content for the hovered tile: everything the tile cannot show.
pub fn hover_tooltip(app: &Disktree, cx: &gpui_kit::App) -> Option<Div> {
+ let crumbs = app.hovered.as_deref()?;
+ let is_dir = app.node_at(crumbs)?.is_dir();
+ let keys = if is_dir {
+ "space mark · enter open"
+ } else {
+ "space mark"
+ };
+ node_card(app, crumbs, keys, cx)
+}
+
+/// What is known about the node at `crumbs`, as a card: name, path, size and
+/// share, counts, and badges, with `keys` for what can be done from there.
+fn node_card(
+ app: &Disktree,
+ crumbs: &[usize],
+ keys: &str,
+ cx: &gpui_kit::App,
+) -> Option<Div> {
let theme = cx.omarchy();
- let crumbs = app.hovered.clone()?;
- let node = app.node_at(&crumbs)?;
- let path = app.path_at(&crumbs);
+ let node = app.node_at(crumbs)?;
+ let path = app.path_at(crumbs);
let parent = crumbs[..crumbs.len().saturating_sub(1)].to_vec();
let parent_value = app.node_at(&parent).map_or(0, |node| node.bytes);
let marked = path.as_deref().is_some_and(|path| app.marks.contains(path));
@@ -2725,11 +2847,7 @@ pub fn hover_tooltip(app: &Disktree, cx: &gpui_kit::App) -> Option<Div> {
div()
.text_size(text::CAPTION)
.text_color(theme.secondary.opacity(0.7))
- .child(if node.is_dir() {
- "space mark · enter open"
- } else {
- "space mark"
- }),
+ .child(keys.to_string()),
);
Some(tip)
}
@@ -2738,11 +2856,15 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div {
let theme = cx.omarchy();
// Sentence case, and the tile a key acts on is always the one under the
// pointer if the pointer moved last, else the keyboard selection.
- let rows: [(&str, &str); 24] = [
+ let rows: [(&str, &str); 25] = [
("space / x", "Mark or unmark the tile you point at"),
("ctrl-click", "Mark without moving the selection"),
("enter", "Open that directory, at any depth"),
("\u{232b} / esc", "Go up one directory"),
+ (
+ "alt \u{2190} / \u{2192}",
+ "Back or forward through where you have been",
+ ),
(
"\u{2190} \u{2191} \u{2193} \u{2192}",
"Move between tiles at this level",