A treemap for finding and removing what fills your disk, for Omarchy. Rust + GPUI.
Rust
disktree-app: a GPUI treemap explorer for Omarchy
Tobi Lutkecd41a9f7c84b
diff --git a/crates/disktree-app/Cargo.toml b/crates/disktree-app/Cargo.tomlnew file mode 100644index 0000000..63644e0--- /dev/null+++ b/crates/disktree-app/Cargo.toml@@ -0,0 +1,29 @@+[package]+name = "disktree-app"+version.workspace = true+edition.workspace = true+rust-version.workspace = true+license.workspace = true+description = "GPUI treemap explorer for disk usage, in Omarchy's visual language"++[[bin]]+name = "disktree"+path = "src/main.rs"++[lints]+workspace = true++[dependencies]+gpui-kit = { version = "=0.6.1", default-features = false, features = ["assets"] }+gpui-omarchy = "0.1.2"+disktree-core = { workspace = true }+anyhow = { workspace = true }+rustc-hash = { workspace = true }++[dev-dependencies]+# The window harness: it lets the tests draw a real frame and press real keys.+gpui-kit = { version = "=0.6.1", default-features = false, features = [+ "assets",+ "test-support",+] }+tempfile = "3"diff --git a/crates/disktree-app/src/main.rs b/crates/disktree-app/src/main.rsnew file mode 100644index 0000000..8dbbaf5--- /dev/null+++ b/crates/disktree-app/src/main.rs@@ -0,0 +1,180 @@+//! `disktree`: find what is eating a volume, mark it, and remove it.+//!+//! The window opens on a treemap of the scanned root — the home directory+//! unless another path is given — with a breadcrumb bar, a selection line, and a+//! live free-space meter. Marking is non-destructive until the review screen+//! is confirmed.++mod marks;+mod palette;+mod state;+#[cfg(test)]+mod tests;+mod treemap_view;+mod ui;+mod views;+mod widgets;++use std::path::PathBuf;++use anyhow::{Context as _, Result};+use disktree_core::scan::ScanOptions;+use gpui_kit::{AppContext as _, WindowOptions, px, size};+use state::Disktree;++/// What the command line asked for.+#[derive(Debug)]+struct Args {+ root: PathBuf,+ options: ScanOptions,+ depth: u32,+}++const USAGE: &str = "\+disktree — a treemap of what is using your disk++usage: disktree [OPTIONS] [PATH]++arguments:+ PATH directory to scan (default: the home directory)++The window opens on a treemap of the root, largest first. Space marks the+selected tile, Enter opens it, c reviews the marked list, ? lists every key.++options:+ -a, --apparent-size measure apparent length instead of allocated blocks+ -l, --follow-links follow symlinks+ -H, --no-hidden skip dotfiles and dot-directories+ -x, --one-filesystem do not cross filesystem boundaries+ -d, --depth N how many levels to draw at once (1-6, default 3)+ --metric files rank by file count instead of bytes+ -h, --help show this help+";++fn main() -> Result<()> {+ let args = parse_args()?;+ let root = args.root.clone();+ let depth = args.depth;+ let title_root = root.clone();++ gpui_kit::application()+ .with_assets(gpui_kit::assets::Assets)+ .run(move |cx| {+ gpui_omarchy::init(cx);+ let options = args.options.clone();+ let root_for_app = root.clone();+ let window = cx+ .open_window(+ WindowOptions {+ window_bounds: Some(gpui_kit::WindowBounds::Windowed(+ gpui_kit::Bounds::new(+ gpui_kit::point(px(120.), px(90.)),+ size(px(1440.), px(900.)),+ ),+ )),+ titlebar: Some(gpui_kit::TitlebarOptions {+ title: Some(+ format!(+ "disktree · {}",+ marks::display_path(+ &title_root,+ std::env::var_os("HOME")+ .map(PathBuf::from)+ .as_deref(),+ )+ )+ .into(),+ ),+ ..Default::default()+ }),+ // Below this the treemap stops being readable, so ask+ // the compositor not to go there.+ window_min_size: Some(size(px(900.), px(600.))),+ ..Default::default()+ },+ move |_, cx| {+ cx.new(|cx| {+ Disktree::new(+ root_for_app.clone(),+ options.clone(),+ depth,+ cx,+ )+ })+ },+ )+ .expect("open the disktree window");++ // The treemap owns the keyboard from the first frame; there is no+ // text field to focus first.+ let _ = window.update(cx, |this, window, cx| {+ let focus = this.focus.clone();+ window.focus(&focus, cx);+ });+ cx.activate(true);+ });+ Ok(())+}++fn parse_args() -> Result<Args> {+ let mut root: Option<PathBuf> = None;+ let mut options = ScanOptions::default();+ let mut depth = 3_u32;+ let mut args = std::env::args().skip(1);++ while let Some(arg) = args.next() {+ match arg.as_str() {+ "-h" | "--help" => {+ println!("{USAGE}");+ std::process::exit(0);+ }+ "-a" | "--apparent-size" => options.apparent_size = true,+ "-l" | "--follow-links" => options.follow_links = true,+ "-H" | "--no-hidden" => options.include_hidden = false,+ "-x" | "--one-filesystem" => options.one_filesystem = true,+ "-d" | "--depth" => {+ let value = args.next().context("--depth needs a number")?;+ depth = value.parse().context("--depth needs a number")?;+ anyhow::ensure!(+ (1..=6).contains(&depth),+ "--depth must be 1 to 6"+ );+ }+ "--metric" => {+ let value = args.next().context("--metric needs a value")?;+ options.metric = match value.as_str() {+ "files" => disktree_core::tree::Metric::Files,+ "bytes" | "size" => disktree_core::tree::Metric::Bytes,+ other => anyhow::bail!(+ "unknown metric {other}; try bytes or files"+ ),+ };+ }+ other if other.starts_with('-') => {+ anyhow::bail!("unknown option {other}\n\n{USAGE}");+ }+ path => {+ anyhow::ensure!(root.is_none(), "only one path can be scanned");+ root = Some(PathBuf::from(path));+ }+ }+ }++ let root = match root {+ Some(root) => root,+ None => std::env::var_os("HOME")+ .map(PathBuf::from)+ .context("no path given and HOME is not set")?,+ };+ // 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.+ let metadata = std::fs::metadata(&root)+ .with_context(|| format!("cannot read {}", root.display()))?;+ anyhow::ensure!(metadata.is_dir(), "{} is not a directory", root.display());++ Ok(Args {+ root,+ options,+ depth: depth.clamp(1, 6),+ })+}diff --git a/crates/disktree-app/src/marks.rs b/crates/disktree-app/src/marks.rsnew file mode 100644index 0000000..51483ce--- /dev/null+++ b/crates/disktree-app/src/marks.rs@@ -0,0 +1,231 @@+//! The set of paths marked for removal.+//!+//! Marks are keyed by absolute path, not by tree position: the tree is+//! re-scanned after a removal, and a mark must survive that (or be reported as+//! gone) rather than silently pointing at a different node.++use std::path::{Path, PathBuf};++use disktree_core::removal::Target;+use disktree_core::tree::{Metric, Node};+use rustc_hash::FxHashSet;++/// Marked paths, in the order they were marked.+#[derive(Debug, Default)]+pub struct Marks {+ items: Vec<Target>,+ index: FxHashSet<PathBuf>,+}++impl Marks {+ pub fn contains(&self, path: &Path) -> bool {+ self.index.contains(path)+ }++ pub fn items(&self) -> &[Target] {+ &self.items+ }++ pub const fn len(&self) -> usize {+ self.items.len()+ }++ pub const fn is_empty(&self) -> bool {+ self.items.is_empty()+ }++ /// Mark `target`, or unmark it when it is already marked.+ ///+ /// Returns `true` when the path ended up marked.+ pub fn toggle(&mut self, target: Target) -> bool {+ if self.index.remove(&target.path) {+ self.items.retain(|item| item.path != target.path);+ false+ } else {+ self.index.insert(target.path.clone());+ self.items.push(target);+ true+ }+ }++ pub fn remove(&mut self, path: &Path) {+ if self.index.remove(path) {+ self.items.retain(|item| item.path != path);+ }+ }++ pub fn clear(&mut self) {+ self.items.clear();+ self.index.clear();+ }++ /// Re-read sizes from a freshly scanned tree and drop marks whose path no+ /// longer exists, so the tally never claims space that is already gone.+ pub fn refresh(&mut self, root_path: &Path, root: &Node, metric: Metric) {+ let mut resolved = Vec::with_capacity(self.items.len());+ for item in &self.items {+ match find(root_path, root, &item.path) {+ Some(node) => resolved.push(Target {+ bytes: node.value(metric),+ is_dir: node.is_dir(),+ hidden: is_hidden(&item.path),+ path: item.path.clone(),+ }),+ None => resolved.push(Target {+ bytes: 0,+ ..item.clone()+ }),+ }+ }+ self.items = resolved;+ }+}++/// Walk the tree to the node at an absolute path. Path components are compared+/// one at a time, so a name containing a path separator cannot confuse it.+pub fn find<'a>(+ root_path: &Path,+ root: &'a Node,+ path: &Path,+) -> Option<&'a Node> {+ let relative = path.strip_prefix(root_path).ok()?;+ let mut node = root;+ for component in relative.components() {+ let name = component.as_os_str().to_string_lossy();+ node = node+ .children+ .iter()+ .find(|child| child.name.as_ref() == name)?;+ }+ Some(node)+}++/// A dotfile or dot-directory by name.+pub fn is_hidden(path: &Path) -> bool {+ path.file_name()+ .is_some_and(|name| name.to_string_lossy().starts_with('.'))+}++/// Shorten a path for display: `~` for the home directory, and the path with+/// the home prefix replaced when it is below it.+pub fn display_path(path: &Path, home: Option<&Path>) -> String {+ match home+ .and_then(|home| path.strip_prefix(home).ok().map(|rest| (home, rest)))+ {+ Some((_, rest)) if rest.as_os_str().is_empty() => "~".to_string(),+ Some((_, rest)) => format!("~/{}", rest.display()),+ None => path.display().to_string(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use disktree_core::tree::{NodeKind, aggregate};++ fn file(name: &str, bytes: u64) -> Node {+ Node::entry(name, NodeKind::File, bytes)+ }++ fn tree() -> Node {+ let mut root = Node::directory("home");+ let mut cache = Node::directory(".cache");+ cache.children.push(file("blob.bin", 900));+ root.children.push(cache);+ root.children.push(file("notes.bin", 100));+ aggregate(&mut root, Metric::Bytes);+ root+ }++ fn target(path: &str, bytes: u64) -> Target {+ Target {+ path: PathBuf::from(path),+ bytes,+ is_dir: false,+ hidden: false,+ }+ }++ #[test]+ fn toggling_marks_and_unmarks() {+ let mut marks = Marks::default();+ assert!(marks.toggle(target("/home/tobi/a", 1)));+ assert!(marks.contains(Path::new("/home/tobi/a")));+ assert_eq!(marks.len(), 1);+ assert!(!marks.toggle(target("/home/tobi/a", 1)));+ assert!(marks.is_empty());+ }++ #[test]+ fn marking_the_same_path_twice_keeps_one_entry() {+ let mut marks = Marks::default();+ marks.toggle(target("/home/tobi/a", 1));+ marks.toggle(target("/home/tobi/a", 1));+ marks.toggle(target("/home/tobi/a", 1));+ assert_eq!(marks.len(), 1);+ }++ #[test]+ fn refresh_re_reads_sizes_from_a_new_tree() {+ let root_path = Path::new("/home/tobi");+ let root = tree();+ let mut marks = Marks::default();+ marks.toggle(target("/home/tobi/.cache", 0));+ marks.toggle(target("/home/tobi/gone", 500));++ marks.refresh(root_path, &root, Metric::Bytes);+ assert_eq!(marks.items()[0].bytes, 900);+ assert!(marks.items()[0].is_dir);+ assert!(marks.items()[0].hidden, "the .cache mark is hidden");+ assert_eq!(marks.items()[1].bytes, 0, "a path that no longer exists");+ }++ #[test]+ fn find_matches_whole_components_only() {+ let root = tree();+ assert!(+ find(+ Path::new("/home/tobi"),+ &root,+ Path::new("/home/tobi/.cache")+ )+ .is_some()+ );+ assert!(+ find(+ Path::new("/home/tobi"),+ &root,+ Path::new("/home/tobi/.cache/blob.bin")+ )+ .is_some()+ );+ assert!(+ find(+ Path::new("/home/tobi"),+ &root,+ Path::new("/home/tobi/cache")+ )+ .is_none()+ );+ assert!(+ find(+ Path::new("/elsewhere"),+ &root,+ Path::new("/home/tobi/notes.bin")+ )+ .is_none()+ );+ }++ #[test]+ fn display_path_shortens_the_home_prefix() {+ let home = Path::new("/home/tobi");+ assert_eq!(+ display_path(Path::new("/home/tobi/.cache/npm"), Some(home)),+ "~/.cache/npm"+ );+ assert_eq!(display_path(home, Some(home)), "~");+ assert_eq!(display_path(Path::new("/var/log"), Some(home)), "/var/log");+ assert_eq!(display_path(Path::new("/var/log"), None), "/var/log");+ }+}diff --git a/crates/disktree-app/src/palette.rs b/crates/disktree-app/src/palette.rsnew file mode 100644index 0000000..93f91a5--- /dev/null+++ b/crates/disktree-app/src/palette.rs@@ -0,0 +1,135 @@+//! Colours derived from the Omarchy theme.+//!+//! Nothing here invents a palette: every colour is the active theme's, shifted+//! in hue, lightness or alpha. That keeps the app inside Omarchy's visual+//! language across themes, and light and dark alike.++use gpui_kit::Hsla;+use gpui_kit::base::ThemeAppearance;+use gpui_omarchy::Theme;++/// Hue for a tile: nesting walks the wheel so levels are readable without+/// borders, and hidden entries get a hue of their own instead of a shade.+///+/// Hidden directories under a home directory are usually the largest thing+/// there — `~/.cache`, `~/.cargo`, `~/.local/share/Trash` — so they are marked+/// by colour rather than hidden away.+pub fn tile_hue(theme: &Theme, depth: u32, hidden: bool) -> f32 {+ let base = if hidden {+ theme.warning.h+ } else {+ theme.accent.h+ };+ wrap_hue((depth as f32).mul_add(0.075, base))+}++fn wrap_hue(hue: f32) -> f32 {+ let hue = hue % 1.0;+ if hue < 0.0 { hue + 1.0 } else { hue }+}++/// Fill for a tile at `depth`, as an opaque colour the mosaic can paint.+pub fn tile_fill(+ theme: &Theme,+ depth: u32,+ hidden: bool,+ marked: bool,+) -> Hsla {+ let dark = theme.appearance == ThemeAppearance::Dark;+ // Deeper levels lift slightly so nested tiles separate from their parent+ // without needing a border on every one of them.+ let lightness = if dark {+ (depth.min(4) as f32).mul_add(0.055, 0.20)+ } else {+ (depth.min(4) as f32).mul_add(-0.055, 0.86)+ };+ let saturation = if hidden { 0.55 } else { 0.42 };+ let fill = Hsla {+ h: tile_hue(theme, depth, hidden),+ s: saturation,+ l: lightness,+ a: 1.0,+ };+ // Keep the mosaic calm: pull it toward the theme background so the tile+ // colours read as tinted surfaces rather than a rainbow.+ let flattened = mix(fill, theme.background, 0.34);+ if marked {+ mix(flattened, theme.danger, 0.30)+ } else {+ flattened+ }+}++/// Linear interpolation between two colours in HSLA.+pub fn mix(from: Hsla, to: Hsla, t: f32) -> Hsla {+ let t = t.clamp(0.0, 1.0);+ let lerp = |a: f32, b: f32| (b - a).mul_add(t, a);+ Hsla {+ h: lerp(from.h, to.h),+ s: lerp(from.s, to.s),+ l: lerp(from.l, to.l),+ a: lerp(from.a, to.a),+ }+}++/// The colour of a tile's label on top of its fill.+pub fn label_color(theme: &Theme, depth: u32) -> Hsla {+ let dark = theme.appearance == ThemeAppearance::Dark;+ let base = if dark { theme.bright } else { theme.background };+ if depth == 0 { base } else { base.opacity(0.86) }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn theme(appearance: ThemeAppearance) -> Theme {+ let mut theme = Theme::tokyo_night();+ theme.appearance = appearance;+ theme+ }++ #[test]+ fn hidden_tiles_are_a_different_hue_from_visible_ones() {+ let theme = theme(ThemeAppearance::Dark);+ let visible = tile_fill(&theme, 0, false, false);+ let hidden = tile_fill(&theme, 0, true, false);+ assert!((visible.h - hidden.h).abs() > 0.02);+ assert!(visible.s > 0.0);+ }++ #[test]+ fn marking_shifts_a_tile_toward_the_danger_colour() {+ let theme = theme(ThemeAppearance::Dark);+ let plain = tile_fill(&theme, 1, false, false);+ let marked = tile_fill(&theme, 1, false, true);+ let plain_distance = (plain.h - theme.danger.h).abs();+ let marked_distance = (marked.h - theme.danger.h).abs();+ assert!(marked_distance < plain_distance);+ }++ #[test]+ fn light_and_dark_appearances_differ_in_lightness() {+ let dark = tile_fill(&theme(ThemeAppearance::Dark), 0, false, false);+ let light = tile_fill(&theme(ThemeAppearance::Light), 0, false, false);+ assert!(light.l > dark.l);+ }++ #[test]+ fn hue_stays_in_range_at_every_depth() {+ let theme = theme(ThemeAppearance::Dark);+ for depth in 0..12 {+ let hue = tile_hue(&theme, depth, false);+ assert!((0.0..1.0).contains(&hue), "depth {depth} gave {hue}");+ }+ }++ #[test]+ fn mix_clamps_its_parameter() {+ let theme = theme(ThemeAppearance::Dark);+ let clamped_low = mix(theme.background, theme.accent, -1.0).l;+ let clamped_high = mix(theme.background, theme.accent, 2.0).l;+ assert!((clamped_low - theme.background.l).abs() < f32::EPSILON);+ assert!((clamped_high - theme.accent.l).abs() < f32::EPSILON);+ }+}diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rsnew file mode 100644index 0000000..7bc9332--- /dev/null+++ b/crates/disktree-app/src/state.rs@@ -0,0 +1,2006 @@+//! Application state and every mutation the UI can perform.+//!+//! The screens in [`crate::views`] are pure functions of this state; all the+//! decisions — what is selected, what a mark means, what a key does, when to+//! re-scan — live here so they can be reasoned about in one place.++use std::cell::Cell;+use std::path::{Path, PathBuf};+use std::rc::Rc;+use std::time::{Duration, Instant};++use disktree_core::removal::{+ Plan, RemovalEvent, RemovalHandle, RemovalMode, Target, TrashBackend,+ detect_trash_backend, plan,+};+use disktree_core::scan::{ScanHandle, ScanOptions, ScanSnapshot};+use disktree_core::space::{SpaceInfo, space_info};+use disktree_core::tree::{Node, path_of};+use disktree_core::treemap::{+ LayoutOptions, Rect, Tile, TileKind, hit, layout,+};+use gpui_kit::{+ Context, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent,+ MouseMoveEvent, Pixels, Point, Render, ScrollDelta, ScrollWheelEvent, Size,+ Window, px, size,+};+use gpui_omarchy::Status;+use rustc_hash::FxHashSet;++use crate::marks::{Marks, display_path, is_hidden};+use crate::treemap_view::{Mosaic, TileDeco};++/// Which screen the app is showing.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum Screen {+ /// Walk the treemap and mark what should go.+ #[default]+ Explore,+ /// Review every marked path and choose how to remove them.+ Review,+ /// A removal is running.+ Running,+ /// The removal finished; show what happened.+ Done,+}++/// The treemap view transform: `screen = (base - origin) * scale`.+///+/// All viewport geometry stays in the base space of an unzoomed layout, so pan+/// and zoom never require a re-layout.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct View {+ pub scale: f32,+ pub origin_x: f32,+ pub origin_y: f32,+}++impl Default for View {+ fn default() -> Self {+ Self::IDENTITY+ }+}++impl View {+ pub const IDENTITY: Self = Self {+ scale: 1.0,+ origin_x: 0.0,+ origin_y: 0.0,+ };+ pub const MIN_SCALE: f32 = 1.0;+ /// Past this, zooming again descends into whatever is under the cursor+ /// instead of magnifying further: the continuous "keep zooming and you are+ /// inside" gesture, with a breadcrumb to walk back out.+ pub const MAX_SCALE: f32 = 5.0;++ pub fn project(&self, rect: Rect) -> Rect {+ Rect::new(+ (rect.x - self.origin_x) * self.scale,+ (rect.y - self.origin_y) * self.scale,+ rect.w * self.scale,+ rect.h * self.scale,+ )+ }++ /// Viewport point to base-space point.+ pub fn unproject(&self, x: f32, y: f32) -> (f32, f32) {+ (+ x / self.scale + self.origin_x,+ y / self.scale + self.origin_y,+ )+ }++ /// Zoom by `factor` toward `(x, y)` and no further than `ceiling`.+ ///+ /// The base point under `(x, y)` stays put, which is what makes a wheel+ /// zoom feel pointed at the tile rather than at the window.+ pub fn zoomed_at(&self, x: f32, y: f32, factor: f32, ceiling: f32) -> Self {+ let scale = (self.scale * factor).clamp(Self::MIN_SCALE, ceiling);+ let (base_x, base_y) = self.unproject(x, y);+ Self {+ scale,+ origin_x: base_x - x / scale,+ origin_y: base_y - y / scale,+ }+ }++ /// The scale at which `rect` exactly fits the viewport.+ pub fn fit_scale(rect: Rect, area: Size<Pixels>) -> f32 {+ let width = area.width.as_f32().max(1.0);+ let height = area.height.as_f32().max(1.0);+ if rect.w <= 0.0 || rect.h <= 0.0 {+ return Self::MIN_SCALE;+ }+ (width / rect.w).min(height / rect.h)+ }++ /// The region of the base layout the viewport currently shows.+ pub fn visible_base(&self, area: Size<Pixels>) -> Rect {+ let width = area.width.as_f32().max(1.0);+ let height = area.height.as_f32().max(1.0);+ Rect::new(+ self.origin_x,+ self.origin_y,+ width / self.scale,+ height / self.scale,+ )+ }++ /// Keep the viewport inside the layout: no empty margins, ever.+ pub fn clamped(self, area: Size<Pixels>) -> Self {+ let width = area.width.as_f32();+ let height = area.height.as_f32();+ let max_x = (width - width / self.scale).max(0.0);+ let max_y = (height - height / self.scale).max(0.0);+ Self {+ scale: self.scale,+ origin_x: self.origin_x.clamp(0.0, max_x),+ origin_y: self.origin_y.clamp(0.0, max_y),+ }+ }+}++/// A layout transition: the region the user is looking at, and where that same+/// region lands in the layout being switched to.+///+/// Every descending or ascending move is one region of the tree changing+/// address. Rather than moving a camera, each tile is drawn from where that+/// region *was* to where it *is*, so the tiles inside the directory that is+/// being entered grow into place and the ones being left slide out. That is+/// what makes "zoom in and descend" read as one motion: the newly visible+/// level is always larger than it was a moment ago, never smaller.+#[derive(Clone, Copy, Debug)]+pub struct LayoutTransition {+ /// The region in the old frame, in viewport coordinates.+ src: Rect,+ /// The same region in the new frame, in viewport coordinates.+ dst: Rect,+ started: Instant,+ duration: Duration,+}++impl LayoutTransition {+ fn new(src: Rect, dst: Rect) -> Self {+ // Longer pulls take a little longer, but never enough to feel slow.+ let ratio = if dst.w > 1.0 { src.w / dst.w } else { 1.0 };+ let magnitude = ratio.abs().max(1.0).log2().clamp(0.0, 4.0);+ Self {+ src,+ dst,+ started: Instant::now(),+ duration: Duration::from_millis(130 + (magnitude * 45.0) as u64),+ }+ }++ /// Where a rectangle in the new layout was, before the switch.+ fn origin_of(&self, rect: Rect) -> Rect {+ let scale = if self.dst.w > 0.0 {+ self.src.w / self.dst.w+ } else {+ 1.0+ };+ Rect::new(+ (rect.x - self.dst.x).mul_add(scale, self.src.x),+ (rect.y - self.dst.y).mul_add(scale, self.src.y),+ rect.w * scale,+ rect.h * scale,+ )+ }++ /// The rectangle to draw at this instant, and whether the transition is+ /// still running.+ fn sample(&self, rect: Rect) -> (Rect, bool) {+ let elapsed =+ self.started.elapsed().as_secs_f32() / self.duration.as_secs_f32();+ if elapsed >= 1.0 {+ return (rect, false);+ }+ let eased = 1.0 - (1.0 - elapsed).powi(3);+ let from = self.origin_of(rect);+ let lerp = |a: f32, b: f32| (b - a).mul_add(eased, a);+ (+ Rect::new(+ lerp(from.x, rect.x),+ lerp(from.y, rect.y),+ lerp(from.w, rect.w),+ lerp(from.h, rect.h),+ ),+ true,+ )+ }+}++/// Layout for one (crumbs, area, options) combination.+struct LayoutCache {+ key: LayoutKey,+ tiles: Vec<Tile>,+}++#[derive(Clone, PartialEq)]+struct LayoutKey {+ crumbs: Vec<usize>,+ width: f32,+ height: f32,+ options: LayoutOptions,+}++/// Result of the removal run, summarised for the final screen.+#[derive(Clone, Debug, Default)]+pub struct RunSummary {+ pub total: usize,+ pub removed: u64,+ pub bytes: u64,+ pub failed: usize,+}++/// Everything the app knows and everything it can do.+pub struct Disktree {+ /// The directory the tree was scanned from.+ pub root_path: PathBuf,+ pub home: Option<PathBuf>,+ pub options: ScanOptions,+ pub tree: Option<Rc<Node>>,+ pub scan: Option<ScanHandle>,+ pub scan_epoch: u64,+ pub progress: ScanSnapshot,+ pub scan_error: Option<String>,++ pub screen: Screen,+ /// Path from the scanned root to the directory currently drawn.+ pub crumbs: Vec<usize>,+ pub selected: Option<Vec<usize>>,+ pub hovered: Option<Vec<usize>>,+ /// 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.+ pub pointer_active: bool,+ pub view: View,+ /// The in-flight layout transition, if a level was just entered or left.+ pub transition: Option<LayoutTransition>,+ pub layout_options: LayoutOptions,+ cache: Option<LayoutCache>,++ /// Mouse position in treemap-local pixels, for hit-testing and the tooltip.+ pub pointer: Option<Point<Pixels>>,+ /// The treemap area in window space, recorded while painting.+ pub treemap_origin: Rc<Cell<Point<Pixels>>>,+ pub treemap_size: Rc<Cell<Size<Pixels>>>,++ pub marks: Marks,+ pub removal_mode: RemovalMode,+ pub trash_backend: TrashBackend,+ /// The permanent-deletion alert dialog is open. Trash needs no dialog: it+ /// is reversible, so it commits directly.+ pub confirm_open: bool,+ /// Focus owner for the alert dialog while it is open.+ pub confirm_focus: FocusHandle,+ /// Focus to move on the next occasion a window is in hand. Key handling+ /// has no window, and opening or closing the dialog must move focus.+ pub focus_request: Option<FocusTarget>,+ /// The window's `rem` in pixels, read each frame. The mosaic is laid out+ /// in pixels, so its header band and label thresholds are scaled by this+ /// to follow interface zoom like the rest of the interface.+ pub rem: f32,+ pub run: Option<RemovalHandle>,+ pub run_epoch: u64,+ pub run_summary: RunSummary,+ pub run_log: Vec<(PathBuf, Result<(), String>)>,+ pub space: Option<SpaceInfo>,+ /// Free space before the removal, for the honest "what did it actually+ /// free" number rather than the sum of what was marked.+ pub space_baseline: Option<SpaceInfo>,+ pub notice: Option<(String, Status)>,++ pub find: String,+ pub find_open: bool,+ pub show_help: bool,+ pub show_selection: bool,+ pub focus: FocusHandle,+}++impl Disktree {+ pub fn new(+ root_path: PathBuf,+ options: ScanOptions,+ depth: u32,+ cx: &mut Context<'_, Self>,+ ) -> Self {+ let home = std::env::var_os("HOME").map(PathBuf::from);+ let space = space_info(&root_path).ok();+ let trash_backend = detect_trash_backend();+ let mut tree = Self {+ root_path,+ home,+ options,+ tree: None,+ scan: None,+ scan_epoch: 0,+ progress: ScanSnapshot::default(),+ scan_error: None,+ screen: Screen::Explore,+ crumbs: Vec::new(),+ selected: None,+ hovered: None,+ pointer_active: false,+ view: View::default(),+ transition: None,+ layout_options: LayoutOptions {+ max_depth: depth.clamp(1, 6),+ ..LayoutOptions::default()+ },+ cache: None,+ pointer: None,+ treemap_origin: Rc::new(Cell::new(Point::new(px(0.), px(0.)))),+ treemap_size: Rc::new(Cell::new(size(px(0.), px(0.)))),+ marks: Marks::default(),+ // Reversible by default whenever this machine has a trash: the+ // permanent path stays one choice away, behind a dialog.+ removal_mode: if trash_backend.is_available() {+ RemovalMode::Trash+ } else {+ RemovalMode::Permanent+ },+ trash_backend,+ confirm_open: false,+ confirm_focus: cx.focus_handle(),+ focus_request: None,+ rem: crate::ui::BASE_REM,+ run: None,+ run_epoch: 0,+ run_summary: RunSummary::default(),+ run_log: Vec::new(),+ space,+ space_baseline: None,+ notice: None,+ find: String::new(),+ find_open: false,+ show_help: false,+ show_selection: true,+ focus: cx.focus_handle(),+ };+ tree.start_scan(cx);+ Self::start_space_ticker(cx);+ tree+ }++ /// Build a view over a tree that is already known.+ ///+ /// Mirrors [`Self::new`] without starting a walk, so a test can hand the+ /// screens a tree it already has instead of waiting on a real one. A+ /// feature that opens an archived scan would use this too.+ #[cfg(test)]+ pub fn with_tree(+ root_path: PathBuf,+ tree: Node,+ options: ScanOptions,+ depth: u32,+ cx: &mut Context<'_, Self>,+ ) -> 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.cache = None;+ app.select_largest(cx);+ app+ }++ /// Select the largest entry of the current root, so the selection line, the+ /// tooltip and the mark key all have something to act on from the first+ /// frame. The largest entry is also the answer to "what is eating my disk"+ /// most of the time.+ fn select_largest(&mut self, cx: &mut Context<'_, Self>) {+ if self.selected.is_some() {+ return;+ }+ if let Some(index) = self.current().and_then(Node::largest_child) {+ self.selected = Some(vec![index]);+ cx.notify();+ }+ }++ // ── scanning ────────────────────────────────────────────────────────++ /// Start a fresh scan, abandoning any walk still in progress.+ pub fn start_scan(&mut self, cx: &mut Context<'_, Self>) {+ 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.tree = None;+ self.crumbs.clear();+ self.selected = None;+ self.hovered = None;+ self.view = View::default();+ self.cache = None;+ self.scan = Some(ScanHandle::spawn(+ self.root_path.clone(),+ self.options.clone(),+ ));+ Self::poll_scan(epoch, cx);+ cx.notify();+ }++ fn poll_scan(epoch: u64, cx: &Context<'_, Self>) {+ cx.spawn(async move |this, cx| {+ loop {+ cx.background_executor()+ .timer(Duration::from_millis(110))+ .await;+ let keep_going = this+ .update(cx, |this, cx| this.poll_scan_once(epoch, cx))+ .unwrap_or(false);+ if !keep_going {+ break;+ }+ }+ })+ .detach();+ }++ /// Drain the scan channel once. Returns whether the poller should keep+ /// ticking. Driven by the poll task above, and by the tests, which cannot+ /// wait on the test clock while a real worker thread walks a directory.+ pub(crate) fn poll_scan_once(+ &mut self,+ epoch: u64,+ cx: &mut Context<'_, Self>,+ ) -> bool {+ if epoch != self.scan_epoch {+ return false;+ }+ let Some(scan) = &self.scan else {+ return false;+ };+ self.progress = scan.progress.snapshot();+ let Some(outcome) = scan.poll() else {+ cx.notify();+ return true;+ };+ match outcome {+ Ok(node) => {+ let metric = self.options.metric;+ self.marks.refresh(&self.root_path, &node, metric);+ self.tree = Some(Rc::new(node));+ self.cache = None;+ self.keep_selection_valid();+ self.select_largest(cx);+ }+ Err(error) => self.scan_error = Some(error.to_string()),+ }+ self.scan = None;+ self.progress.finished = true;+ cx.notify();+ false+ }++ fn keep_selection_valid(&mut self) {+ let Some(tree) = &self.tree else {+ return;+ };+ if tree.resolve(&self.crumbs).is_none() {+ self.crumbs.clear();+ }+ if let Some(selected) = self.selected.clone()+ && tree.resolve(&selected).is_none()+ {+ self.selected = None;+ }+ }++ /// Space changes under us all the time; poll it so the meter is live+ /// without repainting when nothing moved.+ fn start_space_ticker(cx: &Context<'_, Self>) {+ cx.spawn(async move |this, cx| {+ loop {+ let interval = this+ .update(cx, |this, _| {+ if this.screen == Screen::Running {+ Duration::from_millis(150)+ } else {+ Duration::from_millis(1200)+ }+ })+ .unwrap_or(Duration::from_millis(1200));+ cx.background_executor().timer(interval).await;+ let ok = this+ .update(cx, |this, cx| {+ let path = this.root_path.clone();+ let fresh = space_info(&path).ok();+ if fresh != this.space {+ this.space = fresh;+ cx.notify();+ }+ })+ .is_ok();+ if !ok {+ break;+ }+ }+ })+ .detach();+ }++ // ── navigation ──────────────────────────────────────────────────────++ pub fn tree(&self) -> Option<&Node> {+ self.tree.as_deref()+ }++ /// The node the treemap is currently rooted at.+ pub fn current(&self) -> Option<&Node> {+ self.tree+ .as_ref()+ .and_then(|tree| tree.resolve(&self.crumbs))+ }++ pub fn node_at(&self, crumbs: &[usize]) -> Option<&Node> {+ self.tree.as_ref().and_then(|tree| tree.resolve(crumbs))+ }++ pub fn path_at(&self, crumbs: &[usize]) -> Option<PathBuf> {+ let tree = self.tree.as_ref()?;+ Some(path_of(&self.root_path, tree, crumbs))+ }++ /// Path of the directory currently drawn.+ pub fn current_path(&self) -> PathBuf {+ self.path_at(&self.crumbs)+ .unwrap_or_else(|| self.root_path.clone())+ }++ /// 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(),+ )];+ let Some(tree) = &self.tree else {+ return trail;+ };+ let mut crumbs: Vec<usize> = Vec::new();+ for &index in &self.crumbs {+ let Some(node) =+ tree.resolve(&crumbs).and_then(|node| node.child(index))+ else {+ break;+ };+ crumbs.push(index);+ trail.push((node.name.to_string(), crumbs.clone()));+ }+ trail+ }++ /// Descend into the selected tile, or into the largest child of the+ /// current root when nothing is selected.+ pub fn descend(&mut self, cx: &mut Context<'_, Self>) {+ let target = match self.selected.clone() {+ // Enter what is selected, however deep: a directory opens itself,+ // a file opens the directory holding it.+ Some(selected) if selected.len() > self.crumbs.len() => {+ if self.node_at(&selected).is_some_and(Node::is_dir) {+ selected+ } else {+ selected[..selected.len() - 1].to_vec()+ }+ }+ // Nothing below the root is selected: the largest entry.+ _ => match self.current().and_then(Node::largest_child) {+ Some(index) => {+ let mut crumbs = self.crumbs.clone();+ crumbs.push(index);+ crumbs+ }+ None => return,+ },+ };+ let from = self.tile_body(&target).map(|rect| self.view.project(rect));+ self.enter(target, from, cx);+ }++ /// Go inside one child of the current root, so that it fills the viewport.+ ///+ /// `from` is where the child was on screen, when the caller knows it.+ /// Make `target` — any directory below the current root — the root.+ ///+ /// `from` is where that directory's contents were on screen, so the+ /// transition grows them from exactly there into the full viewport.+ fn enter(+ &mut self,+ target: Vec<usize>,+ from: Option<Rect>,+ cx: &mut Context<'_, Self>,+ ) {+ if target.len() <= self.crumbs.len()+ || !target.starts_with(&self.crumbs)+ {+ return;+ }+ let Some(node) = self.node_at(&target) else {+ return;+ };+ if !node.is_dir() || node.children.is_empty() {+ return;+ }+ self.selected = Some(target.clone());+ self.crumbs = target;+ self.forget_hover();+ self.cache = None;+ let area = self.treemap_size.get();+ let src = from.unwrap_or_else(|| self.view.visible_base(area));+ self.view = View::IDENTITY;+ let dst = Rect::new(+ 0.0,+ 0.0,+ area.width.as_f32().max(1.0),+ area.height.as_f32().max(1.0),+ );+ self.transition = Some(LayoutTransition::new(src, dst));+ cx.notify();+ }++ /// Where a drawn directory's contents sit: its tile below the name band.+ /// This, not the whole tile, is the region its children occupy, so it is+ /// what a transition into or out of it has to map.+ pub fn tile_body(&mut self, crumbs: &[usize]) -> Option<Rect> {+ let tile =+ self.layout()?.iter().find(|tile| tile.crumbs() == crumbs)?;+ Some(match tile.header {+ Some(header) => Rect::new(+ tile.rect.x,+ header.bottom(),+ tile.rect.w,+ tile.rect.bottom() - header.bottom(),+ ),+ None => tile.rect,+ })+ }++ /// The deepest drawn directory under a viewport point that has contents+ /// to show: what zooming at that point is zooming into.+ fn zoom_target(&mut self, x: f32, y: f32) -> Option<Vec<usize>> {+ let hovered = self.tile_at(x, y)?;+ let root = self.crumbs.len();+ (root + 1..=hovered.len())+ .rev()+ .map(|length| hovered[..length].to_vec())+ .find(|crumbs| {+ self.node_at(crumbs).is_some_and(|node| {+ node.is_dir() && !node.children.is_empty()+ }) && self.tile_body(crumbs).is_some()+ })+ }++ /// 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;+ };+ // 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.forget_hover();+ self.cache = None;+ self.selected = Some(parent_crumbs);+ self.view = View::IDENTITY;+ self.transition = self+ .tile_body(&child_crumbs)+ .filter(|rect| rect.w > 1.0 && rect.h > 1.0)+ .map(|dst| LayoutTransition::new(src, dst));+ cx.notify();+ }++ /// The crumbs of the parent of the current root, if any.+ pub fn parent_crumbs(&self) -> Option<Vec<usize>> {+ if self.crumbs.is_empty() {+ None+ } else {+ Some(self.crumbs[..self.crumbs.len() - 1].to_vec())+ }+ }++ /// Jump straight to a crumb from the breadcrumb bar.+ ///+ /// A jump can skip several levels, so there is no single region to move:+ /// it lands immediately, the way selecting a folder does.+ pub fn go_to(&mut self, crumbs: Vec<usize>, cx: &mut Context<'_, Self>) {+ self.crumbs.clone_from(&crumbs);+ self.selected = Some(crumbs);+ self.forget_hover();+ self.view = View::IDENTITY;+ self.transition = None;+ self.cache = None;+ cx.notify();+ }++ /// Select the tile at `crumbs` without changing the root.+ pub fn select(+ &mut self,+ crumbs: Option<Vec<usize>>,+ cx: &mut Context<'_, Self>,+ ) {+ self.selected = crumbs;+ cx.notify();+ }++ /// Move the selection geometrically, falling back to the parent at an edge.+ /// The tile a key acts on: under the pointer if the pointer moved last,+ /// otherwise the keyboard selection.+ pub fn action_target(&self) -> Option<Vec<usize>> {+ if self.pointer_active {+ self.hovered.clone().or_else(|| self.selected.clone())+ } else {+ self.selected.clone()+ }+ }++ /// Make the pointed-at tile the selection before a key acts, so marking,+ /// opening and arrow movement all start from what the user is looking at.+ fn adopt_pointer_target(&mut self) {+ if self.pointer_active+ && let Some(hovered) = self.hovered.clone()+ {+ self.selected = Some(hovered);+ }+ }++ /// After the layout changes under a still pointer, its hover is stale+ /// until the pointer moves again.+ fn forget_hover(&mut self) {+ self.hovered = None;+ self.pointer_active = false;+ }++ pub fn move_selection(+ &mut self,+ direction: Direction,+ cx: &mut Context<'_, Self>,+ ) {+ self.pointer_active = false;+ let area = self.treemap_size.get();+ let _ = area;+ let Some(tiles) = self.layout().map(<[Tile]>::to_vec) else {+ return;+ };+ let Some(current) = self.selected.clone() else {+ if let Some(first) = tiles.first() {+ let crumbs = first.crumbs().to_vec();+ self.select(Some(crumbs), cx);+ }+ return;+ };+ let Some(from) = tiles+ .iter()+ .find(|tile| tile.crumbs() == current.as_slice())+ .map(|tile| self.view.project(tile.rect))+ else {+ return;+ };++ // Same-depth neighbours only: stepping into a child by arrow key would+ // make the depth of the selection impossible to predict.+ let depth = current.len();+ let mut best: Option<(f32, Vec<usize>)> = None;+ for tile in &tiles {+ let crumbs = tile.crumbs();+ if crumbs.len() != depth || crumbs == current.as_slice() {+ continue;+ }+ let rect = self.view.project(tile.rect);+ let Some(gap) = direction.gap(&from, &rect) else {+ continue;+ };+ let offset = direction.offset(&from, &rect);+ let score = offset.mul_add(2.5, gap);+ if best.as_ref().is_none_or(|(existing, _)| score < *existing) {+ best = Some((score, crumbs.to_vec()));+ }+ }++ if let Some((_, crumbs)) = best {+ self.select(Some(crumbs), cx);+ } else if direction.is_backwards()+ && let Some(parent) = self.parent_crumbs()+ {+ self.select(Some(parent), cx);+ }+ }++ /// Select the next sibling by rank, which is next-largest by the active+ /// metric. Scanning a directory for space is exactly this walk.+ pub fn cycle_sibling(&mut self, step: isize, cx: &mut Context<'_, Self>) {+ self.pointer_active = false;+ let siblings = self.ranked_siblings();+ if siblings.is_empty() {+ return;+ }+ let current = self.selected.as_ref().and_then(|selected| {+ siblings+ .iter()+ .position(|crumbs| crumbs.as_slice() == selected.as_slice())+ });+ let next = match current {+ Some(index) => {+ let len = siblings.len().cast_signed();+ (((index.cast_signed() + step) % len + len) % len) as usize+ }+ None if step >= 0 => 0,+ None => siblings.len() - 1,+ };+ self.select(Some(siblings[next].clone()), cx);+ }++ fn ranked_siblings(&self) -> Vec<Vec<usize>> {+ let parent = self.selected.as_ref().map_or_else(+ || self.crumbs.clone(),+ |selected| {+ if selected.len() <= self.crumbs.len() {+ self.crumbs.clone()+ } else {+ selected[..selected.len() - 1].to_vec()+ }+ },+ );+ let Some(node) = self.node_at(&parent) else {+ return Vec::new();+ };+ (0..node.children.len())+ .map(|index| {+ let mut crumbs = parent.clone();+ crumbs.push(index);+ crumbs+ })+ .collect()+ }++ /// Mark or unmark the current selection.+ pub fn toggle_mark_selected(&mut self, cx: &mut Context<'_, Self>) {+ let Some(crumbs) = self.selected.clone() else {+ return;+ };+ if crumbs.is_empty() {+ self.notice = Some((+ "the scanned root cannot be removed; open a directory first"+ .into(),+ Status::Warning,+ ));+ cx.notify();+ return;+ }+ self.toggle_mark(&crumbs, cx);+ }++ pub fn toggle_mark(+ &mut self,+ crumbs: &[usize],+ cx: &mut Context<'_, Self>,+ ) {+ let Some(target) = self.target_at(crumbs) else {+ return;+ };+ let marked_now = self.marks.toggle(target);+ self.notice = None;+ if !marked_now {+ cx.notify();+ return;+ }+ // A mark inside something already marked is redundant, and saying so+ // now is friendlier than showing it as redundant on the review screen.+ let marked = self.marks.items().last().cloned();+ if let Some(marked) = marked+ && let Some(parent) = self.marks.items().iter().find(|item| {+ item.path != marked.path && marked.path.starts_with(&item.path)+ })+ {+ let parent = parent.path.clone();+ self.space_baseline = self.space_baseline.or(self.space);+ self.notice = Some((+ format!(+ "{} is already inside the marked {}",+ display_path(&marked.path, self.home.as_deref()),+ display_path(&parent, self.home.as_deref())+ ),+ Status::Warning,+ ));+ }+ cx.notify();+ }++ pub fn target_at(&self, crumbs: &[usize]) -> Option<Target> {+ let node = self.node_at(crumbs)?;+ let path = self.path_at(crumbs)?;+ Some(Target {+ hidden: is_hidden(&path),+ path,+ bytes: node.value(self.options.metric),+ is_dir: node.is_dir(),+ })+ }++ pub fn unmark(&mut self, path: &Path, cx: &mut Context<'_, Self>) {+ self.marks.remove(path);+ cx.notify();+ }++ pub fn clear_marks(&mut self, cx: &mut Context<'_, Self>) {+ self.marks.clear();+ self.notice = None;+ cx.notify();+ }++ /// The plan the review screen shows and the removal runs.+ pub fn plan(&self) -> Plan {+ plan(self.marks.items(), &self.root_path)+ }++ // ── layout and hit-testing ──────────────────────────────────────────++ /// Resolve everything the mosaic needs for this frame.+ ///+ /// Runs once per render, before the paint callbacks: painting then only has+ /// to draw, and the marked/hidden/selected state of every tile is decided+ /// here, where the tree and the marks are both at hand.+ pub fn prepare(&mut self) -> Mosaic {+ let metric = self.options.metric;+ let view = self.view;+ let hovered = self.hovered.clone();+ let selected = self.selected.clone();++ // Marks are paths; the mosaic thinks in crumbs. Resolve once per frame+ // rather than building a path for every tile.+ let mut marked: FxHashSet<Vec<usize>> = FxHashSet::default();+ for item in self.marks.items() {+ if let Some(crumbs) = self.crumbs_for_path(&item.path) {+ marked.insert(crumbs);+ }+ }+ let mut covered: FxHashSet<Vec<usize>> = FxHashSet::default();+ for crumbs in &marked {+ if (1..crumbs.len())+ .any(|length| marked.contains(&crumbs[..length]))+ {+ covered.insert(crumbs.clone());+ }+ }++ let Some(tiles) = self.layout().map(<[Tile]>::to_vec) else {+ return Mosaic {+ view,+ ..Mosaic::default()+ };+ };++ // Colours are keyed to depth-from-the-scanned-root, not depth-from-this+ // view: the layout root is re-based every time the view descends, so a+ // view-relative key would recolour every tile as you walk in. The view+ // root's own absolute depth is the breadcrumb count.+ let base_depth = u32::try_from(self.crumbs.len()).unwrap_or(u32::MAX);+ let mut decorations = Vec::with_capacity(tiles.len());+ let mut labels = Vec::new();+ for tile in &tiles {+ let crumbs = tile.crumbs();+ let hidden = self.crumbs_are_hidden(crumbs);+ let is_marked = marked.contains(crumbs);+ let is_covered = covered.contains(crumbs);+ decorations.push(TileDeco {+ rect: self.animated_rect(tile.rect),+ header: tile.header.map(|header| self.animated_rect(header)),+ depth: tile.depth,+ color_depth: base_depth.saturating_add(tile.depth),+ hidden,+ marked: is_marked,+ covered: is_covered,+ hovered: hovered.as_deref() == Some(crumbs),+ selected: selected.as_deref() == Some(crumbs),+ });++ // Labels are chosen in screen space: zooming in makes room for more+ // of them, which is the point of zooming in.+ let drawn = self.animated_rect(tile.rect);+ let screen = view.project(+ tile.header+ .map_or(drawn, |header| self.animated_rect(header)),+ );+ if screen.w < LABEL_MIN_W_REMS * self.rem+ || screen.h < LABEL_MIN_H_REMS * self.rem+ {+ continue;+ }+ match &tile.kind {+ TileKind::Node { crumbs } => {+ let Some(node) = self.node_at(crumbs) else {+ continue;+ };+ labels.push(Label {+ text: node.name.to_string(),+ rect: self.animated_rect(tile.rect),+ header: tile+ .header+ .map(|header| self.animated_rect(header)),+ color_depth: base_depth.saturating_add(tile.depth),+ marked: is_marked || is_covered,+ size_text: crate::widgets::short_value(node, metric),+ });+ }+ TileKind::Others { count, .. } => labels.push(Label {+ text: format!("+{count} more"),+ rect: self.animated_rect(tile.rect),+ header: None,+ color_depth: base_depth.saturating_add(tile.depth),+ marked: false,+ size_text: String::new(),+ }),+ }+ }++ labels.sort_by(|left, right| {+ let left_area = left.rect.w * left.rect.h;+ let right_area = right.rect.w * right.rect.h;+ right_area.total_cmp(&left_area)+ });+ labels.truncate(MAX_LABELS);++ Mosaic {+ tiles: decorations,+ labels,+ view,+ }+ }++ /// Crumbs for an absolute path, if the tree still contains it.+ #[allow(+ clippy::unnecessary_wraps,+ reason = "a marked path may have been removed from the tree already"+ )]+ pub fn crumbs_for_path(&self, path: &Path) -> Option<Vec<usize>> {+ // The path is relative to the scanned root, so the walk starts there,+ // not at the directory currently drawn.+ let relative = path.strip_prefix(&self.root_path).ok()?;+ let tree = self.tree.clone()?;+ let mut node: &Node = &tree;+ let mut crumbs = Vec::new();+ for component in relative.components() {+ let name = component.as_os_str().to_string_lossy();+ let index = node+ .children+ .iter()+ .position(|child| child.name.as_ref() == name)?;+ crumbs.push(index);+ node = node.child(index)?;+ }+ Some(crumbs)+ }++ /// Whether any component of the path to `crumbs` is a dotfile.+ fn crumbs_are_hidden(&self, crumbs: &[usize]) -> bool {+ let Some(tree) = &self.tree else {+ return false;+ };+ tree.resolve_chain(crumbs)+ .iter()+ .any(|node| node.name.starts_with('.'))+ }++ /// Tiles for the current root and viewport size, computed once per change.+ pub fn layout(&mut self) -> Option<&[Tile]> {+ // A 17 px band at the default rem, scaled so zoom keeps the band's+ // relationship to the label inside it.+ self.layout_options.header = HEADER_REMS * self.rem;+ 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(),+ };+ if key.width < 1.0 || key.height < 1.0 {+ return None;+ }+ let stale = self.cache.as_ref().is_none_or(|cache| cache.key != key);+ if stale {+ 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(+ node,+ &key.crumbs,+ rect,+ self.options.metric,+ &key.options,+ );+ self.cache = Some(LayoutCache { key, tiles });+ }+ self.cache.as_ref().map(|cache| cache.tiles.as_slice())+ }++ /// Base-space rect of the tile at `crumbs`, if it is currently drawn.+ #[cfg(test)]+ pub fn tile_rect(&mut self, crumbs: &[usize]) -> Option<Rect> {+ self.layout()?+ .iter()+ .find(|tile| tile.crumbs() == crumbs)+ .map(|tile| tile.rect)+ }++ /// The deepest tile under a viewport point.+ pub fn tile_at(&mut self, x: f32, y: f32) -> Option<Vec<usize>> {+ let (base_x, base_y) = self.view.unproject(x, y);+ let tiles = self.layout()?;+ hit(tiles, base_x, base_y).map(|tile| tile.crumbs().to_vec())+ }++ // ── view ────────────────────────────────────────────────────────────++ /// Zoom toward a point.+ ///+ /// When `descend` is set the wheel stops magnifying at the point where the+ /// directory under the pointer exactly fits the viewport, and the next+ /// notch goes inside it. That ceiling is what keeps the two gestures+ /// continuous: at the moment the level changes, the tiles inside the+ /// directory are already as large as they will be, so entering makes them+ /// grow rather than shrink.+ pub fn zoom_at(+ &mut self,+ x: f32,+ y: f32,+ factor: f32,+ descend: bool,+ cx: &mut Context<'_, Self>,+ ) {+ let area = self.treemap_size.get();++ // At the bottom of the zoom, zooming out goes up a level.+ if factor < 1.0 && self.view.scale <= View::MIN_SCALE + f32::EPSILON {+ if descend {+ self.ascend(cx);+ }+ return;+ }++ // One directory decides both how far the wheel magnifies and where it+ // then goes: the deepest one under the pointer. At the ceiling its+ // contents fill the view, so going inside continues the same motion.+ let target = if descend {+ self.zoom_target(x, y)+ } else {+ None+ };+ let body = target.as_ref().and_then(|crumbs| self.tile_body(crumbs));+ let ceiling = body+ .map_or(View::MAX_SCALE, |rect| View::fit_scale(rect, area))+ .clamp(View::MIN_SCALE, View::MAX_SCALE);++ if factor > 1.0+ && self.view.scale >= ceiling - f32::EPSILON+ && let Some(target) = target+ {+ let from = body.map(|rect| self.view.project(rect));+ self.enter(target, from, cx);+ return;+ }++ self.view = self.view.zoomed_at(x, y, factor, ceiling).clamped(area);+ cx.notify();+ }++ pub fn reset_view(&mut self, cx: &mut Context<'_, Self>) {+ self.view = View::default();+ cx.notify();+ }++ /// Change how many levels are drawn, which is the other meaning of zoom in+ /// a treemap: seeing further in without changing what is on screen.+ pub fn adjust_depth(&mut self, step: i32, cx: &mut Context<'_, Self>) {+ let depth = (self.layout_options.max_depth.cast_signed() + step)+ .clamp(1, 6) as u32;+ self.layout_options.max_depth = depth;+ self.cache = None;+ cx.notify();+ }++ pub fn toggle_metric(&mut self, cx: &mut Context<'_, Self>) {+ self.options.metric = self.options.metric.toggled();+ 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));+ let metric = self.options.metric;+ self.marks.refresh(+ &self.root_path,+ self.tree.as_ref().unwrap(),+ metric,+ );+ }+ self.cache = None;+ cx.notify();+ }++ // ── removal ─────────────────────────────────────────────────────────++ /// The review screen's commit: move to the trash at once, or ask first for+ /// a permanent deletion, which cannot be undone.+ pub fn commit(&mut self, cx: &mut Context<'_, Self>) {+ if self.plan().is_empty() {+ return;+ }+ match self.removal_mode {+ RemovalMode::Trash => self.begin_removal(cx),+ RemovalMode::Permanent => {+ self.confirm_open = true;+ self.focus_request = Some(FocusTarget::Dialog);+ cx.notify();+ }+ }+ }++ /// The alert dialog's `Delete`.+ pub fn confirm_delete(&mut self, cx: &mut Context<'_, Self>) {+ self.confirm_open = false;+ self.focus_request = Some(FocusTarget::Root);+ self.begin_removal(cx);+ }++ /// The alert dialog's `Cancel`, or Escape.+ pub fn cancel_delete(&mut self, cx: &mut Context<'_, Self>) {+ self.confirm_open = false;+ self.focus_request = Some(FocusTarget::Root);+ cx.notify();+ }++ /// Move focus if something asked for it. Called wherever a window is in+ /// hand: the key listener and the click listeners.+ pub fn apply_focus(+ &mut self,+ window: &mut Window,+ cx: &mut Context<'_, Self>,+ ) {+ match self.focus_request.take() {+ Some(FocusTarget::Root) => window.focus(&self.focus, cx),+ Some(FocusTarget::Dialog) => window.focus(&self.confirm_focus, cx),+ None => {}+ }+ }++ /// `ctrl =`, `ctrl -` and `ctrl 0`: interface zoom. Changes the window's+ /// `rem`, which every size in this app is expressed in, so hierarchy and+ /// spacing keep their proportions at every step.+ pub fn zoom_interface(+ &mut self,+ event: &KeyDownEvent,+ window: &mut Window,+ ) -> bool {+ let keystroke = &event.keystroke;+ if !(keystroke.modifiers.control || keystroke.modifiers.platform) {+ return false;+ }+ let steps = crate::ui::ZOOM_STEPS;+ let current = window.rem_size().as_f32() / crate::ui::BASE_REM;+ let index = steps+ .iter()+ .position(|step| (step - current).abs() < 0.01)+ .unwrap_or(2);+ let next = match keystroke.key.as_str() {+ "=" | "+" => (index + 1).min(steps.len() - 1),+ "-" => index.saturating_sub(1),+ "0" => 2,+ _ => return false,+ };+ window.set_rem_size(px(crate::ui::BASE_REM * steps[next]));+ self.cache = None;+ true+ }++ pub fn begin_removal(&mut self, cx: &mut Context<'_, Self>) {+ let plan = self.plan();+ if plan.is_empty() {+ self.notice = Some(("nothing is marked".into(), Status::Warning));+ cx.notify();+ return;+ }+ self.space_baseline = self.space.or(self.space_baseline);+ self.run_epoch += 1;+ let epoch = self.run_epoch;+ self.run_summary = RunSummary {+ total: plan.targets.len(),+ ..RunSummary::default()+ };+ self.run_log.clear();+ self.screen = Screen::Running;+ self.run = Some(disktree_core::removal::spawn(plan, self.removal_mode));+ Self::poll_removal(epoch, cx);+ cx.notify();+ }++ fn poll_removal(epoch: u64, cx: &Context<'_, Self>) {+ cx.spawn(async move |this, cx| {+ loop {+ cx.background_executor()+ .timer(Duration::from_millis(60))+ .await;+ let keep_going = this+ .update(cx, |this, cx| this.poll_removal_once(epoch, cx))+ .unwrap_or(false);+ if !keep_going {+ break;+ }+ }+ })+ .detach();+ }++ /// Drain the removal channel once. Returns whether the run should keep+ /// being polled. Driven by the poll task above, and by the tests, which+ /// cannot wait on the test clock while a real worker thread runs.+ pub(crate) fn poll_removal_once(+ &mut self,+ epoch: u64,+ cx: &mut Context<'_, Self>,+ ) -> bool {+ if epoch != self.run_epoch {+ return false;+ }+ let Some(run) = &self.run else {+ return false;+ };+ let mut finished = false;+ while let Some(event) = run.poll() {+ match event {+ RemovalEvent::Start { total } => self.run_summary.total = total,+ RemovalEvent::Item {+ path,+ bytes,+ outcome,+ } => {+ if outcome.is_ok() {+ self.run_summary.removed += 1;+ self.run_summary.bytes += bytes;+ } else {+ self.run_summary.failed += 1;+ }+ self.run_log.push((path, outcome));+ }+ RemovalEvent::Done {+ removed,+ bytes,+ failed,+ } => {+ self.run_summary.removed = removed;+ self.run_summary.bytes = bytes;+ self.run_summary.failed = failed;+ finished = true;+ }+ }+ }+ if finished {+ self.run = None;+ self.marks.clear();+ self.screen = Screen::Done;+ // The tree on screen is now wrong; start over rather than leaving+ // numbers that include what was just removed.+ self.start_scan(cx);+ }+ cx.notify();+ !finished+ }++ /// 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() {+ return;+ }+ let Some(tree) = self.tree.clone() else {+ return;+ };+ let Some((crumbs, _)) = tree.find(&needle) else {+ self.notice =+ Some((format!("no entry matches {needle}"), Status::Warning));+ cx.notify();+ return;+ };+ let parent = crumbs[..crumbs.len().saturating_sub(1)].to_vec();+ self.go_to(parent, cx);+ self.selected = Some(crumbs);+ self.notice = None;+ cx.notify();+ }++ // ── input ───────────────────────────────────────────────────────────++ /// Handle a key press. Returns whether the directory on screen changed,+ /// which is what keeps the window title honest.+ pub fn on_key_down(+ &mut self,+ event: &KeyDownEvent,+ cx: &mut Context<'_, Self>,+ ) -> bool {+ let before = self.crumbs.clone();+ self.dispatch_key(event, cx);+ self.crumbs != before+ }++ /// Every binding, in reading order of the hint bar, so the keys and the+ /// documented list cannot drift apart.+ fn dispatch_key(+ &mut self,+ event: &KeyDownEvent,+ cx: &mut Context<'_, Self>,+ ) {+ let key = event.keystroke.key.as_str();+ let control = event.keystroke.modifiers.control;+ let shift = event.keystroke.modifiers.shift;++ // 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.+ if self.confirm_open {+ return;+ }++ if self.show_help {+ if matches!(key, "escape" | "?" | "/" | "q") {+ self.show_help = false;+ cx.notify();+ }+ return;+ }++ // The search field takes the keyboard while it is open. It is a field+ // of three keys on purpose: no editor state to keep in sync with the+ // 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);+ }+ "backspace" => {+ self.find.pop();+ }+ _ => {+ // Some platforms report only `key` for a character and+ // leave `key_char` empty; a one-character key is a+ // character either way.+ let typed = event+ .keystroke+ .key_char+ .as_deref()+ .unwrap_or(event.keystroke.key.as_str());+ if !control && typed.chars().count() == 1 {+ self.find.push_str(typed);+ }+ }+ }+ cx.notify();+ return;+ }++ match self.screen {+ Screen::Explore => self.on_explore_key(key, control, shift, cx),+ Screen::Review => self.on_review_key(key, cx),+ Screen::Running => {+ if key == "escape"+ && let Some(run) = &self.run+ {+ run.cancel();+ self.notice = Some((+ "stopping after the current item".into(),+ Status::Warning,+ ));+ cx.notify();+ }+ }+ Screen::Done => {+ if matches!(key, "escape" | "enter") {+ self.screen = Screen::Explore;+ cx.notify();+ }+ }+ }+ }++ fn on_explore_key(+ &mut self,+ key: &str,+ control: bool,+ shift: bool,+ cx: &mut Context<'_, Self>,+ ) {+ // Keys that act on "the current tile" start from the pointer when it+ // moved last.+ if matches!(+ key,+ "space"+ | "x"+ | "enter"+ | "tab"+ | "left"+ | "right"+ | "up"+ | "down"+ | "h"+ | "j"+ | "k"+ | "l"+ ) {+ self.adopt_pointer_target();+ }+ match key {+ "/" | "s" if !control => {+ self.find_open = true;+ cx.notify();+ }+ "enter" => self.descend(cx),+ "right" | "l" if !control => {+ self.move_selection(Direction::Right, cx);+ }+ "left" | "h" if !control => {+ self.move_selection(Direction::Left, cx);+ }+ "up" | "k" if !control => self.move_selection(Direction::Up, cx),+ "down" | "j" if !control => {+ self.move_selection(Direction::Down, cx);+ }+ "backspace" | "u" if !control => self.ascend(cx),+ "escape" => {+ if self.selected.is_some() {+ self.selected = None;+ } else {+ self.ascend(cx);+ }+ cx.notify();+ }+ "space" => self.toggle_mark_selected(cx),+ "x" if !control => self.toggle_mark_selected(cx),+ "tab" => self.cycle_sibling(if shift { -1 } else { 1 }, cx),+ "c" if !control => {+ if self.marks.is_empty() {+ self.notice = Some((+ "mark something first: space marks the selected tile"+ .into(),+ Status::Warning,+ ));+ } else {+ self.screen = Screen::Review;+ }+ cx.notify();+ }+ "[" => self.adjust_depth(-1, cx),+ "]" => self.adjust_depth(1, cx),+ "-" => {+ self.zoom_at(+ self.half_width(),+ self.half_height(),+ 1.0 / 1.25,+ false,+ cx,+ );+ }+ "=" | "+" => {+ self.zoom_at(+ self.half_width(),+ self.half_height(),+ 1.25,+ false,+ cx,+ );+ }+ "0" => self.reset_view(cx),+ "t" if !control => self.toggle_metric(cx),+ "r" if !control => self.start_scan(cx),+ "i" if !control => {+ self.options.include_hidden = !self.options.include_hidden;+ self.start_scan(cx);+ }+ "d" if !control => {+ self.options.apparent_size = !self.options.apparent_size;+ self.start_scan(cx);+ }+ "p" if !control => {+ self.show_selection = !self.show_selection;+ cx.notify();+ }+ "?" => {+ self.show_help = true;+ cx.notify();+ }+ "q" if !control => cx.quit(),+ _ => {}+ }+ }++ fn on_review_key(&mut self, key: &str, cx: &mut Context<'_, Self>) {+ match key {+ "escape" => {+ self.screen = Screen::Explore;+ cx.notify();+ }+ "enter" => self.commit(cx),+ "!" => self.clear_marks(cx),+ "p" => {+ self.removal_mode = RemovalMode::Permanent;+ cx.notify();+ }+ "m" => {+ self.removal_mode = RemovalMode::Trash;+ cx.notify();+ }+ "?" => {+ self.show_help = true;+ cx.notify();+ }+ _ => {}+ }+ }++ fn half_width(&self) -> f32 {+ self.treemap_size.get().width.as_f32() / 2.0+ }++ fn half_height(&self) -> f32 {+ self.treemap_size.get().height.as_f32() / 2.0+ }++ /// Mouse moved over the treemap.+ pub fn on_mouse_move(+ &mut self,+ event: &MouseMoveEvent,+ cx: &mut Context<'_, Self>,+ ) {+ let origin = self.treemap_origin.get();+ let local = Point::new(+ event.position.x - origin.x,+ event.position.y - origin.y,+ );+ self.pointer = Some(local);+ self.pointer_active = true;+ let previous = self.hovered.clone();+ self.hovered = self.tile_at(local.x.as_f32(), local.y.as_f32());+ // The cursor tooltip is positioned from `pointer`, so a move *within*+ // one tile still has to repaint — otherwise the tooltip sticks where+ // the tile was first entered until the hover target changes.+ if self.hovered != previous || self.hovered.is_some() {+ cx.notify();+ }+ }++ pub fn on_mouse_leave(&mut self, cx: &mut Context<'_, Self>) {+ self.pointer = None;+ self.pointer_active = false;+ if self.hovered.take().is_some() {+ cx.notify();+ }+ }++ /// Click: select, then act on a repeat click, like a file manager.+ pub fn on_mouse_down(+ &mut self,+ event: &MouseDownEvent,+ cx: &mut Context<'_, Self>,+ ) {+ let origin = self.treemap_origin.get();+ let x = (event.position.x - origin.x).as_f32();+ let y = (event.position.y - origin.y).as_f32();+ let crumbs = self.tile_at(x, y);++ match event.button {+ MouseButton::Left if event.click_count >= 2 => {+ if let Some(crumbs) = crumbs {+ self.select(Some(crumbs), cx);+ self.descend(cx);+ }+ }+ MouseButton::Left+ if event.modifiers.control || event.modifiers.platform =>+ {+ if let Some(crumbs) = crumbs {+ self.toggle_mark(&crumbs, cx);+ }+ }+ MouseButton::Left => {+ let activate = crumbs.as_ref().is_some_and(|crumbs| {+ self.selected.as_ref() == Some(crumbs)+ && self.node_at(crumbs).is_some_and(Node::is_dir)+ });+ if activate {+ // A second click on the selection opens it, like a file+ // manager, without needing a double click.+ self.descend(cx);+ return;+ }+ self.select(crumbs, cx);+ }+ MouseButton::Middle => {+ if let Some(crumbs) = crumbs {+ self.toggle_mark(&crumbs, cx);+ }+ }+ _ => {}+ }+ }++ pub fn on_scroll_wheel(+ &mut self,+ event: &ScrollWheelEvent,+ cx: &mut Context<'_, Self>,+ ) {+ let origin = self.treemap_origin.get();+ let x = (event.position.x - origin.x).as_f32();+ let y = (event.position.y - origin.y).as_f32();+ let lines = match event.delta {+ ScrollDelta::Lines(delta) => delta.y,+ ScrollDelta::Pixels(delta) => delta.y.as_f32() / 24.0,+ };+ if lines.abs() < f32::EPSILON {+ return;+ }+ if event.modifiers.shift {+ // Pan instead of zoom, for looking around a magnified view.+ self.view.origin_y =+ (self.view.origin_y - lines * 40.0 / self.view.scale).max(0.0);+ cx.notify();+ return;+ }+ let factor = if lines > 0.0 { 1.15 } else { 1.0 / 1.15 };+ self.zoom_at(x, y, factor, true, cx);+ }++ /// Advance the layout transition, if one is running.+ pub fn tick_transition(&mut self, window: &Window) {+ if let Some(transition) = self.transition {+ let (_, running) = transition.sample(Rect::default());+ if running {+ window.request_animation_frame();+ } else {+ self.transition = None;+ }+ }+ }++ /// A tile's rectangle for this frame: mid-transition it is on its way from+ /// where it was to where it is.+ fn animated_rect(&self, rect: Rect) -> Rect {+ match self.transition {+ Some(transition) => transition.sample(rect).0,+ None => rect,+ }+ }+}++/// A direction for geometric selection movement.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Direction {+ Left,+ Right,+ Up,+ Down,+}++impl Direction {+ const fn is_backwards(self) -> bool {+ matches!(self, Self::Left | Self::Up)+ }++ /// Distance from `from` to `rect` along the axis, if `rect` lies that way.+ fn gap(self, from: &Rect, rect: &Rect) -> Option<f32> {+ let epsilon = 0.5;+ match self {+ Self::Right => {+ let gap = rect.x - from.right();+ (gap >= -epsilon).then_some(gap.max(0.0))+ }+ Self::Left => {+ let gap = from.x - rect.right();+ (gap >= -epsilon).then_some(gap.max(0.0))+ }+ Self::Down => {+ let gap = rect.y - from.bottom();+ (gap >= -epsilon).then_some(gap.max(0.0))+ }+ Self::Up => {+ let gap = from.y - rect.bottom();+ (gap >= -epsilon).then_some(gap.max(0.0))+ }+ }+ }++ /// How far off the direction's axis `rect` sits, so the nearest tile in the+ /// direction wins rather than any tile in that half-plane.+ fn offset(self, from: &Rect, rect: &Rect) -> f32 {+ let overlap =+ |a_start: f32, a_end: f32, b_start: f32, b_end: f32| -> f32 {+ (a_end.min(b_end) - a_start.max(b_start)).max(0.0)+ };+ match self {+ Self::Left | Self::Right => {+ let shared =+ overlap(from.y, from.bottom(), rect.y, rect.bottom());+ (from.h.min(rect.h) - shared).max(0.0)+ }+ Self::Up | Self::Down => {+ let shared =+ overlap(from.x, from.right(), rect.x, rect.right());+ (from.w.min(rect.w) - shared).max(0.0)+ }+ }+ }+}++/// A tile's label, resolved for painting.+#[derive(Clone, Debug)]+pub struct Label {+ pub text: String,+ /// Base-space rectangle; the view transform is applied while painting.+ pub rect: Rect,+ /// The band this label belongs in, when its tile reserved one. A parent's+ /// name goes in its own band, never over its children.+ pub header: Option<Rect>,+ /// Depth from the scanned root, used for the colour so it does not shift+ /// when the view descends.+ pub color_depth: u32,+ pub marked: bool,+ pub size_text: String,+}++/// How many labels one frame will shape.+const MAX_LABELS: usize = 150;++/// Height of a directory's name band, in rem.+const HEADER_REMS: f32 = 1.0625;++/// Smallest tile, in rem, that gets a label: below this a name cannot be read.+const LABEL_MIN_W_REMS: f32 = 3.375;+const LABEL_MIN_H_REMS: f32 = 0.9375;++/// Where keyboard focus should go once a window is available.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum FocusTarget {+ /// The treemap and screens, which own every key binding.+ Root,+ /// The permanent-deletion alert dialog.+ Dialog,+}++impl Render for Disktree {+ fn render(+ &mut self,+ window: &mut Window,+ cx: &mut Context<'_, Self>,+ ) -> impl gpui_kit::IntoElement {+ self.rem = window.rem_size().as_f32();+ self.tick_transition(window);+ crate::views::root(self, window, cx)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn view() -> View {+ View {+ scale: 2.0,+ origin_x: 100.0,+ origin_y: 50.0,+ }+ }++ #[test]+ fn projecting_and_unprojecting_are_inverses() {+ let view = view();+ let (x, y) = view.unproject(400.0, 300.0);+ let rect = Rect::new(x, y, 10.0, 10.0);+ let screen = view.project(rect);+ assert!((screen.x - 400.0).abs() < 0.001);+ assert!((screen.y - 300.0).abs() < 0.001);+ assert!((screen.w - 20.0).abs() < 0.001);+ }++ #[test]+ fn zooming_keeps_the_point_under_the_cursor_still() {+ let view = View::IDENTITY;+ let (before_x, before_y) = view.unproject(300.0, 200.0);+ let zoomed = view.zoomed_at(300.0, 200.0, 2.0, View::MAX_SCALE);+ let rect = Rect::new(before_x, before_y, 1.0, 1.0);+ let screen = zoomed.project(rect);+ assert!((screen.x - 300.0).abs() < 0.01, "{screen:?}");+ assert!((screen.y - 200.0).abs() < 0.01, "{screen:?}");+ }++ #[test]+ fn clamping_never_leaves_a_margin() {+ let area = size(px(800.), px(600.));+ let clamped = View {+ scale: 2.0,+ origin_x: -500.0,+ origin_y: 900.0,+ }+ .clamped(area);+ assert!(clamped.origin_x.abs() < f32::EPSILON);+ assert!((clamped.origin_y - 300.0).abs() < f32::EPSILON);++ let identity = View {+ scale: 1.0,+ origin_x: 40.0,+ origin_y: 40.0,+ }+ .clamped(area);+ assert!(identity.origin_x.abs() < f32::EPSILON);+ assert!(identity.origin_y.abs() < f32::EPSILON);+ }++ #[test]+ fn a_transition_starts_where_the_region_was_and_ends_where_it_is() {+ // A region that occupied the whole viewport, landing in the top-left+ // quarter of the new layout: everything inside it must start twice as+ // large and centred where it was.+ let transition = LayoutTransition::new(+ Rect::new(0.0, 0.0, 800.0, 600.0),+ Rect::new(0.0, 0.0, 400.0, 300.0),+ );+ // A tile inside the destination, at the far corner.+ let tile = Rect::new(200.0, 150.0, 200.0, 150.0);+ let (_, running) = transition.sample(tile);+ assert!(running, "the transition is in flight");+ let origin = transition.origin_of(tile);+ assert!((origin.x - 400.0).abs() < 0.001, "{origin:?}");+ assert!((origin.y - 300.0).abs() < 0.001, "{origin:?}");+ assert!((origin.w - 400.0).abs() < 0.001, "{origin:?}");+ assert!((origin.h - 300.0).abs() < 0.001, "{origin:?}");++ let finished = LayoutTransition {+ started: Instant::now()+ .checked_sub(Duration::from_millis(500))+ .expect("a moment on a running machine"),+ ..transition+ };+ let (end, running) = finished.sample(tile);+ assert!(!running);+ assert_eq!(end, tile, "it ends exactly at the real layout");+ }++ #[test]+ fn a_transition_grows_a_tile_that_is_being_entered() {+ // Entering a child: the child's region becomes the viewport, so+ // everything inside it gets bigger, never smaller.+ let transition = LayoutTransition::new(+ Rect::new(100.0, 100.0, 200.0, 200.0),+ Rect::new(0.0, 0.0, 800.0, 600.0),+ );+ let tile = Rect::new(400.0, 300.0, 100.0, 100.0);+ let origin = transition.origin_of(tile);+ assert!(origin.w < tile.w, "it starts smaller: {origin:?}");+ assert!(+ origin.x > 100.0 && origin.x < 300.0,+ "and where the child was: {origin:?}"+ );+ }++ #[test]+ fn directions_only_see_gaps_on_their_own_side() {+ let from = Rect::new(100.0, 100.0, 50.0, 50.0);+ let right = Rect::new(200.0, 100.0, 50.0, 50.0);+ let left = Rect::new(0.0, 100.0, 50.0, 50.0);+ assert!(Direction::Right.gap(&from, &right).is_some());+ assert!(Direction::Right.gap(&from, &left).is_none());+ assert!(Direction::Left.gap(&from, &left).is_some());+ assert!(Direction::Down.gap(&from, &right).is_none());+ assert_eq!(Direction::Right.gap(&from, &right), Some(50.0));+ // Aligned neighbours have no perpendicular offset; stacked ones do.+ assert!(Direction::Right.offset(&from, &right).abs() < f32::EPSILON);+ assert!(+ Direction::Right+ .offset(&from, &Rect::new(200.0, 160.0, 20.0, 20.0))+ > 0.0+ );+ }+}diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rsnew file mode 100644index 0000000..f923027--- /dev/null+++ b/crates/disktree-app/src/tests.rs@@ -0,0 +1,816 @@+//! End-to-end tests through the real window harness.+//!+//! These drive the application the way a person does — draw a frame, press+//! keys, type — so they catch what unit tests on the state cannot: a screen+//! that panics while painting, a binding that never fires, a removal that+//! reports success without removing anything.++use std::path::Path;++use disktree_core::removal::RemovalMode;+use disktree_core::scan::{ScanOptions, scan};+use disktree_core::treemap::Tile;+use gpui_kit::{+ Bounds, Context, Entity, Pixels, Point, TestAppContext, VisualTestContext,+ px,+};+use gpui_omarchy::Theme;++use crate::state::{Disktree, Screen};++/// A small tree on disk: two directories, a nested file, and a hidden one.+///+/// The hidden directory holds the largest file, which is both the common case+/// in a home directory and the one the ranking has to get right.+fn fixture() -> tempfile::TempDir {+ let temp = tempfile::TempDir::new().expect("tempdir");+ let root = temp.path();+ for (path, bytes) in [+ ("keep/notes.txt", 1_000_usize),+ ("junk/blob.bin", 200_000),+ ("junk/deeper/more.bin", 100_000),+ (".cache/blob.bin", 300_000),+ ] {+ let file = root.join(path);+ std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir");+ std::fs::write(&file, vec![b'x'; bytes]).expect("write");+ }+ temp+}++/// Apparent sizes, so the assertions are about the tree and not about how the+/// filesystem rounds a small file up to a block.+fn options() -> ScanOptions {+ ScanOptions {+ apparent_size: true,+ ..ScanOptions::default()+ }+}++type Window = VisualTestContext;++/// Open a window over a real scan of `root`, without the background walk.+fn view_over<'a>(+ root: &Path,+ cx: &'a mut TestAppContext,+) -> (Entity<Disktree>, &'a mut Window) {+ let tree = scan(root, options()).expect("scan the fixture");+ let root_path = root.to_path_buf();+ let (view, cx) = cx.add_window_view(move |_, cx| {+ Disktree::with_tree(root_path.clone(), tree, options(), 3, cx)+ });+ let focus = view.read_with(cx, |app, _| app.focus.clone());+ cx.update(|window, cx| window.focus(&focus, cx));+ (view, cx)+}++fn draw(cx: &mut Window) {+ cx.update(|window, cx| {+ window.draw(cx).clear(cx);+ });+}++fn press(cx: &mut Window, keys: &str) {+ cx.simulate_keystrokes(keys);+ draw(cx);+}++fn update<R>(+ view: &Entity<Disktree>,+ cx: &mut Window,+ f: impl FnOnce(&mut Disktree, &mut Context<'_, Disktree>) -> R,+) -> R {+ view.update(cx, f)+}++fn read<R>(+ view: &Entity<Disktree>,+ cx: &Window,+ f: impl FnOnce(&Disktree) -> R,+) -> R {+ view.read_with(cx, |app, _| f(app))+}++#[gpui_kit::test]+fn the_window_draws_a_treemap_with_tiles(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ draw(cx);++ let bounds: Bounds<Pixels> =+ cx.debug_bounds("disktree-root").expect("root element");+ assert!(bounds.size.width > px(0.) && bounds.size.height > px(0.));++ let (size, tiles) = update(&view, cx, |app, _| {+ (+ app.treemap_size.get(),+ app.layout().map(<[Tile]>::len).unwrap_or_default(),+ )+ });+ assert!(size.width > px(0.), "treemap width {size:?}");+ assert!(size.height > px(0.), "treemap height {size:?}");+ assert!(tiles >= 3, "tiles laid out: {tiles}");+}++#[gpui_kit::test]+fn the_first_scan_shows_what_it_is_doing_then_the_treemap(+ cx: &mut TestAppContext,+) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let root = temp.path().to_path_buf();+ // Through the real constructor, so this is the path every first run takes.+ let (view, cx) =+ cx.add_window_view(move |_, cx| Disktree::new(root, options(), 3, cx));+ draw(cx);++ // Nothing is known yet, so the viewport counts the walk instead of showing+ // an empty mosaic.+ assert!(read(&view, cx, |app| app.tree().is_none()));+ assert!(cx.debug_bounds("disktree-root").is_some());++ let epoch = read(&view, cx, |app| app.scan_epoch);+ let mut ready = false;+ for _ in 0..600 {+ std::thread::sleep(std::time::Duration::from_millis(5));+ ready = update(&view, cx, |app, cx| {+ app.poll_scan_once(epoch, cx);+ app.tree().is_some()+ });+ if ready {+ break;+ }+ }+ assert!(ready, "the scan landed");+ draw(cx);++ let (tiles, selected, hidden_present) = update(&view, cx, |app, _| {+ (+ app.layout().map(<[Tile]>::len).unwrap_or_default(),+ app.selected.is_some(),+ app.tree().is_some_and(|tree| {+ tree.children.iter().any(|c| c.name.starts_with('.'))+ }),+ )+ });+ assert!(tiles >= 3, "tiles after the scan: {tiles}");+ assert!(+ selected,+ "the largest entry is selected for the selection line"+ );+ assert!(hidden_present, "hidden directories are part of the tree");+}++#[gpui_kit::test]+fn keys_walk_the_tree_and_mark_what_is_selected(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ draw(cx);++ // Largest first: .cache holds the biggest file.+ let (selected, name) = read(&view, cx, |app| {+ (+ app.selected.clone(),+ app.node_at(&[0]).map(|node| node.name.to_string()),+ )+ });+ assert_eq!(selected, Some(vec![0]));+ assert_eq!(name.as_deref(), Some(".cache"));++ press(cx, "space");+ let (marks, bytes) =+ read(&view, cx, |app| (app.marks.len(), app.plan().bytes()));+ assert_eq!(marks, 1);+ assert_eq!(bytes, 300_000, "the whole hidden directory");++ // Enter descends, Escape comes back out.+ press(cx, "enter");+ assert!(!read(&view, cx, |app| app.crumbs.is_empty()));+ press(cx, "escape");+ press(cx, "escape");+ assert!(read(&view, cx, |app| app.crumbs.is_empty()));++ // Space twice more leaves the mark as it was.+ press(cx, "space");+ press(cx, "space");+ let marks = read(&view, cx, |app| app.marks.items().to_vec());+ assert_eq!(marks.len(), 1);+ assert_eq!(marks[0].bytes, 300_000);+}++#[gpui_kit::test]+fn a_permanent_deletion_asks_in_an_alert_dialog_then_removes(+ cx: &mut TestAppContext,+) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ draw(cx);++ // Mark "junk" directly, which is what clicking its tile would do, and+ // choose the permanent path: the trash path would reach the real trash.+ update(&view, cx, |app, cx| {+ app.removal_mode = RemovalMode::Permanent;+ let junk = app+ .tree()+ .and_then(|tree| {+ tree.children+ .iter()+ .position(|child| &*child.name == "junk")+ .map(|index| vec![index])+ })+ .expect("the junk directory");+ app.select(Some(junk.clone()), cx);+ app.toggle_mark(&junk, cx);+ assert_eq!(app.plan().bytes(), 300_000);+ });++ press(cx, "c");+ assert_eq!(read(&view, cx, |app| app.screen), Screen::Review);++ // Enter on the review screen opens the alert dialog; nothing is deleted.+ press(cx, "enter");+ assert!(read(&view, cx, |app| app.confirm_open));+ assert_eq!(read(&view, cx, |app| app.screen), Screen::Review);+ assert!(+ temp.path().join("junk").exists(),+ "nothing has happened yet"+ );++ // Enter in the dialog is its confirm action.+ press(cx, "enter");+ assert!(!read(&view, cx, |app| app.confirm_open));+ assert_eq!(read(&view, cx, |app| app.screen), Screen::Running);++ // The removal runs on a real worker thread, so the test drives the same+ // poll the UI's ticker drives rather than waiting on the test clock.+ let epoch = read(&view, cx, |app| app.run_epoch);+ let mut finished = false;+ for _ in 0..400 {+ std::thread::sleep(std::time::Duration::from_millis(5));+ finished = update(&view, cx, |app, cx| {+ app.poll_removal_once(epoch, cx);+ app.screen == Screen::Done+ });+ if finished {+ break;+ }+ }+ assert!(finished, "the removal finished");+ draw(cx);++ let summary = read(&view, cx, |app| app.run_summary.clone());+ assert_eq!(summary.removed, 1, "{summary:?}");+ assert_eq!(summary.failed, 0, "{summary:?}");+ assert!(+ read(&view, cx, |app| app.marks.is_empty()),+ "the list clears after the run"+ );+ assert!(!temp.path().join("junk").exists(), "junk is gone");+ assert!(+ temp.path().join("keep/notes.txt").exists(),+ "an unmarked directory is untouched"+ );+ assert!(+ temp.path().join(".cache/blob.bin").exists(),+ "an unmarked hidden directory is untouched"+ );+}++/// A subdivided directory keeps a band at the top for its own name, and its+/// children start below it. That is what makes the inner tiles selectable: the+/// parent's name never covers them.+#[gpui_kit::test]+fn a_parents_name_gets_its_own_band_above_its_children(+ cx: &mut TestAppContext,+) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ draw(cx);++ let (band, lowest_child_top, bands_in_mosaic) =+ update(&view, cx, |app, _| {+ let tiles = app.layout().map(<[Tile]>::to_vec).unwrap_or_default();+ let parent = tiles+ .iter()+ .find(|tile| tile.crumbs() == [1])+ .expect("the junk directory");+ let band = parent+ .header+ .expect("junk is subdivided, so it keeps a band");+ let children_top = tiles+ .iter()+ .filter(|tile| {+ tile.crumbs().starts_with(&[1]) && tile.crumbs().len() > 1+ })+ .map(|tile| tile.rect.y)+ .fold(f32::INFINITY, f32::min);+ let mosaic = app.prepare();+ let bands_in_mosaic = mosaic+ .labels+ .iter()+ .filter(|label| label.header.is_some())+ .count();+ (band, children_top, bands_in_mosaic)+ });++ assert!(+ lowest_child_top >= band.bottom() - f32::EPSILON,+ "children start at {} but the band ends at {}",+ lowest_child_top,+ band.bottom()+ );+ assert!(+ band.h >= 8.0,+ "a band has to be tall enough to read: {}",+ band.h+ );+ assert!(+ bands_in_mosaic >= 1,+ "the parent's own label is placed in a band"+ );+}++#[gpui_kit::test]+fn hovering_reports_the_tile_under_the_pointer(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ draw(cx);++ let (origin, biggest, centre) = update(&view, cx, |app, _| {+ // A leaf tile, so "the deepest tile under the pointer" is unambiguous.+ let biggest = app+ .layout()+ .and_then(|tiles| {+ tiles+ .iter()+ .filter(|tile| {+ let crumbs = tile.crumbs();+ !tiles.iter().any(|other| {+ other.crumbs().len() > crumbs.len()+ && other.crumbs().starts_with(crumbs)+ })+ })+ .max_by(|left, right| {+ left.rect.area().total_cmp(&right.rect.area())+ })+ .map(|tile| tile.crumbs().to_vec())+ })+ .expect("a tile to hover");+ let rect = app.tile_rect(&biggest).expect("a rectangle");+ let screen = app.view.project(rect);+ (+ app.treemap_origin.get(),+ biggest,+ (screen.x + screen.w / 2.0, screen.y + screen.h / 2.0),+ )+ });++ let (x, y) = centre;+ cx.simulate_mouse_move(+ Point::new(origin.x + px(x), origin.y + px(y)),+ None,+ gpui_kit::Modifiers::default(),+ );+ draw(cx);++ let hovered = read(&view, cx, |app| app.hovered.clone());+ assert_eq!(hovered.as_deref(), Some(biggest.as_slice()));+}++#[gpui_kit::test]+fn typing_in_the_find_field_jumps_to_a_match(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ draw(cx);++ press(cx, "/");+ assert!(read(&view, cx, |app| app.find_open));++ cx.simulate_input("deeper");+ 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())+ });+ 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]));+}++#[gpui_kit::test]+fn the_help_overlay_opens_and_closes(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ draw(cx);++ press(cx, "?");+ assert!(read(&view, cx, |app| app.show_help));+ press(cx, "escape");+ assert!(!read(&view, cx, |app| app.show_help));+}++#[gpui_kit::test]+fn the_treemap_zooms_with_the_wheel_and_resets(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ draw(cx);++ let middle = read(&view, cx, |app| {+ let size = app.treemap_size.get();+ Point::new(size.width / 2.0, size.height / 2.0)+ });+ update(&view, cx, |app, cx| {+ app.zoom_at(middle.x.as_f32(), middle.y.as_f32(), 1.5, false, cx);+ });+ let zoomed = read(&view, cx, |app| app.view.scale);+ assert!(zoomed > 1.0, "scale after zooming: {zoomed}");++ press(cx, "0");+ assert!((read(&view, cx, |app| app.view.scale) - 1.0).abs() < f32::EPSILON);+}++/// Both appearances Omarchy ships must draw: the palette is derived from the+/// theme, so a light theme is a real second configuration.+#[gpui_kit::test]+fn both_appearances_draw(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ for theme in [Theme::tokyo_night(), Theme::flexoki_light()] {+ view.update(cx, |_, cx| {+ theme.clone().apply(cx);+ cx.notify();+ });+ draw(cx);+ assert!(cx.debug_bounds("disktree-root").is_some());+ }+}++/// A view built without a scan keeps working: the screens must not assume a+/// walk is in flight.+#[gpui_kit::test]+fn a_view_without_flags_or_marks_still_draws(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ update(&view, cx, |app, cx| {+ app.screen = Screen::Review;+ cx.notify();+ });+ draw(cx);+ assert!(cx.debug_bounds("disktree-root").is_some());++ update(&view, cx, |app, cx| {+ app.screen = Screen::Running;+ cx.notify();+ });+ draw(cx);++ update(&view, cx, |app, cx| {+ app.screen = Screen::Done;+ cx.notify();+ });+ draw(cx);+ assert!(cx.debug_bounds("disktree-root").is_some());+}++/// The removal mode is a choice with two independent channels: the key and the+/// button both have to reach the same state.+#[gpui_kit::test]+fn the_review_screen_switches_removal_mode(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ update(&view, cx, |app, cx| {+ app.marks.toggle(disktree_core::removal::Target {+ path: temp.path().join("junk"),+ bytes: 300_000,+ is_dir: true,+ hidden: false,+ });+ app.screen = Screen::Review;+ cx.notify();+ });+ draw(cx);++ press(cx, "m");+ assert_eq!(read(&view, cx, |app| app.removal_mode), RemovalMode::Trash);+ press(cx, "p");+ assert_eq!(+ read(&view, cx, |app| app.removal_mode),+ RemovalMode::Permanent+ );+ press(cx, "!");+ assert!(read(&view, cx, |app| app.marks.is_empty()));+}++/// Escape in the alert dialog cancels: the dialog closes, the review screen+/// stays, and nothing on disk changes.+#[gpui_kit::test]+fn escape_in_the_delete_dialog_cancels(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ update(&view, cx, |app, cx| {+ app.removal_mode = RemovalMode::Permanent;+ app.marks.toggle(disktree_core::removal::Target {+ path: temp.path().join("junk"),+ bytes: 300_000,+ is_dir: true,+ hidden: false,+ });+ app.screen = Screen::Review;+ cx.notify();+ });+ draw(cx);++ press(cx, "enter");+ assert!(read(&view, cx, |app| app.confirm_open));+ press(cx, "escape");+ assert!(!read(&view, cx, |app| app.confirm_open), "Escape cancels");+ assert_eq!(read(&view, cx, |app| app.screen), Screen::Review);+ assert!(temp.path().join("junk").exists());+ assert_eq!(+ read(&view, cx, |app| app.marks.len()),+ 1,+ "the list is kept"+ );+}++/// With a trash on the machine, the reversible path is the default and+/// commits without a dialog; the permanent one is a deliberate choice.+#[gpui_kit::test]+fn the_trash_is_the_default_when_there_is_one(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ let (mode, available) = read(&view, cx, |app| {+ (app.removal_mode, app.trash_backend.is_available())+ });+ if available {+ assert_eq!(mode, RemovalMode::Trash);+ } else {+ assert_eq!(mode, RemovalMode::Permanent);+ }+}++/// `ctrl =` / `ctrl -` / `ctrl 0` change the window's rem, which every size+/// in the app is expressed in, and the mosaic's header band follows it.+#[gpui_kit::test]+fn interface_zoom_scales_the_rem_and_the_header_band(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ draw(cx);+ let rem =+ |cx: &mut Window| cx.update(|window, _| window.rem_size().as_f32());+ let base = rem(cx);+ let band = |view: &Entity<Disktree>, cx: &mut Window| {+ update(view, cx, |app, _| {+ app.layout();+ app.layout_options.header+ })+ };+ let base_band = band(&view, cx);++ press(cx, "ctrl-=");+ let zoomed = rem(cx);+ assert!(zoomed > base, "{zoomed} after zooming in from {base}");+ let zoomed_band = band(&view, cx);+ assert!(+ (zoomed_band / base_band - zoomed / base).abs() < 0.01,+ "the band scales with the rem: {base_band} -> {zoomed_band}"+ );++ press(cx, "ctrl--");+ press(cx, "ctrl--");+ assert!(rem(cx) < base, "zooming out goes below the default");+ press(cx, "ctrl-0");+ assert!((rem(cx) - base).abs() < 0.01, "ctrl 0 resets");+}++/// The crumbs of the directory named `name` directly inside `parent`.+fn child_crumbs(app: &Disktree, parent: &[usize], name: &str) -> Vec<usize> {+ let node = app.node_at(parent).expect("the parent");+ let index = node+ .children+ .iter()+ .position(|child| &*child.name == name)+ .unwrap_or_else(|| panic!("no {name}"));+ let mut crumbs = parent.to_vec();+ crumbs.push(index);+ crumbs+}++/// Regression: the wheel magnified toward the deepest directory under the+/// pointer, then went into the *top-level* one containing it, so the screen+/// after the descent was never the area that was zoomed into.+#[gpui_kit::test]+fn the_wheel_goes_into_the_directory_it_zoomed_into(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ draw(cx);++ // Point at the middle of junk/deeper's contents: a directory one level+ // below a top-level one.+ let (deeper, point) = update(&view, cx, |app, _| {+ let junk = child_crumbs(app, &[], "junk");+ let deeper = child_crumbs(app, &junk, "deeper");+ let body = app.tile_body(&deeper).expect("deeper is drawn");+ (deeper, (body.x + body.w / 2.0, body.y + body.h / 2.0))+ });++ let mut entered = None;+ for _ in 0..40 {+ let crumbs = update(&view, cx, |app, cx| {+ let (x, y) = app.view.unproject(point.0, point.1);+ let screen = app+ .view+ .project(disktree_core::treemap::Rect::new(x, y, 0.0, 0.0));+ app.zoom_at(screen.x, screen.y, 1.15, true, cx);+ app.crumbs.clone()+ });+ draw(cx);+ if !crumbs.is_empty() {+ entered = Some(crumbs);+ break;+ }+ }+ assert_eq!(+ entered.as_deref(),+ Some(deeper.as_slice()),+ "descended into the pointed-at directory, not its top-level ancestor"+ );+}++/// Regression, keyboard side: Enter on a deep selection enters that+/// directory, and on a file enters the directory holding it.+#[gpui_kit::test]+fn enter_opens_the_selected_directory_at_any_depth(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ draw(cx);++ let deeper = update(&view, cx, |app, cx| {+ let junk = child_crumbs(app, &[], "junk");+ let deeper = child_crumbs(app, &junk, "deeper");+ app.select(Some(deeper.clone()), cx);+ app.descend(cx);+ deeper+ });+ assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper);++ press(cx, "escape");+ press(cx, "escape");+ press(cx, "escape");+ let junk = update(&view, cx, |app, cx| {+ app.go_to(Vec::new(), cx);+ let junk = child_crumbs(app, &[], "junk");+ let blob = child_crumbs(app, &junk, "blob.bin");+ app.select(Some(blob), cx);+ app.descend(cx);+ junk+ });+ assert_eq!(+ read(&view, cx, |app| app.crumbs.clone()),+ junk,+ "a file opens its directory"+ );+}++/// The mark key acts on what the pointer is over when the pointer moved+/// last, and on the keyboard selection after an arrow.+#[gpui_kit::test]+fn the_mark_key_follows_the_pointer_until_the_keyboard_moves(+ cx: &mut TestAppContext,+) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ draw(cx);++ // Point at junk's name band, which belongs to junk itself (its body+ // belongs to its children). junk is not the default selection, .cache.+ let (keep, origin, centre) = update(&view, cx, |app, _| {+ let keep = child_crumbs(app, &[], "junk");+ let body = app+ .layout()+ .and_then(|tiles| {+ tiles.iter().find(|tile| tile.crumbs() == keep.as_slice())+ })+ .and_then(|tile| tile.header)+ .expect("junk is drawn with a band");+ (+ keep,+ app.treemap_origin.get(),+ (body.x + body.w / 2.0, body.y + body.h / 2.0),+ )+ });+ assert_ne!(+ read(&view, cx, |app| app.selected.clone()),+ Some(keep.clone())+ );+ cx.simulate_mouse_move(+ Point::new(origin.x + px(centre.0), origin.y + px(centre.1)),+ None,+ gpui_kit::Modifiers::default(),+ );+ draw(cx);++ press(cx, "space");+ let marked = read(&view, cx, |app| app.marks.items().to_vec());+ assert_eq!(marked.len(), 1);+ assert!(+ marked[0].path.ends_with("junk"),+ "marked what the pointer is on: {:?}",+ marked[0].path+ );+ assert_eq!(read(&view, cx, |app| app.selected.clone()), Some(keep));++ // An arrow hands control back to the keyboard selection.+ press(cx, "right");+ assert!(!read(&view, cx, |app| app.pointer_active));+}++/// Regression: after descending, tiles resolved against the scanned root+/// instead of the directory drawn, so labels, hover and marks named strangers.+#[gpui_kit::test]+fn after_descending_every_tile_is_inside_the_directory_drawn(+ cx: &mut TestAppContext,+) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ draw(cx);++ let junk = update(&view, cx, |app, cx| {+ let junk = child_crumbs(app, &[], "junk");+ app.select(Some(junk.clone()), cx);+ app.descend(cx);+ junk+ });+ assert_eq!(read(&view, cx, |app| app.crumbs.clone()), junk);+ draw(cx);++ let (paths, labels) = update(&view, cx, |app, _| {+ let tiles = app.layout().map(<[Tile]>::to_vec).unwrap_or_default();+ let paths: Vec<_> = tiles+ .iter()+ .filter_map(|tile| app.path_at(tile.crumbs()))+ .collect();+ let labels: Vec<String> = app+ .prepare()+ .labels+ .into_iter()+ .map(|label| label.text)+ .collect();+ (paths, labels)+ });+ assert!(!paths.is_empty());+ let junk_path = temp.path().join("junk");+ for path in &paths {+ assert!(path.starts_with(&junk_path), "{path:?} is outside junk");+ }+ for label in &labels {+ assert!(+ ["blob.bin", "deeper", "more.bin"].contains(&label.as_str())+ || label.starts_with('+'),+ "label {label} does not belong to junk"+ );+ }++ // Space on the selection marks something inside junk, never elsewhere.+ update(&view, cx, |app, cx| {+ let blob = child_crumbs(app, &junk, "blob.bin");+ app.select(Some(blob), cx);+ });+ press(cx, "space");+ let marked = read(&view, cx, |app| app.marks.items().to_vec());+ assert_eq!(marked.len(), 1);+ assert_eq!(marked[0].path, junk_path.join("blob.bin"));+ assert_eq!(marked[0].bytes, 200_000);++ // And the mark is drawn on the right tile: its crumbs resolve here.+ let hatched = update(&view, cx, |app, _| {+ app.prepare()+ .tiles+ .iter()+ .filter(|tile| tile.marked)+ .count()+ });+ assert_eq!(hatched, 1, "exactly the marked tile is hatched");+}diff --git a/crates/disktree-app/src/treemap_view.rs b/crates/disktree-app/src/treemap_view.rsnew file mode 100644index 0000000..01a5704--- /dev/null+++ b/crates/disktree-app/src/treemap_view.rs@@ -0,0 +1,433 @@+//! The mosaic: tiles painted on a canvas, labels shaped straight into it.+//!+//! Tiles are painted rather than composed from elements. A treemap can put+//! thousands of rectangles on screen, and an element per rectangle would spend+//! the frame in layout. Painting also means the marked hatch, the selection+//! ring and the hover outline are drawn in one place, in one order.+//!+//! Text is shaped here too. GPUI caches shaped lines, so re-shaping the visible+//! labels every frame costs a lookup, and it lets a label clip exactly to its+//! own tile instead of bleeding into the neighbour.++use std::rc::Rc;++use disktree_core::treemap::Rect;+use gpui_kit::{+ App, Bounds, ContentMask, Context, Corners, Edges, Font, Hsla,+ InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent,+ MouseMoveEvent, ParentElement as _, Pixels, Point, ScrollWheelEvent,+ SharedString, Size, StatefulInteractiveElement as _, Styled, TextAlign,+ TextRun, Window, canvas, div, pattern_slash, px, quad,+};+use gpui_omarchy::{ActiveTheme, Theme};++use crate::palette;+use crate::state::{Disktree, Label, View};++/// How one tile should be drawn, resolved before the paint callback runs so+/// that painting never has to look anything up.+#[derive(Clone, Debug)]+pub struct TileDeco {+ /// Base-space rectangle: the view transform is applied while painting.+ pub rect: Rect,+ /// The band this directory reserved for its name, when it is subdivided.+ pub header: Option<Rect>,+ pub depth: u32,+ /// Depth from the scanned root, used for the fill so descending does not+ /// recolour the mosaic; `depth` stays view-relative for geometry.+ pub color_depth: u32,+ pub hidden: bool,+ pub marked: bool,+ /// Inside another marked directory, so it goes with its parent.+ pub covered: bool,+ pub hovered: bool,+ pub selected: bool,+}++/// Everything the mosaic needs for one frame.+#[derive(Clone, Debug, Default)]+pub struct Mosaic {+ pub tiles: Vec<TileDeco>,+ pub labels: Vec<Label>,+ pub view: View,+}++/// Build the treemap viewport: canvas, input, and the cursor tooltip.+pub fn mosaic(+ mosaic: Mosaic,+ app: &Disktree,+ window: &Window,+ cx: &Context<'_, Disktree>,+) -> impl IntoElement {+ let theme = cx.omarchy().clone();+ let rem = window.rem_size();+ let origin = Rc::clone(&app.treemap_origin);+ let measured = Rc::clone(&app.treemap_size);++ let colors = Colors::new(&theme);+ let font = theme.font.clone();+ let name_size = rem_px(0.75, rem);+ let size_size = rem_px(0.6875, rem);++ let Mosaic {+ tiles,+ labels,+ view,+ } = mosaic;+ let canvas_origin = Rc::clone(&origin);+ let canvas_measured = Rc::clone(&measured);++ div()+ .id("disktree-treemap")+ .relative()+ .flex_1()+ .min_h_0()+ .min_w_0()+ .overflow_hidden()+ .bg(theme.inset)+ .on_hover(cx.listener(|this, hovered: &bool, _, cx| {+ if !hovered {+ this.on_mouse_leave(cx);+ }+ }))+ .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| {+ this.on_mouse_move(event, cx);+ }))+ .on_mouse_down(+ MouseButton::Left,+ cx.listener(|this, event: &MouseDownEvent, _, cx| {+ this.on_mouse_down(event, cx);+ }),+ )+ .on_mouse_down(+ MouseButton::Middle,+ cx.listener(|this, event: &MouseDownEvent, _, cx| {+ this.on_mouse_down(event, cx);+ }),+ )+ .on_scroll_wheel(cx.listener(+ |this, event: &ScrollWheelEvent, _, cx| {+ this.on_scroll_wheel(event, cx);+ },+ ))+ .child(+ canvas(+ move |bounds, window, _| {+ canvas_origin.set(bounds.origin);+ // The layout was computed from the previous frame's size. Ask+ // for one more frame whenever the area is not what we assumed,+ // which is what makes the first paint and a resize settle.+ if canvas_measured.get() != bounds.size {+ canvas_measured.set(bounds.size);+ window.request_animation_frame();+ }+ bounds.size+ },+ move |bounds, _, window, cx| {+ paint_tiles(&tiles, bounds, view, &colors, window);+ paint_labels(+ &labels, bounds, view, &colors, &font, name_size,+ size_size, window, cx,+ );+ },+ )+ .absolute()+ .inset_0(),+ )+}++/// Theme colours resolved once per frame.+struct Colors {+ label: Vec<Hsla>,+ label_dim: Hsla,+ border: Hsla,+ hover_border: Hsla,+ selected_border: Hsla,+ marked_border: Hsla,+ marked_hatch: Hsla,+ marked_label: Hsla,+ covered_border: Hsla,+ header_tint: Hsla,+ header_rule: Hsla,+ fill: Vec<Hsla>,+ fill_hidden: Vec<Hsla>,+ fill_marked: Vec<Hsla>,+}++impl Colors {+ fn new(theme: &Theme) -> Self {+ // Absolute depth runs past the visible nesting (each descent adds to+ // it), so the ladder is longer than `max_depth` and clamps at the end.+ let depth_range = 0..=12;+ Self {+ label: depth_range+ .clone()+ .map(|d| palette::label_color(theme, d))+ .collect(),+ label_dim: theme.bright.opacity(0.55),+ border: theme.background.opacity(0.55),+ hover_border: theme.bright.opacity(0.7),+ selected_border: theme.bright,+ marked_border: theme.danger,+ marked_hatch: theme.danger.opacity(0.4),+ marked_label: theme.bright,+ covered_border: theme.danger.opacity(0.45),+ // A band reads as a label strip because it is lifted a little and+ // closed with a rule, not because it is another colour.+ header_tint: theme.bright.opacity(0.09),+ header_rule: theme.background.opacity(0.75),+ fill: depth_range+ .clone()+ .map(|d| palette::tile_fill(theme, d, false, false))+ .collect(),+ fill_hidden: depth_range+ .clone()+ .map(|d| palette::tile_fill(theme, d, true, false))+ .collect(),+ fill_marked: depth_range+ .map(|d| palette::tile_fill(theme, d, false, true))+ .collect(),+ }+ }++ fn fill(&self, tile: &TileDeco) -> Hsla {+ let index = (tile.color_depth as usize).min(self.fill.len() - 1);+ if tile.marked {+ self.fill_marked[index]+ } else if tile.hidden {+ self.fill_hidden[index]+ } else {+ self.fill[index]+ }+ }++ fn label(&self, depth: u32) -> Hsla {+ self.label[(depth as usize).min(self.label.len() - 1)]+ }+}++fn paint_tiles(+ tiles: &[TileDeco],+ bounds: Bounds<Pixels>,+ view: View,+ colors: &Colors,+ window: &mut Window,+) {+ for tile in tiles {+ let rect = view.project(tile.rect);+ if rect.w <= 0.5 || rect.h <= 0.5 {+ continue;+ }+ let quad_bounds = to_window(&rect, bounds);++ // Every tile gets a hairline of background rather than a bright border:+ // that is what separates nested levels without turning the mosaic into+ // a wireframe.+ let mut width = if tile.depth == 0 { 1.0 } else { 0.5 };+ let mut border = colors.border;+ if tile.marked {+ width = 2.0;+ border = colors.marked_border;+ } else if tile.covered {+ width = 1.0;+ border = colors.covered_border;+ }+ if tile.hovered {+ width = 2.0;+ border = colors.hover_border;+ }+ if tile.selected {+ width = 2.0;+ border = colors.selected_border;+ }++ window.paint_quad(quad(+ quad_bounds,+ Corners::default(),+ colors.fill(tile),+ Edges::all(px(width)),+ border,+ gpui_kit::BorderStyle::Solid,+ ));++ // The band a subdivided directory keeps for its name: lifted, and+ // closed with a rule, so the group reads as a group and the space+ // inside it belongs to the children.+ if let Some(header) = tile.header {+ let header = view.project(header);+ if header.w > 1.0 && header.h > 1.0 {+ let band = to_window(&header, bounds);+ window.paint_quad(quad(+ band,+ Corners::default(),+ colors.header_tint,+ Edges::all(px(0.)),+ colors.header_rule,+ gpui_kit::BorderStyle::Solid,+ ));+ }+ }++ // A hatched overlay is the conventional "this one is going away" mark,+ // and it survives on top of any tile colour the theme produces.+ if tile.marked {+ window.paint_quad(quad(+ inset(quad_bounds, px(2.)),+ Corners::default(),+ pattern_slash(colors.marked_hatch, 2.0, 9.0),+ Edges::all(px(0.)),+ colors.marked_border,+ gpui_kit::BorderStyle::Solid,+ ));+ }+ }+}++#[expect(+ clippy::too_many_arguments,+ reason = "the paint pass threads window state; a struct would only move+ these fields somewhere else"+)]+fn paint_labels(+ labels: &[Label],+ bounds: Bounds<Pixels>,+ view: View,+ colors: &Colors,+ font: &SharedString,+ name_size: Pixels,+ size_size: Pixels,+ window: &mut Window,+ cx: &mut App,+) {+ let font = Font {+ family: font.clone(),+ ..Font::default()+ };+ let name_line_height = name_size * 1.35;+ let text_system = window.text_system().clone();+ // Label geometry is proportioned to the label's own type size, which+ // already follows `rem`: padding, thresholds and gaps then keep their+ // relationship to the text at every interface zoom step.+ let text_padding = name_size * 0.42;+ let text_inset = name_size * 0.25;+ let min_width = name_size * 3.3;+ let size_gap = name_size * 0.67;++ for label in labels {+ // A subdivided directory's name lives in the band it reserved; a leaf's+ // sits at the top of its own tile. Either way the mask is the region+ // the label owns, so no label can reach into another tile.+ let owned = label.header.unwrap_or(label.rect);+ let rect = view.project(owned);+ if px(rect.w) < min_width || px(rect.h) < name_size {+ continue;+ }+ let mask = to_window(&rect, bounds);+ let origin = Point::new(+ mask.origin.x + text_padding,+ mask.origin.y + text_inset,+ );+ let color = if label.marked {+ colors.marked_label+ } else {+ colors.label(label.color_depth)+ };++ let run = TextRun {+ len: label.text.len(),+ font: font.clone(),+ color,+ ..TextRun::default()+ };+ let line = text_system.shape_line(+ SharedString::from(label.text.clone()),+ name_size,+ &[run],+ None,+ );++ window.with_content_mask(+ Some(ContentMask { bounds: mask }),+ |window| {+ let _ = line.paint(+ origin,+ name_line_height,+ TextAlign::Left,+ None,+ window,+ cx,+ );++ if label.size_text.is_empty() {+ return;+ }+ let room = mask.size.width - (origin.x - mask.origin.x) * 2.;+ let size_run = TextRun {+ len: label.size_text.len(),+ font: font.clone(),+ color: colors.label_dim,+ ..TextRun::default()+ };+ let size_line = text_system.shape_line(+ SharedString::from(label.size_text.clone()),+ size_size,+ &[size_run],+ None,+ );+ // Mixed sizes share the name's baseline, not its box. A line+ // paints centred in its line height, putting the baseline at+ // `height / 2 + (ascent - descent) / 2`; equate the two.+ let baseline = origin.y+ + ((line.ascent - line.descent)+ - (size_line.ascent - size_line.descent))+ * 0.5;+ // In a band the size sits at the far end, where it reads as a+ // column; without one it follows the name when there is room.+ let size_origin = if label.header.is_some() {+ Point::new(+ mask.origin.x + mask.size.width+ - size_line.width()+ - text_padding,+ baseline,+ )+ } else {+ if room - line.width() < size_size * 3.0 {+ return;+ }+ Point::new(origin.x + line.width() + size_gap, baseline)+ };+ if size_origin.x > origin.x + line.width() + text_padding {+ let _ = size_line.paint(+ size_origin,+ name_line_height,+ TextAlign::Left,+ None,+ window,+ cx,+ );+ }+ },+ );+ }+}++fn to_window(rect: &Rect, bounds: Bounds<Pixels>) -> Bounds<Pixels> {+ Bounds::new(+ Point::new(bounds.origin.x + px(rect.x), bounds.origin.y + px(rect.y)),+ Size::new(px(rect.w), px(rect.h)),+ )+}++fn inset(bounds: Bounds<Pixels>, amount: Pixels) -> Bounds<Pixels> {+ Bounds::new(+ Point::new(bounds.origin.x + amount, bounds.origin.y + amount),+ Size::new(+ (bounds.size.width - amount * 2.).max(px(0.)),+ (bounds.size.height - amount * 2.).max(px(0.)),+ ),+ )+}++fn rem_px(rems: f32, rem_size: Pixels) -> Pixels {+ px(rems * rem_size.as_f32())+}diff --git a/crates/disktree-app/src/ui.rs b/crates/disktree-app/src/ui.rsnew file mode 100644index 0000000..4644f67--- /dev/null+++ b/crates/disktree-app/src/ui.rs@@ -0,0 +1,92 @@+//! The scale this app draws with: spacing, type, icons and region widths.+//!+//! Everything is in `rem`, following the gpui-kit design guide: type, spacing,+//! controls and icons share one zoom axis, so interface zoom (`ctrl =`,+//! `ctrl -`, `ctrl 0`) keeps every relationship intact instead of only+//! enlarging text. Choose a step by what two things mean to each other, not by+//! the pixels it happens to resolve to today.+//!+//! Radius has a single tier here: Omarchy's surfaces are square, so nothing in+//! this app rounds a corner, and nested surfaces stay concentric by+//! construction.+//!+//! Pixels remain only where a value is physical: hairline borders, the+//! treemap's own geometry (laid out in viewport pixels, then scaled by the+//! view), and positions that come from the pointer.++use gpui_kit::Rems;++/// The guide's semantic spacing scale: 2, 4, 8, 12, 16, 24 and 32 px at the+/// default 16 px rem.+pub mod space {+ use super::Rems;++ /// Optical correction: an icon baseline, a compact separator.+ pub const XXS: Rems = Rems(0.125);+ /// Parts of one control: icon and label, title and its description.+ pub const XS: Rems = Rems(0.25);+ /// Closely related controls: a button group, dialog actions.+ pub const SM: Rems = Rems(0.5);+ /// One content group: columns of a row, compact form rows.+ pub const MD: Rems = Rems(0.75);+ /// Separate groups in one section, and region padding.+ pub const LG: Rems = Rems(1.0);+ /// Separate sections.+ pub const XL: Rems = Rems(1.5);+ /// A major region boundary: empty-state breathing room.+ pub const XXL: Rems = Rems(2.0);+}++/// Type steps. Omarchy's own sizes, so the app reads like its components.+pub mod text {+ use super::Rems;++ /// Metadata, key caps and tooltips.+ pub const CAPTION: Rems = Rems(0.6875);+ /// Body text and control labels.+ pub const BODY: Rems = Rems(0.75);+ /// Window, section and dialog titles.+ pub const TITLE: Rems = Rems(0.875);+}++/// Icon slots, sized with the text they sit beside.+pub mod icon {+ use super::Rems;++ pub const SM: Rems = Rems(0.75);+ pub const MD: Rems = Rems(0.875);+ pub const LG: Rems = Rems(1.375);+}++/// Region and lane widths. Each is the comfortable default for its content at+/// the default rem; they scale with zoom like everything else.+pub mod size {+ use super::Rems;++ /// The volume meter in the status bar.+ pub const SPACE_METER: Rems = Rems(20.0);+ /// The scan meter in the status bar.+ pub const SCAN_METER: Rems = Rems(15.0);+ /// The meter on the scanning panel.+ pub const SCANNING_METER: Rems = Rems(26.25);+ /// The Size | Files choice in the settings row.+ pub const RANKING_CHOICE: Rems = Rems(8.5);+ /// The review screen's summary column.+ pub const REVIEW_SUMMARY: Rems = Rems(22.5);+ /// The review list's share-bar lane.+ pub const SHARE_LANE: Rems = Rems(6.0);+ /// The review list's size lane: right-aligned, so sizes compare.+ pub const SIZE_LANE: Rems = Rems(5.0);+ /// The cursor tooltip.+ pub const TOOLTIP: Rems = Rems(16.75);+ /// The keyboard overlay.+ pub const HELP: Rems = Rems(32.5);+ /// The key column of the keyboard overlay.+ pub const KEY_LANE: Rems = Rems(7.0);+}++/// Interface zoom steps, as a factor of the 16 px default rem.+pub const ZOOM_STEPS: [f32; 7] = [0.75, 0.875, 1.0, 1.125, 1.25, 1.5, 1.75];++/// The default rem, in pixels.+pub const BASE_REM: f32 = 16.0;diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rsnew file mode 100644index 0000000..e0dcf6d--- /dev/null+++ b/crates/disktree-app/src/views.rs@@ -0,0 +1,1916 @@+//! The screens: explore, review, running and done.+//!+//! Each function is a pure reading of [`Disktree`], so what a screen shows is+//! always exactly what the state says — there is no second copy of anything to+//! keep in sync.++use disktree_core::removal::{RemovalMode, Target};+use disktree_core::size::human_bytes;+use disktree_core::tree::Metric;+use gpui_kit::{+ App, Context, Div, ElementId, FontWeight, InteractiveElement as _,+ IntoElement, KeyDownEvent, ParentElement, SharedString, Stateful,+ StatefulInteractiveElement as _, Styled, Window, div, px,+};+use gpui_omarchy::{+ ActiveTheme, ButtonVariant, ChoiceItem, Theme, alert_dialog, button,+ button_group, dialog_button, dialog_description, dialog_popup,+ dialog_title, separator, toggle, with_tooltip,+};++use gpui_kit::prelude::FluentBuilder as _;++use crate::state::{Disktree, Screen};+use crate::treemap_view::{self, Mosaic};+use crate::ui::{icon, size, space, text};+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 = 62.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.+const LIST_LIMIT: usize = 1200;++/// The whole window.+pub fn root(+ app: &mut Disktree,+ window: &mut Window,+ cx: &mut Context<'_, Disktree>,+) -> Stateful<Div> {+ let theme = cx.omarchy().clone();+ let body = match app.screen {+ Screen::Explore => explore(app, window, cx),+ Screen::Review => review(app, window, cx),+ Screen::Running => running(app, cx),+ Screen::Done => done(app, cx),+ };++ let mut root = div()+ .id("disktree-root")+ .debug_selector(|| "disktree-root".into())+ .track_focus(&app.focus)+ .key_context("Disktree")+ // The listener is the only place with a window in hand, so it is also+ // where the titlebar is kept in step with the directory on screen.+ .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| {+ if this.zoom_interface(event, window) {+ cx.notify();+ return;+ }+ let moved = this.on_key_down(event, cx);+ this.apply_focus(window, cx);+ if moved {+ let path = this.current_path();+ let title = format!(+ "disktree · {}",+ crate::marks::display_path(&path, this.home.as_deref())+ );+ window.set_window_title(&title);+ }+ }))+ .relative()+ .flex()+ .flex_col()+ .size_full()+ .bg(theme.background)+ .text_color(theme.foreground)+ .font_family(theme.font)+ .text_size(text::BODY)+ .child(body);+ if let Some(tip) = cursor_tooltip(app, window, cx) {+ root = root.child(tip);+ }+ if app.show_help {+ root = root.child(help_overlay(app, cx));+ }+ if app.confirm_open {+ root = root.child(delete_dialog(app, cx));+ }+ root+}++/// The one question disktree asks: a permanent deletion cannot be undone, so+/// it is an alert dialog that names what goes and what comes back. The trash is+/// reversible and needs no dialog.+fn delete_dialog(+ app: &Disktree,+ cx: &mut Context<'_, Disktree>,+) -> impl IntoElement {+ let plan = app.plan();+ let title = match plan.targets.as_slice() {+ [only] => format!(+ "Delete \u{201c}{}\u{201d} permanently?",+ short_name(&only.path)+ ),+ targets => format!("Delete {} items permanently?", targets.len()),+ };+ let body = format!(+ "This frees {}. Deleted files can\u{2019}t be recovered; move them to the trash if you might need them again.",+ human_bytes(plan.bytes())+ );+ let confirm = cx.entity().downgrade();+ let cancel = confirm.clone();+ let actions = div()+ .flex()+ .flex_row()+ .justify_end()+ .gap(space::SM)+ .child(+ dialog_button(+ "delete-cancel",+ "Cancel",+ ButtonVariant::Secondary,+ cx,+ )+ .on_click(cx.listener(|this, _, window, cx| {+ this.cancel_delete(cx);+ this.apply_focus(window, cx);+ })),+ )+ .child(+ dialog_button(+ "delete-confirm",+ "Delete",+ ButtonVariant::Danger,+ cx,+ )+ .on_click(cx.listener(|this, _, window, cx| {+ this.confirm_delete(cx);+ this.apply_focus(window, cx);+ })),+ );+ let popup = dialog_popup(cx)+ .child(dialog_title(title, cx))+ .child(dialog_description(body, cx))+ .child(actions);+ alert_dialog(&app.confirm_focus, cx)+ .open(true)+ .on_ok(move |_, window, cx| {+ let _ = confirm.update(cx, |this, cx| {+ this.confirm_delete(cx);+ this.apply_focus(window, cx);+ });+ false+ })+ .on_cancel(move |_, window, cx| {+ let _ = cancel.update(cx, |this, cx| {+ this.cancel_delete(cx);+ this.apply_focus(window, cx);+ });+ false+ })+ .popup(popup)+}++// ── explore ─────────────────────────────────────────────────────────────++fn explore(+ app: &mut Disktree,+ window: &mut Window,+ cx: &mut Context<'_, Disktree>,+) -> Div {+ let theme = cx.omarchy().clone();+ let mosaic: Mosaic = app.prepare();+ let selection = app.show_selection;+ // Below this width the header cannot hold title, settings and totals on+ // one line; the totals move to the status bar rather than wrapping.+ let wide =+ window.viewport_size().width.as_f32() / app.rem >= HEADER_WIDE_REMS;+ let header = explore_header(app, &theme, wide, window, cx);+ let trail = breadcrumbs(app, &theme, cx);++ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_h_0()+ .child(header)+ .child(trail)+ .child(div().flex().flex_row().flex_1().min_h_0().child(+ if app.tree().is_none() {+ // The first walk of a home directory takes long enough that+ // an empty viewport would look broken; count the work+ // instead of pretending there is nothing to see.+ scanning_panel(app, &theme, cx).into_any_element()+ } else {+ treemap_view::mosaic(mosaic, app, window, cx).into_any_element()+ },+ ))+ .children(selection.then(|| selection_bar(app, &theme, cx)))+ .child(status_bar(app, &theme, !wide, cx))+ .child(hint_bar(app, &theme, cx))+}++/// What the viewport shows while the first scan is running.+fn scanning_panel(app: &Disktree, theme: &Theme, cx: &gpui_kit::App) -> Div {+ let progress = &app.progress;+ let mut panel = div()+ .flex()+ .flex_col()+ .flex_1()+ .min_h_0()+ .items_center()+ .justify_center()+ .gap(space::LG)+ .bg(theme.inset)+ .child(+ gpui_omarchy::icon(gpui_omarchy::IconName::Loader)+ .size(icon::LG)+ .text_color(theme.accent),+ )+ .child(+ div()+ .text_size(text::TITLE)+ .font_weight(FontWeight::SEMIBOLD)+ .text_color(theme.bright)+ .child(format!("Reading {}", widgets::display_root(app))),+ )+ .child(+ div()+ .flex()+ .flex_row()+ .gap(space::XL)+ .child(widgets::stat(+ "files",+ widgets::human_count(progress.files),+ cx,+ ))+ .child(widgets::stat("directories", widgets::human_count(progress.dirs), cx))+ .child(widgets::stat("measured", human_bytes(progress.bytes), cx))+ .child(widgets::stat_colored(+ "unreadable",+ widgets::human_count(progress.errors),+ if progress.errors > 0 {+ theme.warning+ } else {+ theme.secondary+ },+ cx,+ )),+ )+ .child(+ div()+ .w(size::SCANNING_METER)+ .child(widgets::meter_row(+ "",+ "",+ progress_estimate(progress.files),+ theme.accent,+ cx,+ )),+ )+ .child(+ div()+ .text_size(text::BODY)+ .text_color(theme.secondary)+ .child("Marking, zooming and the free-space meter all work as soon as it lands."),+ );++ if let Some(error) = &app.scan_error {+ panel = panel.child(+ div()+ .max_w(size::HELP)+ .p(space::MD)+ .border_1()+ .border_color(theme.danger)+ .text_color(theme.danger)+ .text_size(text::BODY)+ .child(error.clone()),+ );+ }+ panel+}++fn explore_header(+ app: &Disktree,+ theme: &Theme,+ wide: bool,+ window: &mut Window,+ cx: &mut Context<'_, Disktree>,+) -> Div {+ let tree = app.tree();+ let scanned = tree.map_or(0, |node| node.bytes);+ let files = tree.map_or(0, |node| node.files);+ let dirs = tree.map_or(0, |node| node.dirs);++ let mut row = div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::MD)+ .px(space::LG)+ .py(space::MD)+ // Leading: the app and what the whole scan found. Trailing: the+ // controls that decide what is measured, on the edge they own. The+ // breadcrumb below names only the place.+ .child(+ div()+ .flex_shrink_0()+ .text_size(text::TITLE)+ .font_weight(FontWeight::BOLD)+ .text_color(theme.bright)+ .child("disktree"),+ );+ if wide {+ row = row+ .child(div().w(space::MD))+ .child(widgets::stat("Scanned", human_bytes(scanned), cx))+ .child(widgets::stat("Files", widgets::human_count(files), cx))+ .child(widgets::stat(+ "Directories",+ widgets::human_count(dirs),+ cx,+ ));+ }+ row = row.child(div().flex_1());+ if app.find_open || !app.find.is_empty() {+ row = row.child(find_field(app, theme));+ }+ row.child(view_settings(app, window, cx))+}++fn find_field(app: &Disktree, theme: &Theme) -> Div {+ div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::SM)+ .px(space::SM)+ .py(space::XS)+ .border_1()+ .border_color(if app.find_open {+ theme.accent+ } else {+ theme.control_border()+ })+ .bg(theme.normal_fill())+ .text_size(text::BODY)+ .child(+ gpui_omarchy::icon(gpui_omarchy::IconName::Search)+ .size(icon::SM)+ .text_color(theme.secondary),+ )+ .child(if app.find.is_empty() {+ div()+ .text_color(theme.secondary.opacity(0.7))+ .child("Find by name")+ } else {+ div().text_color(theme.bright).child(app.find.clone())+ })+}++fn breadcrumbs(+ app: &Disktree,+ theme: &Theme,+ cx: &Context<'_, Disktree>,+) -> Div {+ let trail = app.breadcrumbs();+ let last = trail.len().saturating_sub(1);+ let mut row = div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::XXS)+ .px(space::LG)+ .py(space::SM)+ .min_h_0()+ .border_b_1()+ .border_color(theme.divider());++ for (index, (label, crumbs)) in trail.into_iter().enumerate() {+ if index > 0 {+ row = row.child(+ div()+ .text_color(theme.secondary.opacity(0.6))+ .text_size(text::CAPTION)+ .child("/"),+ );+ }+ let active = index == last;+ let id = ElementId::Name(SharedString::from(format!("crumb-{index}")));+ row = row.child(widgets::crumb(id, label, active, cx).on_click(+ cx.listener(move |this, _, _, cx| this.go_to(crumbs.clone(), cx)),+ ));+ }++ row+}++/// How the mosaic is measured and drawn, as real controls with visible state.+///+/// Every control hands the keyboard straight back to the treemap: arrows,+/// Space and Enter belong to the tiles, and a settings click must not quietly+/// capture them.+fn view_settings(+ app: &Disktree,+ window: &mut Window,+ cx: &mut Context<'_, Disktree>,+) -> Div {+ let focus = app.focus.clone();+ let entity = cx.entity().downgrade();++ let ranking = {+ let entity = entity.clone();+ let focus = focus.clone();+ button_group(+ "ranking",+ vec![+ ChoiceItem::new("bytes", "Size"),+ ChoiceItem::new("files", "Files"),+ ],+ Some(usize::from(app.options.metric == Metric::Files)),+ move |index, window, cx| {+ let _ = entity.update(cx, |this, cx| {+ let wanted = if index == 0 {+ Metric::Bytes+ } else {+ Metric::Files+ };+ if this.options.metric != wanted {+ this.toggle_metric(cx);+ }+ });+ window.focus(&focus, cx);+ },+ window,+ cx,+ )+ .w(size::RANKING_CHOICE)+ // Tighter than a standalone group, so the segmented control shares+ // the toggles' height and centre line in this toolbar row.+ .p(space::XXS)+ };++ let hidden = {+ let entity = entity.clone();+ let focus = focus.clone();+ toggle("hidden", "Hidden files", app.options.include_hidden, cx)+ .tab_stop(false)+ .on_change(move |_, _, window, cx| {+ let _ = entity.update(cx, |this, cx| {+ this.options.include_hidden = !this.options.include_hidden;+ this.start_scan(cx);+ });+ window.focus(&focus, cx);+ })+ };++ let apparent = {+ toggle("apparent", "Apparent size", app.options.apparent_size, cx)+ .tab_stop(false)+ .on_change(move |_, _, window, cx| {+ let _ = entity.update(cx, |this, cx| {+ this.options.apparent_size = !this.options.apparent_size;+ this.start_scan(cx);+ });+ window.focus(&focus, cx);+ })+ };++ let depth = app.layout_options.max_depth;+ let levels = with_tooltip(+ button(+ "levels",+ format!("{depth} levels"),+ // Outline, like the toggles beside it: bare text reads as a label.+ ButtonVariant::Outline,+ cx,+ )+ .tab_stop(false)+ .on_click(cx.listener(|this, _, window, cx| {+ // Cycles, so the pointer can reach every depth; the keys step.+ let step = if this.layout_options.max_depth >= 6 {+ -5+ } else {+ 1+ };+ this.adjust_depth(step, cx);+ window.focus(&this.focus, cx);+ })),+ "Levels drawn at once \u{00b7} [ and ]",+ );++ div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::SM)+ .child(ranking)+ .child(hidden)+ .child(apparent)+ .child(levels)+}++/// What the keys act on, as one line above the status bar: name and path,+/// size and share, and the two actions that apply to it. The mosaic keeps the+/// full width of the window.+fn selection_bar(+ app: &Disktree,+ theme: &Theme,+ cx: &Context<'_, Disktree>,+) -> Div {+ let target = app.action_target().unwrap_or_else(|| app.crumbs.clone());+ let row = div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::XL)+ .px(space::LG)+ .py(space::SM)+ .border_t_1()+ .border_color(theme.divider())+ .bg(theme.surface);++ let Some(node) = app.node_at(&target) else {+ return row.child(+ div()+ .text_color(theme.secondary)+ .child("Point at a tile or select one with the arrows"),+ );+ };+ let path = app.path_at(&target);+ let parent = target[..target.len().saturating_sub(1)].to_vec();+ let parent_value = app.node_at(&parent).map_or(0, |node| node.bytes);+ let root_value = app.tree().map_or(0, |tree| tree.bytes);+ let marked = path.as_deref().is_some_and(|path| app.marks.contains(path));+ let covered_by = marks_ancestor(app, path.as_deref());+ let is_current_root = target == app.crumbs;++ // Identity: the lane that shrinks, so a long path truncates instead of+ // pushing the actions off the edge.+ let identity = div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::SM)+ .flex_1()+ .min_w_0()+ .child(+ gpui_omarchy::icon(if node.is_dir() {+ gpui_omarchy::IconName::FolderOpen+ } else {+ gpui_omarchy::IconName::File+ })+ .size(icon::MD)+ .flex_shrink_0()+ .text_color(theme.secondary),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .gap(space::XXS)+ .min_w_0()+ .overflow_hidden()+ .child(+ div()+ .text_size(text::TITLE)+ .font_weight(FontWeight::SEMIBOLD)+ .text_color(theme.bright)+ .whitespace_nowrap()+ .child(node.name.to_string()),+ )+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .whitespace_nowrap()+ .child(path.as_deref().map_or_else(+ String::new,+ |path| {+ crate::marks::display_path(+ path,+ app.home.as_deref(),+ )+ },+ )),+ ),+ );++ // Badges stay neutral unless the state is a real deletion or warning.+ let mut badges = div().flex().flex_row().gap(space::XS).flex_shrink_0();+ if node.name.starts_with('.') {+ badges = badges.child(widgets::chip("Hidden", theme.secondary, cx));+ }+ if marked {+ badges = badges.child(widgets::chip("Marked", theme.danger, cx));+ }+ if let Some(ancestor) = &covered_by {+ badges = badges.child(widgets::chip(+ format!("Inside marked {ancestor}"),+ theme.secondary,+ cx,+ ));+ }+ if node.read_error {+ badges = badges.child(widgets::chip("Unreadable", theme.warning, cx));+ }++ // Measure: the size, then its share, then what it holds.+ let measure = div()+ .flex()+ .flex_col()+ .gap(space::XXS)+ .flex_shrink_0()+ .items_end()+ .child(+ div()+ .text_size(text::TITLE)+ .font_weight(FontWeight::BOLD)+ .text_color(theme.bright)+ .child(widgets::value(node, app.options.metric)),+ )+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(format!(+ "{} of its directory \u{00b7} {} of the scan \u{00b7} {} files",+ widgets::percent(node.bytes, parent_value),+ widgets::percent(node.bytes, root_value),+ widgets::human_count(node.files),+ )),+ );++ // One primary, only where it is what Enter does. Marking is reversible,+ // so it is framed but neither primary nor danger. Both hand the keyboard+ // back to the treemap.+ let mut actions = div().flex().flex_row().gap(space::SM).flex_shrink_0();+ if !is_current_root && node.is_dir() {+ let crumbs = target.clone();+ actions = actions.child(+ button("open", "Open", ButtonVariant::Primary, cx)+ .tab_stop(false)+ .on_click(cx.listener(move |this, _, window, cx| {+ this.go_to(crumbs.clone(), cx);+ window.focus(&this.focus, cx);+ })),+ );+ }+ if !is_current_root {+ let crumbs = target;+ actions = actions.child(+ button(+ "mark",+ if marked { "Unmark" } else { "Mark for removal" },+ ButtonVariant::Outline,+ cx,+ )+ .tab_stop(false)+ .on_click(cx.listener(move |this, _, window, cx| {+ this.toggle_mark(&crumbs.clone(), cx);+ window.focus(&this.focus, cx);+ })),+ );+ }++ row.child(identity)+ .child(badges)+ .child(measure)+ .child(actions)+}++fn short_name(path: &std::path::Path) -> String {+ path.file_name().map_or_else(+ || path.display().to_string(),+ |name| name.to_string_lossy().into_owned(),+ )+}++/// The marked ancestor of a path, if any, so the UI can explain nesting.+fn marks_ancestor(+ app: &Disktree,+ path: Option<&std::path::Path>,+) -> Option<String> {+ let path = path?;+ app.marks+ .items()+ .iter()+ .filter(|item| item.path != path && path.starts_with(&item.path))+ .map(|item| short_name(&item.path))+ .next()+}++/// The volume and the marks: what was found, what it will free, and the+/// command that acts on the marks, next to the marks it acts on.+fn status_bar(+ app: &Disktree,+ theme: &Theme,+ show_totals: bool,+ cx: &Context<'_, Disktree>,+) -> Div {+ let plan = app.plan();+ let reclaiming = plan.bytes();+ let marked = app.marks.len();+ let mut row = div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::LG)+ .px(space::LG)+ .py(space::SM)+ .border_t_1()+ .border_color(theme.divider())+ .bg(theme.surface);++ row =+ row.child(div().w(size::SPACE_METER).flex_shrink_0().when_some(+ app.space,+ |this, space| {+ this.child(widgets::space_meter(space, reclaiming, cx))+ },+ ));++ row = row.child(+ div()+ .flex()+ .flex_col()+ .gap(space::XXS)+ .child(widgets::stat_colored(+ "Marked for removal",+ if marked == 0 {+ "Nothing marked".to_string()+ } else {+ format!(+ "{marked} items \u{00b7} {}",+ human_bytes(reclaiming)+ )+ },+ if marked > 0 {+ theme.danger+ } else {+ theme.secondary+ },+ cx,+ ))+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(if marked == 0 {+ "Space marks the tile you point at".to_string()+ } else if !plan.covered.is_empty()+ || !plan.blocked.is_empty()+ {+ format!(+ "{} nested \u{00b7} {} kept back",+ plan.covered.len(),+ plan.blocked.len()+ )+ } else if app.removal_mode == RemovalMode::Trash {+ "Will move to the trash".to_string()+ } else {+ "Will delete permanently".to_string()+ }),+ ),+ );++ if marked > 0 {+ row = row.child(+ button("review", "Review\u{2026}", ButtonVariant::Secondary, cx)+ .tab_stop(false)+ .on_click(cx.listener(|this, _, window, cx| {+ this.screen = Screen::Review;+ cx.notify();+ window.focus(&this.focus, cx);+ })),+ );+ }++ row = row.child(div().flex_1());++ if app.scan.is_some() {+ let progress = &app.progress;+ row = row.child(+ div()+ .flex()+ .flex_col()+ .gap(space::XS)+ .w(size::SCAN_METER)+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(format!(+ "Scanning \u{00b7} {} files \u{00b7} {}",+ widgets::human_count(progress.files),+ human_bytes(progress.bytes)+ )),+ )+ .child(widgets::meter_row(+ "",+ "",+ progress_estimate(progress.files),+ theme.accent,+ cx,+ )),+ );+ } else {+ if show_totals && let Some(tree) = app.tree() {+ row = row.child(widgets::stat(+ "Scanned",+ human_bytes(tree.bytes),+ cx,+ ));+ }+ row = row.child(widgets::stat(+ "Entries read",+ widgets::human_count(app.progress.files),+ cx,+ ));+ if app.progress.errors > 0 {+ row = row.child(widgets::stat_colored(+ "Unreadable",+ format!("{} paths", app.progress.errors),+ theme.warning,+ cx,+ ));+ }+ }++ if let Some((message, status)) = &app.notice {+ row = row.child(+ div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::SM)+ .px(space::SM)+ .py(space::XS)+ .border_1()+ .border_color(widgets::alert_color(*status, cx).opacity(0.5))+ .text_color(widgets::alert_color(*status, cx))+ .text_size(text::CAPTION)+ .child(message.clone()),+ );+ }+ if let Some(error) = &app.scan_error {+ row = row.child(+ div()+ .text_color(theme.danger)+ .text_size(text::CAPTION)+ .child(error.clone()),+ );+ }++ row+}++/// A scan has no total to measure against, so the meter shows the work done+/// rather than pretending to know how far along it is.+fn progress_estimate(files: u64) -> f32 {+ if files == 0 {+ 0.06+ } else {+ // Asymptotic: the bar keeps moving while the walk continues.+ let scaled = files as f32 / (files as f32 + 20_000.0);+ (0.1 + scaled * 0.85).min(0.99)+ }+}++fn hint_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div {+ // Most useful first, so a narrow window clips the least useful. The key+ // to every other key is pinned to the trailing edge and never clipped.+ let hints: [(&str, &str); 10] = [+ ("space", "mark"),+ ("enter", "open"),+ ("\u{232b}", "up"),+ ("c", "review"),+ ("\u{2190}\u{2191}\u{2193}\u{2192}", "move"),+ ("/", "find"),+ ("scroll", "zoom"),+ ("[ ]", "levels"),+ ("0", "reset"),+ ("r", "rescan"),+ ];+ let mut lane = div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::LG)+ .flex_1()+ .min_w_0()+ .overflow_hidden();+ for (keys, label) in hints {+ lane = lane.child(widgets::hint(keys, label, cx).flex_shrink_0());+ }++ let mut row = div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::LG)+ .px(space::LG)+ .py(space::SM)+ .border_t_1()+ .border_color(theme.divider())+ .bg(theme.background)+ .child(lane);+ // The magnification only earns space when it is not the default.+ if (app.view.scale - 1.0).abs() > 0.01 {+ row = row.child(+ div()+ .flex_shrink_0()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(format!("{:.1}\u{00d7}", app.view.scale)),+ );+ }+ row.child(widgets::hint("?", "all keys", cx).flex_shrink_0())+}++// ── review ──────────────────────────────────────────────────────────────++fn review(+ app: &Disktree,+ window: &mut Window,+ cx: &mut Context<'_, Disktree>,+) -> Div {+ let theme = cx.omarchy().clone();+ let plan = app.plan();+ let items: Vec<Target> = app.marks.items().to_vec();+ let covered: Vec<Target> = plan.covered.clone();+ let blocked = plan.blocked.clone();++ let mut list = div()+ .id("marked-list")+ .flex()+ .flex_col()+ .flex_1()+ .min_w_0()+ .overflow_y_scroll()+ .border_1()+ .border_color(theme.border)+ .bg(theme.inset);++ if items.is_empty() {+ list = list.child(+ div()+ .p(space::XXL)+ .text_color(theme.secondary)+ .child("Nothing is marked. Go back and mark what should go."),+ );+ }++ for (index, item) in items.iter().take(LIST_LIMIT).enumerate() {+ let is_covered =+ covered.iter().any(|covered| covered.path == item.path);+ let blocked_reason = blocked+ .iter()+ .find(|blocked| blocked.path == item.path)+ .map(|blocked| blocked.reason.clone());+ list = list.child(mark_row(+ index,+ item,+ is_covered,+ blocked_reason,+ app,+ &theme,+ cx,+ ));+ }+ if items.len() > LIST_LIMIT {+ list = list.child(+ div()+ .px(space::MD)+ .py(space::SM)+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(format!(+ "{} more are marked and will be removed too. Unmark them in the treemap.",+ items.len() - LIST_LIMIT+ )),+ );+ }++ let summary = review_summary(app, &plan, &theme, window, cx);+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_h_0()+ .child(screen_header(+ "Review",+ &format!(+ "{} marked \u{00b7} {} to free",+ app.marks.len(),+ human_bytes(plan.bytes())+ ),+ &theme,+ cx,+ ))+ .child(+ div()+ .flex()+ .flex_row()+ .gap(space::LG)+ .p(space::LG)+ .flex_1()+ .min_h_0()+ .child(list)+ .child(summary),+ )+ .child(review_footer(app, &theme, cx))+}++/// One marked path. Lanes are fixed, so names, bars and sizes line up down+/// the list and sizes can be compared by eye.+fn mark_row(+ index: usize,+ item: &Target,+ covered: bool,+ blocked: Option<String>,+ app: &Disktree,+ theme: &Theme,+ cx: &Context<'_, Disktree>,+) -> Div {+ let root_value = app.tree().map_or(0, |tree| tree.bytes);+ let path_text = crate::marks::display_path(&item.path, app.home.as_deref());+ let color = if blocked.is_some() || covered {+ theme.secondary+ } else {+ theme.foreground+ };+ div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::MD)+ .px(space::MD)+ .py(space::SM)+ .border_b_1()+ .border_color(theme.divider())+ .child(+ gpui_omarchy::icon(if item.is_dir {+ gpui_omarchy::IconName::FolderOpen+ } else {+ gpui_omarchy::IconName::File+ })+ .size(icon::SM)+ .flex_shrink_0()+ .text_color(theme.secondary),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .gap(space::XXS)+ .min_w_0()+ .flex_1()+ .child(+ div()+ .min_w_0()+ .text_color(color)+ .child(short_name(&item.path)),+ )+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(path_text),+ ),+ )+ .children(covered.then(|| {+ widgets::chip("Inside a marked directory", theme.secondary, cx)+ }))+ .children(+ blocked.map(|reason| widgets::chip(reason, theme.warning, cx)),+ )+ .child(div().w(size::SHARE_LANE).flex_shrink_0().child(+ widgets::glyph_bar(+ item.bytes,+ root_value.max(1),+ 8,+ theme.secondary,+ cx,+ ),+ ))+ .child(+ // Comparable numbers right-align.+ div()+ .w(size::SIZE_LANE)+ .flex_shrink_0()+ .flex()+ .justify_end()+ .text_color(theme.bright)+ .child(human_bytes(item.bytes)),+ )+ .child(+ button(+ ElementId::Name(SharedString::from(format!("unmark-{index}"))),+ "Unmark",+ ButtonVariant::Outline,+ cx,+ )+ .on_click(cx.listener({+ let path = item.path.clone();+ move |this, _, _, cx| this.unmark(&path.clone(), cx)+ })),+ )+}++fn review_summary(+ app: &Disktree,+ plan: &disktree_core::removal::Plan,+ theme: &Theme,+ window: &mut Window,+ cx: &mut Context<'_, Disktree>,+) -> Div {+ let reclaiming = plan.bytes();+ let trash = app.trash_backend.is_available();++ // One silhouette for one either-or choice, reversible option first.+ let entity = cx.entity().downgrade();+ let mode = button_group(+ "removal-mode",+ vec![+ ChoiceItem::new("trash", "Move to trash").disabled(!trash),+ ChoiceItem::new("permanent", "Delete permanently"),+ ],+ Some(usize::from(app.removal_mode == RemovalMode::Permanent)),+ move |index, _, cx| {+ let _ = entity.update(cx, |this, cx| {+ this.removal_mode = if index == 0 {+ RemovalMode::Trash+ } else {+ RemovalMode::Permanent+ };+ cx.notify();+ });+ },+ window,+ cx,+ );++ let explanation = match app.removal_mode {+ RemovalMode::Trash => format!(+ "Recoverable from the trash until it is emptied. Uses {}.",+ app.trash_backend.label()+ ),+ RemovalMode::Permanent => {+ "Deleted at once, like rm -rf. Nothing is recoverable.".to_string()+ }+ };++ let mut panel = div()+ .flex()+ .flex_col()+ .gap(space::XL)+ .w(size::REVIEW_SUMMARY)+ .flex_shrink_0()+ .p(space::LG)+ .border_1()+ .border_color(theme.border)+ .bg(theme.surface)+ .child(+ div()+ .flex()+ .flex_col()+ .gap(space::SM)+ .child(widgets::section("What happens", cx))+ .child(mode)+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(explanation),+ ),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .gap(space::SM)+ .child(widgets::section("Totals", cx))+ .child(widgets::row(+ "Marked",+ format!("{}", app.marks.len()),+ cx,+ ))+ .child(widgets::row(+ "Acted on",+ format!("{}", plan.targets.len()),+ cx,+ ))+ .child(widgets::row(+ "Nested, go with a parent",+ format!("{}", plan.covered.len()),+ cx,+ ))+ .child(widgets::row(+ "Kept back",+ format!("{}", plan.blocked.len()),+ cx,+ ))+ .child(widgets::row(+ "Space freed",+ human_bytes(reclaiming),+ cx,+ )),+ );++ if let Some(volume) = app.space {+ panel = panel.child(+ div()+ .flex()+ .flex_col()+ .gap(space::SM)+ .child(widgets::section("Volume", cx))+ .child(widgets::space_meter(volume, reclaiming, cx)),+ );+ }++ if !plan.blocked.is_empty() {+ let mut blocked = div().flex().flex_col().gap(space::XS);+ for item in plan.blocked.iter().take(6) {+ blocked = blocked.child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.warning)+ .child(format!(+ "{}: {}",+ short_name(&item.path),+ item.reason+ )),+ );+ }+ panel = panel.child(+ div()+ .flex()+ .flex_col()+ .gap(space::XS)+ .child(widgets::section("Kept back", cx))+ .child(blocked),+ );+ }++ panel+ .child(div().flex_1())+ .child(commit_controls(app, plan, cx))+}++/// The screen's one commitment. Moving to the trash is the default commit,+/// so it is the primary action; a permanent deletion is destructive, so it is+/// the danger action and asks first, which its ellipsis promises.+fn commit_controls(+ app: &Disktree,+ plan: &disktree_core::removal::Plan,+ cx: &Context<'_, Disktree>,+) -> Div {+ let count = plan.targets.len();+ let noun = if count == 1 { "item" } else { "items" };+ let (label, variant) = match app.removal_mode {+ RemovalMode::Trash => (+ format!("Move {count} {noun} to trash"),+ ButtonVariant::Primary,+ ),+ RemovalMode::Permanent => (+ format!("Delete {count} {noun}\u{2026}"),+ ButtonVariant::Danger,+ ),+ };+ let unavailable = plan.is_empty()+ || (app.removal_mode == RemovalMode::Trash+ && !app.trash_backend.is_available());++ div()+ .flex()+ .flex_row()+ .justify_end()+ .gap(space::SM)+ .child(+ button("back", "Back", ButtonVariant::Secondary, cx).on_click(+ cx.listener(|this, _, window, cx| {+ this.screen = Screen::Explore;+ cx.notify();+ window.focus(&this.focus, cx);+ }),+ ),+ )+ .child(+ button("commit", label, variant, cx)+ .disabled(unavailable)+ .on_click(cx.listener(|this, _, window, cx| {+ this.commit(cx);+ this.apply_focus(window, cx);+ })),+ )+}++fn review_footer(app: &Disktree, theme: &Theme, cx: &App) -> Div {+ let commit = match app.removal_mode {+ RemovalMode::Trash => "move to trash",+ RemovalMode::Permanent => "delete\u{2026}",+ };+ div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::LG)+ .px(space::LG)+ .py(space::SM)+ .border_t_1()+ .border_color(theme.divider())+ .child(widgets::hint("enter", commit, cx))+ .child(widgets::hint("m", "trash", cx))+ .child(widgets::hint("p", "permanent", cx))+ .child(widgets::hint("!", "unmark all", cx))+ .child(widgets::hint("esc", "back", cx))+ .child(div().flex_1())+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(format!(+ "{} available",+ app.space.map_or_else(+ || "?".into(),+ |space| human_bytes(space.available)+ )+ )),+ )+}++// ── running ─────────────────────────────────────────────────────────────++fn running(app: &Disktree, cx: &gpui_kit::Context<'_, Disktree>) -> Div {+ let theme = cx.omarchy().clone();+ let summary = app.run_summary.clone();+ let done = summary.removed + summary.failed as u64;+ let progress = if summary.total == 0 {+ 0.0+ } else {+ done as f32 / summary.total as f32+ };++ let mut log = div()+ .id("run-log")+ .flex()+ .flex_col()+ .flex_1()+ .min_h_0()+ .overflow_y_scroll()+ .border_1()+ .border_color(theme.border)+ .bg(theme.inset);+ for (path, outcome) in app.run_log.iter().rev().take(200) {+ let ok = outcome.is_ok();+ log = log.child(+ div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::SM)+ .px(space::MD)+ .py(space::XS)+ .text_size(text::CAPTION)+ .child(+ gpui_omarchy::icon(if ok {+ gpui_omarchy::IconName::Check+ } else {+ gpui_omarchy::IconName::X+ })+ .size(icon::SM)+ .text_color(if ok {+ theme.success+ } else {+ theme.danger+ }),+ )+ .child(+ div()+ .flex_1()+ .min_w_0()+ .text_color(if ok {+ theme.foreground+ } else {+ theme.danger+ })+ .child(short_name(path)),+ )+ .children(outcome.as_ref().err().map(|error| {+ div()+ .text_size(text::CAPTION)+ .text_color(theme.warning)+ .child(error.clone())+ })),+ );+ }++ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_h_0()+ .child(screen_header(+ "Removing",+ &format!("{} of {} done", done, summary.total),+ &theme,+ cx,+ ))+ .child(+ div()+ .flex()+ .flex_col()+ .gap(space::MD)+ .p(space::LG)+ .flex_1()+ .min_h_0()+ .child(widgets::meter_row(+ "progress",+ format!(+ "{} removed · {} to free",+ summary.removed,+ human_bytes(summary.bytes)+ ),+ progress,+ if app.removal_mode == RemovalMode::Permanent {+ theme.danger+ } else {+ theme.accent+ },+ cx,+ ))+ .children(+ app.space.map(|space| widgets::space_meter(space, 0, cx)),+ )+ .child(log),+ )+ .child(+ div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::LG)+ .px(space::LG)+ .py(space::SM)+ .border_t_1()+ .border_color(theme.divider())+ .child(widgets::hint("esc", "stop after the current item", cx)),+ )+}++// ── done ────────────────────────────────────────────────────────────────++fn done(app: &Disktree, cx: &gpui_kit::Context<'_, Disktree>) -> Div {+ let theme = cx.omarchy().clone();+ let summary = app.run_summary.clone();+ let measured = match (app.space_baseline, app.space) {+ (Some(before), Some(after)) => Some(+ after+ .available+ .cast_signed()+ .saturating_sub(before.available.cast_signed()),+ ),+ _ => None,+ };++ let mut failures = div().flex().flex_col().gap(space::XXS);+ for (path, outcome) in app+ .run_log+ .iter()+ .filter(|(_, outcome)| outcome.is_err())+ .take(40)+ {+ failures = failures.child(+ div()+ .flex()+ .flex_row()+ .gap(space::SM)+ .text_size(text::CAPTION)+ .child(div().text_color(theme.danger).child(short_name(path)))+ .child(div().text_color(theme.secondary).child(+ outcome.as_ref().err().cloned().unwrap_or_default(),+ )),+ );+ }++ let mut body = div()+ .flex()+ .flex_col()+ .gap(space::MD)+ .p(space::LG)+ .flex_1()+ .min_h_0()+ .child(+ div()+ .flex()+ .flex_row()+ .gap(space::XXL)+ .child(widgets::stat_colored(+ "removed",+ format!("{} items", summary.removed),+ theme.success,+ cx,+ ))+ .child(widgets::stat("bytes claimed", human_bytes(summary.bytes), cx))+ .child(widgets::stat_colored(+ "failed",+ format!("{}", summary.failed),+ if summary.failed > 0 {+ theme.danger+ } else {+ theme.secondary+ },+ cx,+ ))+ .children(measured.map(|delta| {+ widgets::stat_colored(+ "volume freed",+ if delta >= 0 {+ format!("+{}", human_bytes(delta.unsigned_abs()))+ } else {+ format!("-{}", human_bytes(delta.unsigned_abs()))+ },+ if delta >= 0 { theme.success } else { theme.warning },+ cx,+ )+ })),+ )+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child("The treemap is being re-scanned so the numbers on screen match the disk again."),+ );++ if let Some(space) = app.space {+ body = body.child(widgets::space_meter(space, 0, cx));+ }+ if app.scan.is_some() {+ body = body.child(widgets::meter_row(+ "re-scanning",+ format!("{} files", widgets::human_count(app.progress.files)),+ progress_estimate(app.progress.files),+ theme.accent,+ cx,+ ));+ }+ if summary.failed > 0 {+ body = body+ .child(separator(cx))+ .child(widgets::section("what could not be removed", cx))+ .child(failures);+ }++ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_h_0()+ .child(screen_header("Done", "removal finished", &theme, cx))+ .child(body)+ .child(+ div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::LG)+ .px(space::LG)+ .py(space::SM)+ .border_t_1()+ .border_color(theme.divider())+ .child(+ // An acknowledgement: the result is already on screen.+ button("continue", "Done", ButtonVariant::Primary, cx)+ .on_click(cx.listener(|this, _, window, cx| {+ this.screen = Screen::Explore;+ cx.notify();+ window.focus(&this.focus, cx);+ })),+ )+ .child(widgets::hint("enter", "continue", cx)),+ )+}++// ── shared ──────────────────────────────────────────────────────────────++fn screen_header(+ title: &str,+ subtitle: &str,+ theme: &Theme,+ cx: &gpui_kit::App,+) -> Div {+ let _ = cx;+ div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::MD)+ .px(space::LG)+ .py(space::MD)+ .border_b_1()+ .border_color(theme.divider())+ .child(+ div()+ .text_size(text::TITLE)+ .font_weight(FontWeight::BOLD)+ .text_color(theme.bright)+ .child(title.to_string()),+ )+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(subtitle.to_string()),+ )+}++/// A tooltip that follows the cursor above everything else in the window.+///+/// It is a layer of the root view rather than a child of the treemap, so it is+/// never clipped at the edge of the mosaic, and it tracks the pointer the+/// hover logic already maintains, so it cannot lag behind the tile it+/// describes.+pub fn cursor_tooltip(+ app: &Disktree,+ window: &Window,+ cx: &gpui_kit::App,+) -> Option<Div> {+ // Placement is in pixels because the pointer is; the card's own size and+ // gaps come from the rem scale so they follow interface zoom.+ const HEIGHT_REMS: f32 = 6.5;+ let rem = window.rem_size().as_f32();+ let width = size::TOOLTIP.0 * rem;+ let height = HEIGHT_REMS * rem;+ let gap = space::MD.0 * rem;+ let edge = space::XS.0 * rem;++ let pointer = app.pointer?;+ let content = hover_tooltip(app, cx)?;+ let origin = app.treemap_origin.get();+ let window_size = window.bounds().size;++ // Flip to the other side of the pointer rather than overflow the window.+ let anchor_x = origin.x.as_f32() + pointer.x.as_f32();+ let anchor_y = origin.y.as_f32() + pointer.y.as_f32();+ let x = if anchor_x + gap + width > window_size.width.as_f32() {+ (anchor_x - gap - width).max(edge)+ } else {+ anchor_x + gap+ };+ let y = if anchor_y + gap + height > window_size.height.as_f32() {+ (anchor_y - gap - height).max(edge)+ } else {+ 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()+ .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 tooltip content for the hovered tile: everything the tile cannot show.+pub fn hover_tooltip(app: &Disktree, 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 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));+ let hidden = node.name.starts_with('.');+ let covered = marks_ancestor(app, path.as_deref());++ let mut tip = div()+ .flex()+ .flex_col()+ .gap(space::XS)+ .child(+ div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::XS)+ .child(+ gpui_omarchy::icon(if node.is_dir() {+ gpui_omarchy::IconName::FolderOpen+ } else {+ gpui_omarchy::IconName::File+ })+ .size(icon::SM)+ .text_color(theme.secondary),+ )+ .child(+ div()+ .min_w_0()+ .font_weight(FontWeight::SEMIBOLD)+ .text_color(theme.bright)+ .child(node.name.to_string()),+ ),+ )+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(path.as_deref().map_or_else(String::new, |path| {+ crate::marks::display_path(path, app.home.as_deref())+ })),+ )+ .child(+ div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::SM)+ .child(+ div()+ .text_size(text::TITLE)+ .font_weight(FontWeight::BOLD)+ .text_color(theme.bright)+ .child(human_bytes(node.bytes)),+ )+ .child(widgets::glyph_bar(+ node.bytes,+ parent_value.max(1),+ 10,+ theme.secondary,+ cx,+ ))+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(widgets::percent(node.bytes, parent_value)),+ ),+ )+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(format!(+ "{} files · {} dirs · {} direct",+ widgets::human_count(node.files),+ widgets::human_count(+ node.dirs.saturating_sub(u64::from(node.is_dir()))+ ),+ human_bytes(node.own_bytes)+ )),+ );++ let mut badges = div().flex().flex_row().gap(space::XS).flex_wrap();+ if hidden {+ badges = badges.child(widgets::chip("Hidden", theme.secondary, cx));+ }+ if marked {+ badges =+ badges.child(widgets::chip("Marked for removal", theme.danger, cx));+ }+ if let Some(ancestor) = covered {+ badges = badges.child(widgets::chip(+ format!("Inside marked {ancestor}"),+ theme.secondary,+ cx,+ ));+ }+ tip = tip.child(badges);+ tip = tip.child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary.opacity(0.7))+ .child(if node.is_dir() {+ "space mark · enter open"+ } else {+ "space mark"+ }),+ );+ Some(tip)+}++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); 23] = [+ ("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"),+ (+ "\u{2190} \u{2191} \u{2193} \u{2192}",+ "Move between tiles at this level",+ ),+ ("tab", "Next largest sibling"),+ ("scroll", "Zoom toward a directory, then go into it"),+ ("shift-scroll", "Pan the magnified view"),+ ("[ / ]", "Draw fewer or more levels at once"),+ ("- / = / 0", "Magnify, shrink, or reset the view"),+ ("ctrl = / - / 0", "Interface zoom"),+ ("/", "Find an entry by name"),+ ("c", "Review the marked list"),+ ("t", "Rank by size or by file count"),+ ("r", "Scan again from the same root"),+ ("d", "Disk usage or apparent size"),+ ("i", "Include or skip hidden entries"),+ ("p", "Show or hide the selection line"),+ ("q", "Quit"),+ ("", ""),+ (+ "Review screen",+ "m trash \u{00b7} p permanent \u{00b7} ! unmark all",+ ),+ ("", "enter commits \u{00b7} esc goes back"),+ ("", "A permanent deletion always asks first"),+ ];++ let mut keys = div().flex().flex_col().gap(space::SM);+ for (key, label) in rows {+ if key.is_empty() && label.is_empty() {+ continue;+ }+ keys = keys.child(+ div()+ .flex()+ .flex_row()+ .gap(space::MD)+ .items_center()+ .child(+ div()+ .w(size::KEY_LANE)+ .flex_shrink_0()+ .text_size(text::CAPTION)+ .text_color(theme.accent)+ .child(key.to_string()),+ )+ .child(+ div()+ .text_size(text::BODY)+ .text_color(theme.foreground)+ .child(label.to_string()),+ ),+ );+ }++ div()+ .absolute()+ .inset_0()+ .flex()+ .items_center()+ .justify_center()+ .bg(theme.background.opacity(0.86))+ .child(+ div()+ .flex()+ .flex_col()+ .gap(space::MD)+ .w(size::HELP)+ .p(space::XL)+ .border_1()+ .border_color(theme.border)+ .bg(theme.surface)+ .child(+ div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::SM)+ .child(+ gpui_omarchy::icon(+ gpui_omarchy::IconName::Keyboard,+ )+ .size(icon::MD)+ .text_color(theme.accent),+ )+ .child(+ div()+ .text_size(text::TITLE)+ .font_weight(FontWeight::BOLD)+ .text_color(theme.bright)+ .child("Keyboard and mouse"),+ ),+ )+ .child(keys)+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(format!(+ "? or esc closes \u{00b7} {} \u{00b7} {}",+ app.root_path.display(),+ app.options.metric.label()+ )),+ ),+ )+}diff --git a/crates/disktree-app/src/widgets.rs b/crates/disktree-app/src/widgets.rsnew file mode 100644index 0000000..5849eb5--- /dev/null+++ b/crates/disktree-app/src/widgets.rs@@ -0,0 +1,347 @@+//! Small presentation pieces shared by the screens.+//!+//! Everything is built from the active Omarchy theme's tokens, and every piece+//! is a plain function over borrowed data so the screens stay readable.++use disktree_core::size::{human_bytes, human_bytes_short, share, share_bar};+use disktree_core::space::SpaceInfo;+use disktree_core::tree::{Metric, Node};+use gpui_kit::prelude::FluentBuilder as _;+use gpui_kit::{+ App, Div, ElementId, FontWeight, Hsla, InteractiveElement as _,+ ParentElement, SharedString, Styled, div, relative,+};+use gpui_omarchy::{ActiveTheme, Status};++use crate::ui::{space, text};++use crate::state::Disktree;++/// The scanned root, shortened to `~` where it is the home directory.+pub fn display_root(app: &Disktree) -> String {+ crate::marks::display_path(&app.root_path, app.home.as_deref())+}++/// File counts, which is what a directory count is too.+pub fn human_count(value: u64) -> String {+ disktree_core::size::human_count(value)+}++/// The value to show for a node under the active metric.+pub fn short_value(node: &Node, metric: Metric) -> String {+ match metric {+ Metric::Bytes => human_bytes_short(node.bytes),+ Metric::Files => human_count(node.files),+ }+}++/// The value to show in tables and headers.+pub fn value(node: &Node, metric: Metric) -> String {+ match metric {+ Metric::Bytes => human_bytes(node.bytes),+ Metric::Files => format!("{} files", human_count(node.files)),+ }+}++/// A dim label above a number, for the header strip.+pub fn stat(+ label: impl Into<SharedString>,+ value: impl Into<SharedString>,+ cx: &App,+) -> Div {+ let theme = cx.omarchy();+ div()+ .flex()+ .flex_col()+ .gap(space::XXS)+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary.opacity(0.75))+ .child(label.into()),+ )+ .child(+ div()+ .text_size(text::TITLE)+ .font_weight(FontWeight::SEMIBOLD)+ .text_color(theme.bright)+ .child(value.into()),+ )+}++/// A value with a status colour rather than the neutral one.+pub fn stat_colored(+ label: impl Into<SharedString>,+ value: impl Into<SharedString>,+ color: Hsla,+ cx: &App,+) -> Div {+ let theme = cx.omarchy();+ div()+ .flex()+ .flex_col()+ .gap(space::XXS)+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary.opacity(0.75))+ .child(label.into()),+ )+ .child(+ div()+ .text_size(text::TITLE)+ .font_weight(FontWeight::SEMIBOLD)+ .text_color(color)+ .child(value.into()),+ )+}++/// A square chip, used for counts and states.+pub fn chip(label: impl Into<SharedString>, color: Hsla, cx: &App) -> Div {+ let theme = cx.omarchy();+ div()+ .px(space::XS)+ .py(space::XXS)+ .border_1()+ .border_color(color.opacity(0.5))+ .bg(color.opacity(0.1))+ .text_color(color)+ .text_size(text::CAPTION)+ .font_family(theme.font.clone())+ .child(label.into())+}++/// A labelled meter: `label · bar · value`.+pub fn meter_row(+ label: impl Into<SharedString>,+ value: impl Into<SharedString>,+ fraction: f32,+ color: Hsla,+ cx: &App,+) -> Div {+ let theme = cx.omarchy();+ div()+ .flex()+ .flex_col()+ .gap(space::XS)+ .child(+ div()+ .flex()+ .flex_row()+ .justify_between()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(div().child(label.into()))+ .child(+ div()+ .text_color(theme.bright)+ .font_weight(FontWeight::MEDIUM)+ .child(value.into()),+ ),+ )+ .child(+ div()+ .w_full()+ .h(space::XS)+ .bg(theme.foreground.opacity(0.08))+ .child(+ div()+ .h_full()+ .w(relative(fraction.clamp(0.0, 1.0)))+ .bg(color),+ ),+ )+}++/// The volume meter: what is used, what is free, and what the marks will free.+///+/// The projection is drawn as a separate segment so "this much comes back" is+/// visible rather than only stated.+pub fn space_meter(space: SpaceInfo, reclaiming: u64, cx: &App) -> Div {+ let theme = cx.omarchy();+ let total = space.total.max(1);+ let projected = space.after_removing(reclaiming);+ let used_now = space.used() as f32 / total as f32;+ let gained = (projected.used() as f32 / total as f32).max(0.0);+ let used_now = used_now.clamp(0.0, 1.0);+ let gained = gained.clamp(0.0, used_now);++ let label = if reclaiming > 0 {+ format!(+ "{} free · {} after removing {}",+ human_bytes(space.available),+ human_bytes(projected.available),+ human_bytes(reclaiming)+ )+ } else {+ format!(+ "{} free of {}",+ human_bytes(space.available),+ human_bytes(space.total)+ )+ };++ div()+ .flex()+ .flex_col()+ .gap(space::XS)+ .child(+ div()+ .flex()+ .flex_row()+ .justify_between()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(div().child(label)),+ )+ .child(+ div()+ .relative()+ .w_full()+ .h(space::XS)+ .bg(theme.foreground.opacity(0.08))+ .child(+ // Used space, as a bar from the left.+ div()+ .absolute()+ .left_0()+ .top_0()+ .h_full()+ .w(relative(used_now))+ .bg(theme.foreground.opacity(0.22)),+ )+ .child(+ // What stays used after the removals: the bar shrinks to+ // here, so the gap is exactly what comes back.+ div()+ .absolute()+ .left_0()+ .top_0()+ .h_full()+ .w(relative(gained))+ .bg(theme.danger.opacity(0.55)),+ )+ .child(+ // The reclaimed slice sits at the right edge of what is+ // currently used.+ div()+ .absolute()+ .left(relative(gained))+ .top_0()+ .h_full()+ .w(relative(used_now - gained))+ .bg(theme.success.opacity(0.65)),+ ),+ )+}++/// A `key value` hint pair for the bottom bar.+pub fn hint(+ keys: impl Into<SharedString>,+ label: impl Into<SharedString>,+ cx: &App,+) -> Div {+ let theme = cx.omarchy();+ div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::XS)+ .child(gpui_omarchy::keycap(keys, cx))+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child(label.into()),+ )+}++/// A section heading inside a panel.+pub fn section(label: impl Into<SharedString>, cx: &App) -> Div {+ let theme = cx.omarchy();+ div()+ .text_size(text::CAPTION)+ .font_weight(FontWeight::SEMIBOLD)+ .text_color(theme.secondary.opacity(0.85))+ .child(label.into())+}++/// A definition row: label on the left, value on the right.+pub fn row(+ label: impl Into<SharedString>,+ value: impl Into<SharedString>,+ cx: &App,+) -> Div {+ let theme = cx.omarchy();+ div()+ .flex()+ .flex_row()+ .justify_between()+ .gap(space::SM)+ .text_size(text::CAPTION)+ .child(div().text_color(theme.secondary).child(label.into()))+ .child(div().min_w_0().text_color(theme.bright).child(value.into()))+}++/// A block-glyph share bar, which reads as a bar at any font size.+pub fn glyph_bar(+ part: u64,+ total: u64,+ width: usize,+ color: Hsla,+ cx: &App,+) -> Div {+ let theme = cx.omarchy();+ div()+ .text_size(text::CAPTION)+ .font_family(theme.font.clone())+ .text_color(color)+ .child(SharedString::from(share_bar(part, total, width)))+}++/// A percentage with one decimal below ten percent.+pub fn percent(part: u64, total: u64) -> String {+ let value = share(part, total);+ if value < 9.95 {+ format!("{value:.1}%")+ } else {+ format!("{value:.0}%")+ }+}++/// The status colour for an alert.+pub fn alert_color(status: Status, cx: &App) -> Hsla {+ let theme = cx.omarchy();+ match status {+ Status::Neutral => theme.secondary,+ Status::Success => theme.success,+ Status::Warning => theme.warning,+ Status::Error => theme.danger,+ }+}++/// A clickable breadcrumb segment.+pub fn crumb(+ id: impl Into<ElementId>,+ label: impl Into<SharedString>,+ active: bool,+ cx: &App,+) -> gpui_kit::Stateful<Div> {+ let theme = cx.omarchy();+ let color = if active {+ theme.bright+ } else {+ theme.secondary+ };+ div()+ .id(id)+ .px(space::XS)+ .py(space::XXS)+ .text_size(text::BODY)+ .text_color(color)+ .when(active, |this| this.font_weight(FontWeight::SEMIBOLD))+ .when(!active, |this| {+ this.hover(|style| style.bg(theme.hover_fill()))+ })+ .child(label.into())+}