diff --git a/crates/disktree-app/src/git.rs b/crates/disktree-app/src/git.rs new file mode 100644 index 0000000..5c52eb6 --- /dev/null +++ b/crates/disktree-app/src/git.rs @@ -0,0 +1,137 @@ +//! What git knows about a checkout, for the selection panel. +//! +//! Before deleting an agent worktree the question is "would anything be +//! lost": uncommitted changes, stashes, commits nobody pushed. That is three +//! cheap git calls, run off the UI thread when a checkout is selected and +//! remembered per path. + +use std::path::Path; +use std::process::{Command, Stdio}; + +/// A checkout's state, as far as losing work is concerned. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct GitState { + /// Paths `git status --porcelain` lists: changed, staged or untracked. + pub changed: usize, + pub stashes: usize, + /// Commits ahead of the upstream; `None` when there is no upstream. + pub unpushed: Option, +} + +impl GitState { + /// Nothing would be lost by deleting it. + pub const fn is_clean(&self) -> bool { + self.changed == 0 + && self.stashes == 0 + && matches!(self.unpushed, Some(0)) + } + + /// One short line: `clean, no stash`, `3 changed, 1 stash, 2 unpushed`. + pub fn summary(&self) -> String { + let mut parts = Vec::new(); + parts.push(if self.changed == 0 { + "clean".to_string() + } else { + format!("{} changed", self.changed) + }); + parts.push(match self.stashes { + 0 => "no stash".to_string(), + 1 => "1 stash".to_string(), + count => format!("{count} stashes"), + }); + match self.unpushed { + Some(0) => {} + Some(count) => parts.push(format!("{count} unpushed")), + None => parts.push("no upstream".to_string()), + } + parts.join(", ") + } +} + +/// Whether `path` is the top of a checkout: it has a `.git` directory, or the +/// `.git` file a worktree gets. +pub fn is_checkout(path: &Path) -> bool { + std::fs::symlink_metadata(path.join(".git")).is_ok() +} + +/// Ask git. `None` when `path` is not a checkout or git is not installed. +pub fn state(path: &Path) -> Option { + if !is_checkout(path) { + return None; + } + let status = run(path, &["status", "--porcelain=v1", "-z"])?; + let changed = status.split('\0').filter(|line| !line.is_empty()).count(); + let stashes = + run(path, &["stash", "list"]).map_or(0, |list| list.lines().count()); + let unpushed = run(path, &["rev-list", "--count", "@{upstream}..HEAD"]) + .and_then(|count| count.trim().parse().ok()); + Some(GitState { + changed, + stashes, + unpushed, + }) +} + +fn run(path: &Path, args: &[&str]) -> Option { + let output = Command::new("git") + .arg("-C") + .arg(path) + .args(args) + // Never prompt, never page, never take a lock for the index refresh. + .env("GIT_TERMINAL_PROMPT", "0") + .env("GIT_OPTIONAL_LOCKS", "0") + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .output() + .ok()?; + output + .status + .success() + .then(|| String::from_utf8_lossy(&output.stdout).into_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn summaries_say_what_would_be_lost() { + let clean = GitState { + unpushed: Some(0), + ..GitState::default() + }; + assert!(clean.is_clean()); + assert_eq!(clean.summary(), "clean, no stash"); + let busy = GitState { + changed: 3, + stashes: 1, + unpushed: Some(2), + }; + assert!(!busy.is_clean()); + assert_eq!(busy.summary(), "3 changed, 1 stash, 2 unpushed"); + let local = GitState::default(); + assert_eq!(local.summary(), "clean, no stash, no upstream"); + assert!(!local.is_clean(), "unpushed history could be lost"); + } + + #[test] + fn reads_a_real_checkout() { + let dir = tempfile::tempdir().expect("tempdir"); + assert_eq!(state(dir.path()), None, "not a checkout"); + let git = |args: &[&str]| { + Command::new("git") + .arg("-C") + .arg(dir.path()) + .args(args) + .output() + .is_ok_and(|output| output.status.success()) + }; + if !git(&["init", "-q"]) { + return; // no git on this machine + } + std::fs::write(dir.path().join("a.txt"), "hi").expect("write"); + let state = state(dir.path()).expect("a checkout"); + assert_eq!(state.changed, 1, "one untracked file"); + assert_eq!(state.stashes, 0); + } +} diff --git a/crates/disktree-app/src/main.rs b/crates/disktree-app/src/main.rs index 8dbbaf5..e26653a 100644 --- a/crates/disktree-app/src/main.rs +++ b/crates/disktree-app/src/main.rs @@ -5,6 +5,7 @@ //! live free-space meter. Marking is non-destructive until the review screen //! is confirmed. +mod git; mod marks; mod palette; mod state; @@ -45,7 +46,10 @@ 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, --disk scan the whole disk the home directory is on + -X, --cross-filesystems + also measure other disks, network shares and pseudo + filesystems mounted below PATH (off by default) -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 @@ -120,6 +124,7 @@ fn parse_args() -> Result { let mut root: Option = None; let mut options = ScanOptions::default(); let mut depth = 3_u32; + let mut disk = false; let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { @@ -131,7 +136,11 @@ fn parse_args() -> Result { "-a" | "--apparent-size" => options.apparent_size = true, "-l" | "--follow-links" => options.follow_links = true, "-H" | "--no-hidden" => options.include_hidden = false, + // Staying on one volume is the default; the flag is kept so + // old invocations still work. "-x" | "--one-filesystem" => options.one_filesystem = true, + "-X" | "--cross-filesystems" => options.one_filesystem = false, + "-D" | "--disk" => disk = true, "-d" | "--depth" => { let value = args.next().context("--depth needs a number")?; depth = value.parse().context("--depth needs a number")?; @@ -160,7 +169,16 @@ fn parse_args() -> Result { } } + anyhow::ensure!( + !(disk && root.is_some()), + "--disk and a PATH cannot be combined" + ); + let home = std::env::var_os("HOME").map(PathBuf::from); let root = match root { + _ if disk => home + .as_deref() + .and_then(disktree_core::space::volume_root_for) + .unwrap_or_else(|| PathBuf::from("/")), Some(root) => root, None => std::env::var_os("HOME") .map(PathBuf::from) diff --git a/crates/disktree-app/src/palette.rs b/crates/disktree-app/src/palette.rs index 93f91a5..1f5ad7e 100644 --- a/crates/disktree-app/src/palette.rs +++ b/crates/disktree-app/src/palette.rs @@ -1,82 +1,176 @@ -//! Colours derived from the Omarchy theme. +//! Colour that means something. //! -//! 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. +//! A tile's hue says what kind of data it is ([`Category`]); every hue sits +//! at the same muted saturation and lightness, so no block stands out by +//! accident, and deeper tiles lift slightly so nesting reads without borders. +//! Reclaimable space is a hatch, not a colour, so "what is it" and "can it go" +//! are read independently. +//! +//! One strong colour is kept apart: the highlight, the theme's warning amber. +//! It marks the selection, the main action, reclaimable totals and the free +//! space after a removal, and nothing else, so the eye goes straight to it. +//! +//! Lightness, saturation and the surface every fill is pulled toward come +//! from the active Omarchy theme, so the mosaic sits inside it, light or dark. -use gpui_kit::Hsla; +use disktree_core::classify::Category; use gpui_kit::base::ThemeAppearance; +use gpui_kit::{Hsla, Rgba}; 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 +/// The hue a category is drawn in, and how much colour it carries. The +/// neutral kinds (documents, unknown) carry almost none. +const fn hue(category: Category) -> (f32, f32) { + match category { + Category::Code => (0.605, 1.0), + Category::AgentScratch => (0.065, 1.0), + Category::Toolchain => (0.415, 1.0), + Category::Synced => (0.535, 1.0), + Category::Git => (0.955, 1.0), + Category::Media => (0.745, 1.0), + Category::Cache => (0.125, 0.95), + Category::Documents => (0.6, 0.18), + Category::Other => (0.6, 0.08), } } -/// Linear interpolation between two colours in HSLA. +const fn dark(theme: &Theme) -> bool { + matches!(theme.appearance, ThemeAppearance::Dark) +} + +/// The fill for a tile of `category`, `depth` levels into the view. +pub fn category_fill(theme: &Theme, category: Category, depth: u32) -> Hsla { + let (h, chroma) = hue(category); + let step = depth.min(4) as f32; + let (s, l) = if dark(theme) { + (0.26 * chroma, step.mul_add(0.028, 0.215)) + } else { + (0.30 * chroma, step.mul_add(-0.03, 0.84)) + }; + // Pulled a little toward the theme surface, so each theme tints it. + mix(Hsla { h, s, l, a: 1.0 }, theme.inset, 0.12) +} + +/// The saturated version of a category's hue: the strip over a top-level +/// directory and the legend swatch. +pub fn category_accent(theme: &Theme, category: Category) -> Hsla { + let (h, chroma) = hue(category); + let (s, l) = if dark(theme) { + (0.42 * chroma, 0.52) + } else { + (0.45 * chroma, 0.46) + }; + Hsla { h, s, l, a: 1.0 } +} + +/// The age ramp, newest first: this week, this month, this half-year, this +/// year, older. +pub const AGE_BUCKETS: [(i64, &str); 5] = [ + (7, "This week"), + (30, "This month"), + (182, "Six months"), + (365, "This year"), + (i64::MAX, "Older"), +]; + +/// Which [`AGE_BUCKETS`] entry an age in days falls in. +pub fn age_bucket(days: i64) -> usize { + AGE_BUCKETS + .iter() + .position(|(limit, _)| days <= *limit) + .unwrap_or(AGE_BUCKETS.len() - 1) +} + +/// The fill for age mode: recent writes carry the theme accent, and colour +/// drains out of a tile as it goes untouched. +pub fn age_fill(theme: &Theme, bucket: usize, depth: u32) -> Hsla { + let fade = bucket.min(AGE_BUCKETS.len() - 1) as f32 / 4.0; + let step = depth.min(4) as f32; + let (s, l) = if dark(theme) { + ( + (1.0 - fade).mul_add(0.34, 0.03), + step.mul_add(0.028, 0.29 - fade * 0.09), + ) + } else { + ( + (1.0 - fade).mul_add(0.36, 0.04), + step.mul_add(-0.03, 0.74 + fade * 0.1), + ) + }; + mix( + Hsla { + h: theme.accent.h, + s, + l, + a: 1.0, + }, + theme.inset, + 0.1, + ) +} + +/// The age swatch for the legend. +pub fn age_accent(theme: &Theme, bucket: usize) -> Hsla { + let fade = bucket.min(AGE_BUCKETS.len() - 1) as f32 / 4.0; + let l = if dark(theme) { + 0.55 - fade * 0.25 + } else { + 0.45 + fade * 0.25 + }; + Hsla { + h: theme.accent.h, + s: (1.0 - fade).mul_add(0.45, 0.04), + l, + a: 1.0, + } +} + +/// The one strong colour: selection, the main action, what can be had back. +pub const fn highlight(theme: &Theme) -> Hsla { + theme.warning +} + +/// Text on a filled highlight. +pub const fn on_highlight(theme: &Theme) -> Hsla { + if dark(theme) { + theme.background + } else { + theme.bright + } +} + +/// The diagonal hatch over reclaimable space: quiet enough to leave the hue +/// readable, visible on every fill. +pub fn hatch(theme: &Theme) -> Hsla { + if dark(theme) { + theme.bright.opacity(0.16) + } else { + theme.foreground.opacity(0.18) + } +} + +/// Linear interpolation between two colours, in RGB: interpolating hue +/// would drag a colour around the wheel on its way to a grey. 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), - } + let (a, b) = (from.to_rgb(), to.to_rgb()); + Hsla::from(Rgba { + r: lerp(a.r, b.r), + g: lerp(a.g, b.g), + b: lerp(a.b, b.b), + a: lerp(a.a, b.a), + }) } -/// The colour of a tile's label on top of its fill. +/// A tile's name 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) } + let base = if dark(theme) { + theme.bright + } else { + theme.foreground + }; + if depth == 0 { base } else { base.opacity(0.88) } } #[cfg(test)] @@ -84,52 +178,84 @@ 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}"); + match appearance { + ThemeAppearance::Dark => Theme::tokyo_night(), + ThemeAppearance::Light => Theme::flexoki_light(), } } + #[test] + fn every_legend_category_has_its_own_hue() { + let theme = theme(ThemeAppearance::Dark); + let fills: Vec = Category::LEGEND + .iter() + .map(|&category| category_accent(&theme, category)) + .collect(); + for (index, left) in fills.iter().enumerate() { + for right in &fills[index + 1..] { + let apart = (left.h - right.h).abs() > 0.03 + || (left.s - right.s).abs() > 0.1; + assert!(apart, "{left:?} and {right:?} read as one colour"); + } + } + } + + #[test] + fn colourful_categories_share_one_level() { + let theme = theme(ThemeAppearance::Dark); + let code = category_fill(&theme, Category::Code, 0); + let git = category_fill(&theme, Category::Git, 0); + assert!((code.l - git.l).abs() < 0.02); + assert!((code.s - git.s).abs() < 0.03); + } + + #[test] + fn deeper_tiles_lift_away_from_the_background() { + for appearance in [ThemeAppearance::Dark, ThemeAppearance::Light] { + let theme = theme(appearance); + let top = category_fill(&theme, Category::Code, 0); + let deep = category_fill(&theme, Category::Code, 3); + // Away from the background: lighter on dark, darker on light. + let distance = |fill: Hsla| (fill.l - theme.background.l).abs(); + assert!(distance(deep) > distance(top) + 0.05, "{appearance:?}"); + } + } + + #[test] + fn the_highlight_is_not_a_category_colour() { + let theme = theme(ThemeAppearance::Dark); + let highlight = highlight(&theme); + for category in Category::LEGEND { + let fill = category_fill(&theme, category, 0); + assert!(highlight.s - fill.s > 0.2, "{category:?} competes"); + } + } + + #[test] + fn age_buckets_cover_every_age_in_order() { + assert_eq!(age_bucket(0), 0); + assert_eq!(age_bucket(8), 1); + assert_eq!(age_bucket(100), 2); + assert_eq!(age_bucket(300), 3); + assert_eq!(age_bucket(5000), 4); + let theme = theme(ThemeAppearance::Dark); + assert!(age_fill(&theme, 0, 0).s > age_fill(&theme, 4, 0).s); + } + + #[test] + fn mixing_toward_a_grey_keeps_the_hue() { + let theme = theme(ThemeAppearance::Dark); + let orange = category_accent(&theme, Category::AgentScratch); + let mixed = mix(orange, theme.inset, 0.3); + assert!((mixed.h - orange.h).abs() < 0.02, "{mixed:?}"); + } + #[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); + assert!((clamped_low - theme.background.l).abs() < 1e-3); + assert!((clamped_high - theme.accent.l).abs() < 1e-3); } } diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index 7bc9332..1844944 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -9,13 +9,16 @@ use std::path::{Path, PathBuf}; use std::rc::Rc; use std::time::{Duration, Instant}; +use disktree_core::insights::{Candidate, worth_a_look}; use disktree_core::removal::{ Plan, RemovalEvent, RemovalHandle, RemovalMode, Target, TrashBackend, detect_trash_backend, plan, }; use disktree_core::scan::{ScanHandle, ScanOptions, ScanSnapshot}; -use disktree_core::space::{SpaceInfo, space_info}; -use disktree_core::tree::{Node, path_of}; +use disktree_core::space::{ + SpaceInfo, device_for, space_info, volume_root_for, +}; +use disktree_core::tree::{Metric, Node, path_of}; use disktree_core::treemap::{ LayoutOptions, Rect, Tile, TileKind, hit, layout, }; @@ -25,11 +28,51 @@ use gpui_kit::{ Window, px, size, }; use gpui_omarchy::Status; -use rustc_hash::FxHashSet; +use rustc_hash::{FxHashMap, FxHashSet}; + +use crate::git::GitState; use crate::marks::{Marks, display_path, is_hidden}; use crate::treemap_view::{Mosaic, TileDeco}; +/// What a tile's colour says. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ColorMode { + /// The kind of data it is. + #[default] + Kind, + /// How long since anything in it was written. + Age, +} + +/// What is scanned, as the trail's switch names it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Scope { + /// The home directory. + Home, + /// The whole disk the home directory lives on. + Disk, +} + +/// The side panel's width in rem: default and limits. In rem, so interface +/// zoom scales it with everything it holds. +pub const PANEL_REMS: f32 = 23.0; +pub const PANEL_MIN_REMS: f32 = 17.0; +pub const PANEL_MAX_REMS: f32 = 44.0; + +/// The panel width, in rem, for its left edge at `pointer_x` in a window +/// `viewport` pixels wide: between its limits, and never so wide that the +/// mosaic is squeezed below the panel's own minimum. +pub fn panel_width(pointer_x: f32, viewport: f32, rem: f32) -> f32 { + let width = (viewport - pointer_x) / rem; + let max = + (viewport / rem - PANEL_MIN_REMS).clamp(PANEL_MIN_REMS, PANEL_MAX_REMS); + width.clamp(PANEL_MIN_REMS, max) +} + +/// How many "worth a look" findings the panel lists. +const INSIGHT_LIMIT: usize = 6; + /// Which screen the app is showing. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Screen { @@ -296,6 +339,25 @@ pub struct Disktree { pub show_help: bool, pub show_selection: bool, pub focus: FocusHandle, + + pub color_mode: ColorMode, + /// The largest things worth clearing, recomputed when a scan lands. + pub insights: Vec, + /// What git knows about each checkout that has been selected; `None` + /// once asked and found not to be one. + pub git: FxHashMap>, + git_pending: FxHashSet, + /// The device the scanned volume is mounted from. + pub device: Option, + /// The top of the disk the home directory lives on: what "Whole disk" + /// scans. + pub disk_root: Option, + /// The side panel's width, in rem; dragged from its left edge. + pub panel_rems: f32, + pub scan_started: Option, + pub scan_elapsed: Option, + /// Unix seconds when the tree landed: the "now" ages are measured from. + pub scanned_at: i64, } impl Disktree { @@ -357,7 +419,23 @@ impl Disktree { show_help: false, show_selection: true, focus: cx.focus_handle(), + color_mode: ColorMode::Kind, + insights: Vec::new(), + git: FxHashMap::default(), + git_pending: FxHashSet::default(), + device: None, + disk_root: None, + panel_rems: PANEL_REMS, + scan_started: None, + scan_elapsed: None, + scanned_at: now_seconds(), }; + tree.device = device_for(&tree.root_path); + tree.disk_root = tree + .home + .as_deref() + .or(Some(tree.root_path.as_path())) + .and_then(volume_root_for); tree.start_scan(cx); Self::start_space_ticker(cx); tree @@ -380,10 +458,77 @@ impl Disktree { app.marks.refresh(&app.root_path, &tree, app.options.metric); app.tree = Some(Rc::new(tree)); app.cache = None; + app.refresh_insights(); app.select_largest(cx); app } + /// Which scope the current root is, if it is one of the two. + pub fn scope(&self) -> Option { + if self.home.as_deref() == Some(self.root_path.as_path()) { + Some(Scope::Home) + } else if self.disk_root.as_deref() == Some(self.root_path.as_path()) { + Some(Scope::Disk) + } else { + None + } + } + + /// Scan a different root: the home directory, the whole disk, or any + /// directory. Marks are kept; a mark outside the new root is shown as + /// kept back, never removed. + pub fn set_root(&mut self, root: PathBuf, cx: &mut Context<'_, Self>) { + if root == self.root_path && self.tree.is_some() { + return; + } + self.space = space_info(&root).ok(); + self.device = device_for(&root); + self.root_path = root; + self.screen = Screen::Explore; + self.start_scan(cx); + } + + /// Switch to a scope. + pub fn set_scope(&mut self, scope: Scope, cx: &mut Context<'_, Self>) { + let root = match scope { + Scope::Home => self.home.clone(), + Scope::Disk => self.disk_root.clone(), + }; + if let Some(root) = root { + self.set_root(root, cx); + } + } + + /// Recompute "worth a look" from the tree on screen. + fn refresh_insights(&mut self) { + self.scanned_at = now_seconds(); + self.insights = self.tree.as_deref().map_or_else(Vec::new, |tree| { + worth_a_look(tree, self.scanned_at, INSIGHT_LIMIT) + }); + } + + /// Ask git about `path` once, off the UI thread, if it is a checkout. + pub fn ensure_git(&mut self, path: &Path, cx: &Context<'_, Self>) { + if self.git.contains_key(path) || self.git_pending.contains(path) { + return; + } + let path = path.to_path_buf(); + self.git_pending.insert(path.clone()); + let task = cx.background_executor().spawn({ + let path = path.clone(); + async move { crate::git::state(&path) } + }); + cx.spawn(async move |this, cx| { + let state = task.await; + let _ = this.update(cx, |this, cx| { + this.git_pending.remove(&path); + this.git.insert(path, state); + cx.notify(); + }); + }) + .detach(); + } + /// 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" @@ -415,6 +560,10 @@ impl Disktree { self.hovered = None; self.view = View::default(); self.cache = None; + self.insights.clear(); + self.git.clear(); + self.scan_started = Some(Instant::now()); + self.scan_elapsed = None; self.scan = Some(ScanHandle::spawn( self.root_path.clone(), self.options.clone(), @@ -465,6 +614,9 @@ impl Disktree { self.marks.refresh(&self.root_path, &node, metric); self.tree = Some(Rc::new(node)); self.cache = None; + self.refresh_insights(); + self.scan_elapsed = + self.scan_started.map(|started| started.elapsed()); self.keep_selection_valid(); self.select_largest(cx); } @@ -719,6 +871,16 @@ impl Disktree { cx.notify(); } + /// Show `crumbs` in its directory, selected: what a "worth a look" row + /// or a found name does. + pub fn reveal(&mut self, crumbs: Vec, cx: &mut Context<'_, Self>) { + let parent = crumbs[..crumbs.len().saturating_sub(1)].to_vec(); + self.go_to(parent, cx); + self.selected = Some(crumbs); + self.pointer_active = false; + cx.notify(); + } + /// Select the tile at `crumbs` without changing the root. pub fn select( &mut self, @@ -976,24 +1138,34 @@ impl Disktree { }; }; - // 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); + // Hue comes from the node's kind; lightness from its depth in this + // view, so the first level always reads as the first level. + let age = self.color_mode == ColorMode::Age; + let now = self.scanned_at; 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 node = match &tile.kind { + TileKind::Node { crumbs } => self.node_at(crumbs), + TileKind::Others { .. } => None, + }; + let category = node.map_or_else(Default::default, |n| n.category); + let age_bucket = (age && node.is_some_and(|n| n.modified > 0)) + .then(|| { + let days = + (now - node.map_or(now, |n| n.modified)) / 86_400; + crate::palette::age_bucket(days) + }); 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, + category, + age_bucket, + reclaimable: node.is_some_and(|n| n.reclaim.is_some()), + unreadable: node.is_some_and(|n| n.read_error), marked: is_marked, covered: is_covered, hovered: hovered.as_deref() == Some(crumbs), @@ -1023,7 +1195,7 @@ impl Disktree { header: tile .header .map(|header| self.animated_rect(header)), - color_depth: base_depth.saturating_add(tile.depth), + depth: tile.depth, marked: is_marked || is_covered, size_text: crate::widgets::short_value(node, metric), }); @@ -1032,7 +1204,7 @@ impl Disktree { text: format!("+{count} more"), rect: self.animated_rect(tile.rect), header: None, - color_depth: base_depth.saturating_add(tile.depth), + depth: tile.depth, marked: false, size_text: String::new(), }), @@ -1077,21 +1249,12 @@ impl Disktree { 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; + self.layout_options.header_inner = HEADER_INNER_REMS * self.rem; let area = self.treemap_size.get(); let key = LayoutKey { crumbs: self.crumbs.clone(), @@ -1217,10 +1380,36 @@ impl Disktree { metric, ); } + // Children are ordered by the metric, so every crumb moved. + self.refresh_insights(); self.cache = None; cx.notify(); } + /// The Size | Files | Age choice: what areas measure, and what colour + /// says. Age keeps areas by size, since age has no area of its own. + pub fn set_mode(&mut self, index: usize, cx: &mut Context<'_, Self>) { + let (metric, color) = match index { + 1 => (Metric::Files, ColorMode::Kind), + 2 => (Metric::Bytes, ColorMode::Age), + _ => (Metric::Bytes, ColorMode::Kind), + }; + self.color_mode = color; + if self.options.metric != metric { + self.toggle_metric(cx); + } + cx.notify(); + } + + /// The Size | Files | Age choice currently on. + pub const fn mode_index(&self) -> usize { + match (self.color_mode, self.options.metric) { + (ColorMode::Age, _) => 2, + (ColorMode::Kind, Metric::Files) => 1, + (ColorMode::Kind, Metric::Bytes) => 0, + } + } + // ── removal ───────────────────────────────────────────────────────── /// The review screen's commit: move to the trash at once, or ask first for @@ -1404,11 +1593,8 @@ impl Disktree { cx.notify(); return; }; - let parent = crumbs[..crumbs.len().saturating_sub(1)].to_vec(); - self.go_to(parent, cx); - self.selected = Some(crumbs); + self.reveal(crumbs, cx); self.notice = None; - cx.notify(); } // ── input ─────────────────────────────────────────────────────────── @@ -1595,8 +1781,18 @@ impl Disktree { ); } "0" => self.reset_view(cx), - "t" if !control => self.toggle_metric(cx), + "t" if !control => { + self.set_mode((self.mode_index() + 1) % 3, cx); + } "r" if !control => self.start_scan(cx), + "g" if !control => { + let next = if self.scope() == Some(Scope::Disk) { + Scope::Home + } else { + Scope::Disk + }; + self.set_scope(next, cx); + } "i" if !control => { self.options.include_hidden = !self.options.include_hidden; self.start_scan(cx); @@ -1661,6 +1857,21 @@ impl Disktree { event.position.x - origin.x, event.position.y - origin.y, ); + // Moves are delivered here even when the pointer is elsewhere in the + // window. Outside the mosaic there is nothing to hover, and a stale + // tooltip would cover whatever the pointer went to — the panel's + // resize handle, for one. + let area = self.treemap_size.get(); + let inside = local.x >= px(0.) + && local.y >= px(0.) + && local.x < area.width + && local.y < area.height; + if !inside { + if self.pointer.is_some() || self.hovered.is_some() { + self.on_mouse_leave(cx); + } + return; + } self.pointer = Some(local); self.pointer_active = true; let previous = self.hovered.clone(); @@ -1844,9 +2055,8 @@ pub struct Label { /// 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, - /// Depth from the scanned root, used for the colour so it does not shift - /// when the view descends. - pub color_depth: u32, + /// Nesting depth in this view: the first level is set in bold. + pub depth: u32, pub marked: bool, pub size_text: String, } @@ -1854,8 +2064,20 @@ pub struct Label { /// 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; +/// Height of a top-level directory's name band, in rem. +const HEADER_REMS: f32 = 1.375; + +/// Height of the slim label row a deeper open directory keeps, in rem. +const HEADER_INNER_REMS: f32 = 1.0; + +/// Now, in Unix seconds. +pub fn now_seconds() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |since| { + i64::try_from(since.as_secs()).unwrap_or(i64::MAX) + }) +} /// Smallest tile, in rem, that gets a label: below this a name cannot be read. const LABEL_MIN_W_REMS: f32 = 3.375; diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rs index f923027..bcaf16a 100644 --- a/crates/disktree-app/src/tests.rs +++ b/crates/disktree-app/src/tests.rs @@ -814,3 +814,100 @@ fn after_descending_every_tile_is_inside_the_directory_drawn( }); assert_eq!(hatched, 1, "exactly the marked tile is hatched"); } + +/// Drive the scan the view started until its tree lands. +fn finish_scan(view: &Entity, cx: &mut Window) { + let epoch = read(view, cx, |app| app.scan_epoch); + for _ in 0..600 { + std::thread::sleep(std::time::Duration::from_millis(5)); + let ready = update(view, cx, |app, cx| { + app.poll_scan_once(epoch, cx); + app.tree().is_some() + }); + if ready { + return; + } + } + panic!("the scan never landed"); +} + +#[gpui_kit::test] +fn dragging_the_panel_edge_resizes_it_within_its_limits( + cx: &mut TestAppContext, +) { + use crate::state::{PANEL_MAX_REMS, PANEL_MIN_REMS, panel_width}; + use gpui_kit::{Modifiers, MouseButton}; + + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + draw(cx); + let handle = cx.debug_bounds("panel-handle").expect("the panel is shown"); + let start = handle.center(); + let before = read(&view, cx, |app| app.panel_rems); + + // A drag starts on the first move and reports moves after it, as a real + // pointer does in many small steps. + let drag = |cx: &mut Window, from: Point, to: Point| { + cx.simulate_mouse_down(from, MouseButton::Left, Modifiers::none()); + for step in 1..=4 { + let t = step as f32 / 4.0; + let at = Point::new(from.x + (to.x - from.x) * t, to.y); + cx.simulate_mouse_move( + at, + Some(MouseButton::Left), + Modifiers::none(), + ); + } + cx.simulate_mouse_up(to, MouseButton::Left, Modifiers::none()); + draw(cx); + }; + + // Wider: drag the edge 160 px to the left. + let wider = Point::new(start.x - px(160.), start.y); + drag(cx, start, wider); + let after = read(&view, cx, |app| app.panel_rems); + assert!( + (after - before - 10.0).abs() < 0.5, + "160 px is 10 rem: {before} -> {after}" + ); + + // The limits, for any edge position: a minimum, a maximum, and never + // so wide that the mosaic gets less room than the panel's own minimum. + assert!((panel_width(1390., 1400., 16.) - PANEL_MIN_REMS).abs() < 1e-3); + assert!((panel_width(0., 3000., 16.) - PANEL_MAX_REMS).abs() < 1e-3); + let squeezed = panel_width(0., 800., 16.); + assert!((squeezed - (800. / 16. - PANEL_MIN_REMS)).abs() < 1e-3); + assert!((panel_width(0., 300., 16.) - PANEL_MIN_REMS).abs() < 1e-3); +} + +#[gpui_kit::test] +fn g_switches_between_the_home_directory_and_the_whole_disk( + cx: &mut TestAppContext, +) { + use crate::state::Scope; + + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + // Stand-ins: the fixture is "home", a directory in it is "the disk". + let disk = temp.path().join("junk"); + update(&view, cx, |app, _| { + app.home = Some(temp.path().to_path_buf()); + app.disk_root = Some(disk.clone()); + }); + assert_eq!(read(&view, cx, Disktree::scope), Some(Scope::Home)); + + press(cx, "g"); + assert_eq!(read(&view, cx, |app| app.root_path.clone()), disk); + assert!(read(&view, cx, |app| app.scan.is_some()), "a new scan runs"); + finish_scan(&view, cx); + assert_eq!(read(&view, cx, Disktree::scope), Some(Scope::Disk)); + let top = read(&view, cx, |app| app.tree().map(|tree| tree.bytes)); + assert!(top.is_some_and(|bytes| bytes > 0)); + + press(cx, "g"); + finish_scan(&view, cx); + assert_eq!(read(&view, cx, Disktree::scope), Some(Scope::Home)); +} diff --git a/crates/disktree-app/src/treemap_view.rs b/crates/disktree-app/src/treemap_view.rs index 01a5704..093ee70 100644 --- a/crates/disktree-app/src/treemap_view.rs +++ b/crates/disktree-app/src/treemap_view.rs @@ -13,7 +13,7 @@ use std::rc::Rc; use disktree_core::treemap::Rect; use gpui_kit::{ - App, Bounds, ContentMask, Context, Corners, Edges, Font, Hsla, + App, Bounds, ContentMask, Context, Corners, Edges, Font, FontWeight, Hsla, InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement as _, Pixels, Point, ScrollWheelEvent, SharedString, Size, StatefulInteractiveElement as _, Styled, TextAlign, @@ -21,6 +21,8 @@ use gpui_kit::{ }; use gpui_omarchy::{ActiveTheme, Theme}; +use disktree_core::classify::Category; + use crate::palette; use crate::state::{Disktree, Label, View}; @@ -30,13 +32,16 @@ use crate::state::{Disktree, Label, View}; 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, + /// Nesting depth in this view; `0` is the first level. 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, + /// What kind of data it is: the hue. + pub category: Category, + /// In age mode, which [`palette::AGE_BUCKETS`] entry it falls in. + pub age_bucket: Option, + /// Its space can be had back: hatched. + pub reclaimable: bool, + /// Part of it could not be read: flagged in its corner. + pub unreadable: bool, pub marked: bool, /// Inside another marked directory, so it goes with its parent. pub covered: bool, @@ -138,71 +143,99 @@ pub fn mosaic( /// Theme colours resolved once per frame. struct Colors { - label: Vec, + label: [Hsla; 2], 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, - fill_hidden: Vec, - fill_marked: Vec, + warning: Hsla, + hatch: Hsla, + /// Fills per category, then per depth. + fill: Vec<[Hsla; DEPTHS]>, + /// The strip over a top-level directory, per category. + strip: Vec, + /// Fills per age bucket, then per depth. + age: Vec<[Hsla; DEPTHS]>, + marked_fill: Hsla, +} + +/// Depth steps a fill distinguishes; deeper clamps. +const DEPTHS: usize = 5; + +/// Every category, in the order [`category_index`] numbers them. +const CATEGORIES: [Category; 9] = [ + Category::Code, + Category::AgentScratch, + Category::Toolchain, + Category::Synced, + Category::Git, + Category::Media, + Category::Documents, + Category::Cache, + Category::Other, +]; + +fn category_index(category: Category) -> usize { + CATEGORIES + .iter() + .position(|&known| known == category) + .unwrap_or(CATEGORIES.len() - 1) } 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; + let ladder = |fill: &dyn Fn(u32) -> Hsla| { + std::array::from_fn(|depth| fill(depth as u32)) + }; 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, + label: [ + palette::label_color(theme, 0), + palette::label_color(theme, 1), + ], + label_dim: palette::label_color(theme, 1).opacity(0.5), + hover_border: theme.bright.opacity(0.55), + selected_border: palette::highlight(theme), 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)) + marked_label: theme.danger, + covered_border: theme.danger.opacity(0.4), + warning: theme.warning, + hatch: palette::hatch(theme), + fill: CATEGORIES + .iter() + .map(|&category| { + ladder(&|depth| { + palette::category_fill(theme, category, depth) + }) + }) .collect(), - fill_hidden: depth_range - .clone() - .map(|d| palette::tile_fill(theme, d, true, false)) + strip: CATEGORIES + .iter() + .map(|&category| palette::category_accent(theme, category)) .collect(), - fill_marked: depth_range - .map(|d| palette::tile_fill(theme, d, false, true)) + age: (0..palette::AGE_BUCKETS.len()) + .map(|bucket| { + ladder(&|depth| palette::age_fill(theme, bucket, depth)) + }) .collect(), + marked_fill: palette::mix(theme.inset, theme.danger, 0.16), } } 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] + return self.marked_fill; + } + let depth = (tile.depth as usize).min(DEPTHS - 1); + match tile.age_bucket { + Some(bucket) => self.age[bucket.min(self.age.len() - 1)][depth], + None => self.fill[category_index(tile.category)][depth], } } - fn label(&self, depth: u32) -> Hsla { - self.label[(depth as usize).min(self.label.len() - 1)] + const fn label(&self, depth: u32) -> Hsla { + self.label[if depth == 0 { 0 } else { 1 }] } } @@ -213,74 +246,127 @@ fn paint_tiles( colors: &Colors, window: &mut Window, ) { + let none = Edges::all(px(0.)); + let solid = gpui_kit::BorderStyle::Solid; + let scale = window.scale_factor(); + // Outlines are drawn after every fill: a directory's children paint over + // its body, and would otherwise cover its selection ring, leaving only + // slivers of it showing in the gaps between them. + let mut outlines: Vec<(u8, Bounds, f32, Hsla)> = Vec::new(); 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; - } + let quad_bounds = snap(to_window(&rect, bounds), scale); + // No border by default: the gaps between tiles, wider between the + // top-level directories, are what separate them. window.paint_quad(quad( quad_bounds, Corners::default(), colors.fill(tile), - Edges::all(px(width)), - border, - gpui_kit::BorderStyle::Solid, + none, + colors.hover_border, + 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 { + // Reclaimable space is hatched, over any hue: the hatch answers + // "can it go", the colour "what is it". Everything inside a + // reclaimable directory is reclaimable too, so only the outermost + // one needs painting; its children repaint their own fill and hatch. + if tile.reclaimable && !tile.marked { window.paint_quad(quad( - inset(quad_bounds, px(2.)), + quad_bounds, Corners::default(), - pattern_slash(colors.marked_hatch, 2.0, 9.0), - Edges::all(px(0.)), - colors.marked_border, - gpui_kit::BorderStyle::Solid, + pattern_slash(colors.hatch, 1.0, 6.0), + none, + colors.hatch, + solid, )); } + + // A top-level directory carries a thin strip of its colour, so the + // first level of structure reads before any detail. + if tile.depth == 0 && tile.age_bucket.is_none() { + let strip = Bounds::new( + quad_bounds.origin, + Size::new( + quad_bounds.size.width, + px(2.0_f32.min(quad_bounds.size.height.as_f32())), + ), + ); + window.paint_quad(quad( + strip, + Corners::default(), + colors.strip[category_index(tile.category)], + none, + colors.hover_border, + solid, + )); + } + + if tile.unreadable && rect.w > 12.0 && rect.h > 12.0 { + // A small warning corner: part of this was never measured. + let mark = Bounds::new( + Point::new( + quad_bounds.origin.x + quad_bounds.size.width - px(6.), + quad_bounds.origin.y + px(2.), + ), + Size::new(px(4.), px(4.)), + ); + window.paint_quad(quad( + mark, + Corners::default(), + colors.warning, + none, + colors.warning, + solid, + )); + } + + // Ranked so the most important ring is painted last, on top. + let outline = if tile.selected { + Some((3, 2.0, colors.selected_border)) + } else if tile.hovered { + Some((2, 1.0, colors.hover_border)) + } else if tile.marked { + Some((1, 2.0, colors.marked_border)) + } else if tile.covered { + Some((0, 1.0, colors.covered_border)) + } else { + None + }; + if let Some((rank, width, color)) = outline { + outlines.push((rank, quad_bounds, width, color)); + } } + outlines.sort_by_key(|(rank, ..)| *rank); + for (_, ring, width, color) in outlines { + window.paint_quad(quad( + ring, + Corners::default(), + gpui_kit::transparent_black(), + Edges::all(px(width)), + color, + solid, + )); + } +} + +/// Round a rectangle's edges to device pixels. Tiles land on fractional +/// positions, and a 2 px strip or ring there smears across a pixel row and +/// leaves a seam; rounding each edge, not the size, keeps neighbours flush. +fn snap(bounds: Bounds, scale: f32) -> Bounds { + let round = |value: Pixels| px((value.as_f32() * scale).round() / scale); + let left = round(bounds.origin.x); + let top = round(bounds.origin.y); + let right = round(bounds.origin.x + bounds.size.width); + let bottom = round(bounds.origin.y + bounds.size.height); + Bounds::new( + Point::new(left, top), + Size::new((right - left).max(px(0.)), (bottom - top).max(px(0.))), + ) } #[expect( @@ -330,12 +416,21 @@ fn paint_labels( let color = if label.marked { colors.marked_label } else { - colors.label(label.color_depth) + colors.label(label.depth) + }; + // The first level is set in bold in its band: it names a region. + let weight = if label.depth == 0 && label.header.is_some() { + FontWeight::BOLD + } else { + FontWeight::NORMAL }; let run = TextRun { len: label.text.len(), - font: font.clone(), + font: Font { + weight, + ..font.clone() + }, color, ..TextRun::default() }; @@ -381,9 +476,27 @@ fn paint_labels( + ((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() { + // A first-level band puts the size at the far end, where the + // sizes read as a column; a deeper band follows the name. A + // closed tile stacks it under the name when it is tall enough. + let stacked = label.header.is_none() + && mask.size.height >= name_line_height * 2.0 + text_inset; + if stacked { + let _ = size_line.paint( + Point::new( + origin.x, + origin.y + name_line_height * 0.92, + ), + name_line_height, + TextAlign::Left, + None, + window, + cx, + ); + return; + } + let size_origin = if label.header.is_some() && label.depth == 0 + { Point::new( mask.origin.x + mask.size.width - size_line.width() @@ -418,16 +531,6 @@ fn to_window(rect: &Rect, bounds: Bounds) -> Bounds { ) } -fn inset(bounds: Bounds, amount: Pixels) -> Bounds { - 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.rs index 4644f67..c024022 100644 --- a/crates/disktree-app/src/ui.rs +++ b/crates/disktree-app/src/ui.rs @@ -47,6 +47,12 @@ pub mod text { pub const BODY: Rems = Rems(0.75); /// Window, section and dialog titles. pub const TITLE: Rems = Rems(0.875); + /// The app name and the selection's name. + pub const HEADING: Rems = Rems(1.125); + /// A figure worth reading from across the room: the free space. + pub const FIGURE: Rems = Rems(1.625); + /// The selection's size: the one number the panel exists to show. + pub const DISPLAY: Rems = Rems(2.5); } /// Icon slots, sized with the text they sit beside. @@ -63,14 +69,16 @@ pub mod icon { 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); + /// A list row's share bar. + pub const ROW_BAR: Rems = Rems(5.5); + /// A legend or identity swatch. + pub const SWATCH: Rems = Rems(0.625); + /// A thin meter: share of the scan, the disk. + pub const METER: Rems = Rems(0.3125); /// 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 Size | Files | Age choice in the settings row. + pub const RANKING_CHOICE: Rems = Rems(11.0); /// The review screen's summary column. pub const REVIEW_SUMMARY: Rems = Rems(22.5); /// The review list's share-bar lane. diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index e0dcf6d..fff8804 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -4,30 +4,38 @@ //! always exactly what the state says — there is no second copy of anything to //! keep in sync. +use disktree_core::classify::Category; +use disktree_core::insights::{Candidate, Finding, STALE_DAYS}; use disktree_core::removal::{RemovalMode, Target}; use disktree_core::size::human_bytes; use disktree_core::tree::Metric; +use gpui_kit::base::CheckboxState; use gpui_kit::{ - App, Context, Div, ElementId, FontWeight, InteractiveElement as _, - IntoElement, KeyDownEvent, ParentElement, SharedString, Stateful, - StatefulInteractiveElement as _, Styled, Window, div, px, + App, AppContext as _, ClickEvent, Context, Div, DragMoveEvent, ElementId, + FontWeight, InteractiveElement as _, IntoElement, KeyDownEvent, + ParentElement, Rems, SharedString, Stateful, + StatefulInteractiveElement as _, Styled, Window, div, pattern_slash, px, + relative, }; use gpui_omarchy::{ ActiveTheme, ButtonVariant, ChoiceItem, Theme, alert_dialog, button, - button_group, dialog_button, dialog_description, dialog_popup, - dialog_title, separator, toggle, with_tooltip, + button_group, checkbox, dialog_button, dialog_description, dialog_popup, + dialog_title, separator, with_tooltip, }; use gpui_kit::prelude::FluentBuilder as _; -use crate::state::{Disktree, Screen}; +use crate::palette; +use crate::state::{ + ColorMode, Disktree, PANEL_REMS, Scope, Screen, panel_width, +}; 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; +const HEADER_WIDE_REMS: f32 = 86.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. @@ -173,34 +181,1278 @@ fn explore( ) -> 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); + let width_rems = window.viewport_size().width.as_f32() / app.rem; + let wide = width_rems >= HEADER_WIDE_REMS; + // The panel is where the selection, the marks and the disk live; it + // only gives way when the mosaic would be too narrow to read. + let panel = app.show_selection && width_rems >= PANEL_SHOWN_REMS; + if panel && let Some(path) = selection_checkout(app) { + app.ensure_git(&path, cx); + } + + let viewport = 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. + scanning_panel(app, &theme, cx).into_any_element() + } else { + treemap_view::mosaic(mosaic, app, window, cx).into_any_element() + }; 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() + .child(top_bar(app, &theme, wide, window, cx)) + .child( + div() + .id("explore-body") + .flex() + .flex_row() + .flex_1() + .min_h_0() + // The panel's handle starts the drag; the width follows the + // pointer from here, wherever it goes in the window. + .on_drag_move(cx.listener( + |this, event: &DragMoveEvent, window, cx| { + this.panel_rems = panel_width( + event.event.position.x.as_f32(), + window.viewport_size().width.as_f32(), + this.rem, + ); + cx.notify(); + }, + )) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .min_h_0() + .child(trail_and_legend(app, &theme, cx)) + .child( + div() + .flex() + .flex_1() + .min_h_0() + .px(space::LG) + .pb(space::SM) + .child(viewport), + ), + ) + .children(panel.then(|| side_panel(app, &theme, cx))), + ) + .child(key_bar(app, &theme, cx)) +} + +/// The selection, when it is a checkout git can say something about. +fn selection_checkout(app: &Disktree) -> Option { + let target = app.action_target()?; + let node = app.node_at(&target)?; + if !node.is_dir() { + return None; + } + let path = app.path_at(&target)?; + crate::git::is_checkout(&path).then_some(path) +} + +/// Width, in rem, below which the side panel gives the mosaic its room. +const PANEL_SHOWN_REMS: f32 = 52.0; + +/// What the panel handle drags. The width itself lives in the app state. +#[derive(Clone, Copy, Debug)] +struct PanelDrag; + +/// A drag needs a view to draw under the pointer; resizing draws nothing. +struct NoGhost; + +impl gpui_kit::Render for NoGhost { + fn render( + &mut self, + _: &mut Window, + _: &mut Context<'_, Self>, + ) -> impl IntoElement { + div() + } +} + +// ── top bar ───────────────────────────────────────────────────────────── + +/// The app, what the whole scan found, and the controls that decide what +/// is measured, on the edge they own. +fn top_bar( + app: &Disktree, + theme: &Theme, + wide: bool, + window: &mut Window, + cx: &mut Context<'_, Disktree>, +) -> Div { + let tree = app.tree(); + let scanned = tree.map_or(app.progress.bytes, |node| node.bytes); + let files = tree.map_or(app.progress.files, |node| node.files); + let dirs = tree.map_or(app.progress.dirs, |node| node.dirs); + let errors = app.progress.errors; + + let mut row = div() + .flex() + .flex_row() + .items_center() + .gap(space::LG) + .px(space::LG) + .py(space::MD) + .border_b_1() + .border_color(theme.divider()) + .child(logo(theme)) + // What is scanned sits with the name: the totals beside it are + // totals of this choice. + .child(scope_switch(app, window, cx)); + if wide { + let value = |text: String| text; + row = row + .child(widgets::figure( + "Scanned", + value(human_bytes(scanned)), + theme.bright, + cx, + )) + .child(widgets::figure( + "Files", + widgets::human_count(files), + theme.bright, + cx, + )) + .child(widgets::figure( + "Dirs", + widgets::human_count(dirs), + theme.bright, + cx, + )) + .child(widgets::figure( + "Unreadable", + widgets::human_count(errors), + if errors > 0 { + theme.warning + } else { + theme.secondary + }, + cx, + )); + } + row.child(div().flex_1()) + .child(view_settings(app, window, cx)) +} + +/// Four tiles in category colours, and the name. +fn logo(theme: &Theme) -> Div { + let tile = |category| { + div() + .size(space::SM) + .bg(palette::category_accent(theme, category)) + }; + let column = |top, bottom| { + div() + .flex() + .flex_col() + .gap(space::XXS) + .child(tile(top)) + .child(tile(bottom)) + }; + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .flex_shrink_0() + .child( + div() + .flex() + .flex_row() + .gap(space::XXS) + .child(column(Category::Code, Category::Synced)) + .child(column(Category::AgentScratch, Category::Toolchain)), + ) + .child( + div() + .text_size(text::HEADING) + .font_weight(FontWeight::BOLD) + .text_color(theme.bright) + .child("disktree"), + ) +} + +/// 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 mode = { + let entity = entity.clone(); + let focus = focus.clone(); + button_group( + "mode", + vec![ + ChoiceItem::new("size", "Size"), + ChoiceItem::new("files", "Files"), + ChoiceItem::new("age", "Age"), + ], + Some(app.mode_index()), + move |index, window, cx| { + let _ = entity.update(cx, |this, cx| this.set_mode(index, cx)); + window.focus(&focus, cx); }, + window, + cx, + ) + .w(size::RANKING_CHOICE) + // Tighter than a standalone group, so the segmented control shares + // the checkboxes' height and centre line. + .p(space::XXS) + }; + + let check = |on: bool| { + if on { + CheckboxState::Checked + } else { + CheckboxState::Unchecked + } + }; + let hidden = { + let entity = entity.clone(); + let focus = focus.clone(); + checkbox( + "hidden", + "Hidden files", + check(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 = { + checkbox( + "apparent", + "Apparent size", + check(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 theme = cx.omarchy().clone(); + let depth = app.layout_options.max_depth; + let stepper = |id: &'static str, + label: &'static str, + step: i32, + cx: &mut Context<'_, Disktree>| { + button(id, label, ButtonVariant::Secondary, cx) + .tab_stop(false) + .disabled(if step < 0 { depth <= 1 } else { depth >= 6 }) + .on_click(cx.listener(move |this, _, window, cx| { + this.adjust_depth(step, cx); + window.focus(&this.focus, cx); + })) + }; + let depth_control = with_tooltip( + div() + .id("depth") + .flex() + .flex_row() + .items_center() + .border_1() + .border_color(theme.control_border()) + .child( + div() + .px(space::SM) + .text_size(text::BODY) + .text_color(theme.foreground) + .child(format!("Depth {depth}")), + ) + .child(stepper("depth-less", "\u{2212}", -1, cx)) + .child(stepper("depth-more", "+", 1, cx)), + "Levels drawn at once \u{00b7} [ and ]", + ); + + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .flex_shrink_0() + .child(mode) + .child(hidden) + .child(apparent) + .child(depth_control) +} + +// ── trail and legend ──────────────────────────────────────────────────── + +/// Where you are, as a clickable trail, and what the colours mean, on one +/// row over the mosaic. +fn trail_and_legend( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Div { + let trail = app.breadcrumbs(); + let last = trail.len().saturating_sub(1); + let mut crumbs = div() + .flex() + .flex_row() + .items_center() + .gap(space::XXS) + .flex_shrink_0(); + for (index, (label, path)) in trail.into_iter().enumerate() { + if index > 0 { + crumbs = crumbs.child( + div() + .text_color(theme.secondary.opacity(0.5)) + .text_size(text::BODY) + .child("/"), + ); + } + let id = ElementId::Name(SharedString::from(format!("crumb-{index}"))); + crumbs = crumbs.child( + widgets::crumb(id, label, index == last, cx).on_click( + cx.listener(move |this, _, _, cx| this.go_to(path.clone(), cx)), + ), + ); + } + + let mut row = div() + .flex() + .flex_row() + .items_center() + .gap(space::LG) + .px(space::LG) + .py(space::SM) + .child(crumbs); + if app.find_open || !app.find.is_empty() { + row = row.child(find_field(app, theme)); + } + row.child(div().flex_1()).child(legend(app, theme, cx)) +} + +/// What is scanned: the home directory or the whole disk it lives on. A +/// root given on the command line is neither, and selects nothing. +fn scope_switch( + app: &Disktree, + window: &mut Window, + cx: &mut Context<'_, Disktree>, +) -> impl IntoElement { + let entity = cx.entity().downgrade(); + let focus = app.focus.clone(); + let disk = app.disk_root.as_deref().map_or_else( + || "/ Whole disk".to_string(), + |root| format!("{} Whole disk", root.display()), + ); + with_tooltip( + button_group( + "scope", + vec![ + ChoiceItem::new("home", "~ Home"), + ChoiceItem::new("disk", disk), + ], + app.scope().map(|scope| usize::from(scope == Scope::Disk)), + move |index, window, cx| { + let _ = entity.update(cx, |this, cx| { + this.set_scope( + if index == 1 { Scope::Disk } else { Scope::Home }, + cx, + ); + }); + window.focus(&focus, cx); + }, + window, + cx, + ) + .flex_shrink_0() + .p(space::XXS), + "What to scan · g switches", + ) +} + +/// The key to the colours: the categories, or the age ramp in age mode. +/// Clipped from the trailing end when the row runs out of room. +fn legend(app: &Disktree, theme: &Theme, cx: &App) -> Div { + let item = |swatch: Div, label: &'static str| { + div() + .flex() + .flex_row() + .items_center() + .gap(space::XS) + .flex_shrink_0() + .child(swatch) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(label), + ) + }; + let mut lane = div() + .flex() + .flex_row() + .items_center() + .gap(space::MD) + .min_w_0() + .overflow_hidden(); + if app.color_mode == ColorMode::Age { + for (bucket, (_, label)) in palette::AGE_BUCKETS.iter().enumerate() { + lane = lane.child(item( + widgets::swatch(palette::age_accent(theme, bucket)), + label, + )); + } + } else { + for category in Category::LEGEND { + lane = lane.child(item( + widgets::swatch(palette::category_accent(theme, category)), + category.label(), + )); + } + } + let ground = palette::category_fill(theme, Category::Other, 0); + let hatch = cx.omarchy().bright.opacity(0.5); + div() + .flex() + .flex_row() + .items_center() + .gap(space::MD) + .min_w_0() + .overflow_hidden() + .child(item(widgets::hatch_swatch(hatch, ground), "Reclaimable")) + .child(lane) +} + +// ── side panel ────────────────────────────────────────────────────────── + +/// Selection, worth a look, marked, and the disk: everything a decision +/// needs, next to the mosaic rather than under it. +fn side_panel( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Div { + let rule = || div().h(px(1.)).bg(theme.divider()); + // A hairline to look at, a wider strip to grab; double-click resets. + let handle = div() + .id("panel-handle") + .debug_selector(|| "panel-handle".into()) + .absolute() + .top_0() + .bottom_0() + .left(px(-3.)) + .w(px(6.)) + .cursor_col_resize() + .hover(|style| style.bg(theme.accent.opacity(0.35))) + .on_drag(PanelDrag, |_, _, _, cx| cx.new(|_| NoGhost)) + .on_click(cx.listener(|this, event: &ClickEvent, _, cx| { + if event.click_count() >= 2 { + this.panel_rems = PANEL_REMS; + cx.notify(); + } + })); + div() + .relative() + .flex() + .flex_col() + .gap(space::LG) + .w(Rems(app.panel_rems)) + .flex_shrink_0() + .min_h_0() + .px(space::LG) + .py(space::LG) + .border_l_1() + .border_color(theme.divider()) + .bg(theme.surface) + .child(handle) + .child(selection_section(app, theme, cx)) + .child(rule()) + // The lists scroll; the selection above and the disk below stay put, + // so the two numbers that matter never leave the screen. + .child( + div() + .id("panel-lists") + .flex() + .flex_col() + .gap(space::LG) + .flex_1() + .min_h_0() + .overflow_y_scroll() + .child(worth_section(app, theme, cx)) + .child(rule()) + .child(marked_section(app, theme, cx)), + ) + .children(notice_line(app, theme, cx)) + .child(disk_section(app, theme, cx)) +} + +/// What the keys act on: its name and place, its size set large with its +/// share of the scan, when it was last written, what git says, and the two +/// things to do with it. +fn selection_section( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Div { + let section = div() + .flex() + .flex_col() + .gap(space::MD) + .child(widgets::eyebrow("Selection", cx)); + let target = app.action_target().unwrap_or_else(|| app.crumbs.clone()); + let Some(node) = app.node_at(&target) else { + return section.child( + div() + .text_color(theme.secondary) + .child("Point at a tile or select one with the arrows"), + ); + }; + let path = app.path_at(&target); + 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; + let highlight = palette::highlight(theme); + + let identity = div() + .flex() + .flex_col() + .gap(space::XS) + .min_w_0() + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .min_w_0() + .child( + div() + .flex_shrink_0() + .w(space::XS) + .h(text::HEADING) + .bg(palette::category_accent(theme, node.category)), + ) + .child( + div() + .text_size(text::HEADING) + .font_weight(FontWeight::BOLD) + .text_color(theme.bright) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(node.name.to_string()), + ), + ) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(path.as_deref().map_or_else(String::new, |path| { + crate::marks::display_path(path, app.home.as_deref()) + })), + ); + + let (number, unit) = match app.options.metric { + Metric::Bytes => widgets::split_size(&human_bytes(node.bytes)), + Metric::Files => (widgets::human_count(node.files), "files".into()), + }; + let share = node.bytes as f32 / root_value.max(1) as f32; + let measure = div() + .flex() + .flex_col() + .gap(space::SM) + .child(widgets::measure( + number, + text::DISPLAY, + unit, + text::TITLE, + cx, )) - .children(selection.then(|| selection_bar(app, &theme, cx))) - .child(status_bar(app, &theme, !wide, cx)) - .child(hint_bar(app, &theme, cx)) + .child(widgets::bar(share, highlight, cx)); + + let fourth = if node.is_dir() + && let Some(path) = &path + && crate::git::is_checkout(path) + { + let value = match app.git.get(path) { + Some(Some(state)) => state.summary(), + Some(None) => "not readable".to_string(), + None => "asking\u{2026}".to_string(), + }; + let clean = + matches!(app.git.get(path), Some(Some(state)) if state.is_clean()); + widgets::figure( + "Git", + value, + if clean { theme.success } else { theme.bright }, + cx, + ) + } else { + let kind = node.reclaim.map_or_else( + || node.category.label().to_string(), + |reason| { + format!("{} \u{00b7} {}", node.category.label(), reason.label()) + }, + ); + widgets::figure("Kind", kind, theme.bright, cx) + }; + let grid = div() + .flex() + .flex_col() + .gap(space::MD) + .child( + div() + .flex() + .flex_row() + .child(div().flex_1().min_w_0().child(widgets::figure( + "Of scan", + widgets::percent(node.bytes, root_value), + theme.bright, + cx, + ))) + .child(div().flex_1().min_w_0().child(widgets::figure( + "Files", + widgets::human_count(node.files), + theme.bright, + cx, + ))), + ) + .child( + div() + .flex() + .flex_row() + .child(div().flex_1().min_w_0().child(widgets::figure( + "Last write", + widgets::ago(crate::state::now_seconds(), node.modified), + theme.bright, + cx, + ))) + .child(div().flex_1().min_w_0().child(fourth)), + ); + + // Only states that change the decision earn a badge. + let mut chips = Vec::new(); + if marked { + chips.push(widgets::chip("Marked", theme.danger, cx)); + } + if let Some(ancestor) = &covered_by { + chips.push(widgets::chip( + format!("Inside marked {ancestor}"), + theme.secondary, + cx, + )); + } + if node.read_error { + chips.push(widgets::chip("Partly unreadable", theme.warning, cx)); + } + let badges = (!chips.is_empty()).then(|| { + div() + .flex() + .flex_row() + .flex_wrap() + .gap(space::XS) + .children(chips) + }); + + // Open is secondary: Enter already does it. Marking is the action this + // tool exists for, so it takes the highlight. + let mut actions = div().flex().flex_row().gap(space::SM); + if !is_current_root { + if node.is_dir() { + let crumbs = target.clone(); + actions = actions.child( + button("open", "Open", ButtonVariant::Outline, cx) + .tab_stop(false) + .flex_1() + .justify_center() + .on_click(cx.listener(move |this, _, window, cx| { + this.go_to(crumbs.clone(), cx); + window.focus(&this.focus, cx); + })), + ); + } + let crumbs = target; + let mark = button( + "mark", + if marked { "Unmark" } else { "Mark for removal" }, + ButtonVariant::Primary, + cx, + ) + .tab_stop(false) + .flex_1() + .justify_center() + .on_click(cx.listener(move |this, _, window, cx| { + this.toggle_mark(&crumbs.clone(), cx); + window.focus(&this.focus, cx); + })); + actions = actions.child(if marked { + mark + } else { + let on = palette::on_highlight(theme); + mark.bg(highlight) + .border_color(highlight) + .text_color(on) + .font_weight(FontWeight::SEMIBOLD) + .hover(move |style| { + style.bg(highlight.opacity(0.85)).border_color(highlight) + }) + }); + } + + section + .child(identity) + .child(measure) + .child(grid) + .children(badges) + .child(actions) +} + +/// The biggest things that could plausibly go, with their total. +fn worth_section( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Div { + let total: u64 = app.insights.iter().map(|candidate| candidate.bytes).sum(); + let largest = app.insights.first().map_or(1, |candidate| candidate.bytes); + let highlight = palette::highlight(theme); + let mut section = div().flex().flex_col().gap(space::XS).child( + div() + .flex() + .flex_row() + .items_center() + .justify_between() + .pb(space::XS) + .child(widgets::eyebrow("Worth a look", cx)) + .when(total > 0, |this| { + this.child( + div() + .text_size(text::CAPTION) + .text_color(highlight) + .child(human_bytes(total)), + ) + }), + ); + if app.insights.is_empty() { + return section.child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(if app.tree().is_some() { + "Nothing obviously disposable" + } else { + "Waiting for the scan" + }), + ); + } + let selected = app.action_target(); + for (index, candidate) in app.insights.iter().enumerate() { + let Some(node) = app.node_at(&candidate.crumbs) else { + continue; + }; + let (title, detail) = insight_text(app, candidate); + let accent = palette::category_accent(theme, node.category); + let active = selected.as_deref() == Some(candidate.crumbs.as_slice()); + let crumbs = candidate.crumbs.clone(); + section = section.child( + div() + .id(ElementId::Name(format!("insight-{index}").into())) + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .px(space::SM) + .py(space::XS) + .when(active, |this| this.bg(theme.hover_fill())) + .hover(|style| style.bg(theme.hover_fill())) + .on_click(cx.listener(move |this, _, window, cx| { + this.reveal(crumbs.clone(), cx); + window.focus(&this.focus, cx); + })) + .child(div().flex_shrink_0().w(px(2.)).h(space::XL).bg(accent)) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .child( + div() + .text_size(text::BODY) + .text_color(theme.bright) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(title), + ) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary.opacity(0.8)) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(detail), + ), + ) + .child( + div() + .flex() + .flex_col() + .items_end() + .gap(space::XS) + .flex_shrink_0() + .w(size::ROW_BAR) + .child( + div() + .text_size(text::BODY) + .text_color(theme.bright) + .child(human_bytes(candidate.bytes)), + ) + .child(widgets::bar( + candidate.bytes as f32 / largest.max(1) as f32, + accent, + cx, + )), + ), + ); + } + section +} + +/// A finding's title, as the last two parts of its path, and why it is on +/// the list. +fn insight_text(app: &Disktree, candidate: &Candidate) -> (String, String) { + let tree = app.tree(); + let chain = tree + .map_or_else(Vec::new, |tree| tree.resolve_chain(&candidate.crumbs)); + let names: Vec<&str> = + chain.iter().skip(1).map(|node| &*node.name).collect(); + let tail = names[names.len().saturating_sub(2)..].join("/"); + match &candidate.finding { + Finding::Reclaimable(reason) => (tail, reason.label().to_string()), + Finding::Worktrees { count, oldest_days } => ( + tail, + format!( + "{count} worktree{} \u{00b7} oldest {oldest_days} d", + if *count == 1 { "" } else { "s" } + ), + ), + Finding::StaleExperiments { count } => ( + format!("{tail} > {STALE_DAYS} days"), + format!( + "{count} experiment{} untouched", + if *count == 1 { "" } else { "s" } + ), + ), + } +} + +/// What is queued for removal, each with a way off the list. +fn marked_section( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Div { + let plan = app.plan(); + let count = app.marks.len(); + let header = div() + .flex() + .flex_row() + .items_center() + .justify_between() + .child(widgets::eyebrow( + if count == 0 { + "Marked".to_string() + } else { + format!("Marked · {count}") + }, + cx, + )) + .when(count > 0, |this| { + this.child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(human_bytes(plan.bytes())), + ) + }); + let mut section = div().flex().flex_col().gap(space::XS).child(header); + if count == 0 { + return section.child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child("Space marks the tile you point at"), + ); + } + for (index, item) in app.marks.items().iter().take(MARKED_ROWS).enumerate() + { + let category = app + .crumbs_for_path(&item.path) + .and_then(|crumbs| app.node_at(&crumbs)) + .map_or(Category::Other, |node| node.category); + let path = item.path.clone(); + section = section.child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .text_size(text::CAPTION) + .child( + div() + .flex_shrink_0() + .size(space::SM) + .rounded_full() + .bg(palette::category_accent(theme, category)), + ) + .child( + div() + .flex_1() + .min_w_0() + .text_color(theme.foreground) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(crate::marks::display_path( + &item.path, + app.home.as_deref(), + )), + ) + .child( + div() + .flex_shrink_0() + .text_color(theme.secondary) + .child(human_bytes(item.bytes)), + ) + .child( + div() + .id(ElementId::Name(format!("unmark-{index}").into())) + .flex_shrink_0() + .px(space::XS) + .text_color(theme.secondary.opacity(0.7)) + .hover(|style| style.text_color(theme.danger)) + .on_click(cx.listener(move |this, _, window, cx| { + this.unmark(&path, cx); + window.focus(&this.focus, cx); + })) + .child("\u{00d7}"), + ), + ); + } + if count > MARKED_ROWS { + section = section.child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(format!( + "+{} more on the review screen", + count - MARKED_ROWS + )), + ); + } + if !plan.covered.is_empty() || !plan.blocked.is_empty() { + section = section.child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(format!( + "{} nested \u{00b7} {} kept back", + plan.covered.len(), + plan.blocked.len() + )), + ); + } + section +} + +/// Marked rows the panel lists before pointing at the review screen. +const MARKED_ROWS: usize = 6; + +/// The last thing that happened, or a scan error, above the disk. +fn notice_line(app: &Disktree, theme: &Theme, cx: &App) -> Option
{ + let (message, color) = if let Some(error) = &app.scan_error { + (error.clone(), theme.danger) + } else { + let (message, status) = app.notice.as_ref()?; + (message.clone(), widgets::alert_color(*status, cx)) + }; + Some( + div() + .px(space::SM) + .py(space::XS) + .border_1() + .border_color(color.opacity(0.5)) + .text_color(color) + .text_size(text::CAPTION) + .child(message), + ) +} + +/// Free space on the volume now, and after the marks go. +fn disk_section( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Div { + let device = app.device.clone().unwrap_or_default(); + let mut section = div().flex().flex_col().gap(space::SM).child( + div() + .flex() + .flex_row() + .gap(space::SM) + .child(widgets::eyebrow("Disk", cx)) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary.opacity(0.6)) + .child(device), + ), + ); + let Some(space_info) = app.space else { + return section.child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child("Free space is not available here"), + ); + }; + let reclaiming = app.plan().bytes(); + let after = space_info.after_removing(reclaiming); + let highlight = palette::highlight(theme); + let (number, unit) = + widgets::split_size(&human_bytes(space_info.available)); + let total = space_info.total.max(1) as f32; + let used_now = (space_info.used() as f32 / total).clamp(0.0, 1.0); + let used_after = (after.used() as f32 / total).clamp(0.0, used_now); + + section = section.child( + div() + .flex() + .flex_row() + .items_end() + .child(widgets::measure( + number, + text::FIGURE, + format!("{unit} free"), + text::BODY, + cx, + )) + .child(div().flex_1()) + .when(reclaiming > 0, |this| { + // Lifted like the unit beside the figure, onto its baseline. + this.child( + div() + .text_size(text::TITLE) + .line_height(text::TITLE) + .pb(gpui_kit::Rems( + (text::FIGURE.0 - text::TITLE.0) * 0.2, + )) + .text_color(highlight) + .child(format!( + "→ {} free", + human_bytes(after.available) + )), + ) + }), + ); + // Used space from the left; the slice the marks give back is the hatched + // end of it, so the gap it leaves is exactly what comes back. + section = section.child( + div() + .relative() + .w_full() + .h(space::SM) + .bg(theme.foreground.opacity(0.08)) + .child( + div() + .absolute() + .left_0() + .top_0() + .h_full() + .w(relative(used_after)) + .bg(theme.foreground.opacity(0.28)), + ) + .child( + div() + .absolute() + .left(relative(used_after)) + .top_0() + .h_full() + .w(relative(used_now - used_after)) + .bg(highlight.opacity(0.25)) + .child( + div() + .size_full() + .bg(pattern_slash(highlight, 1.0, 3.0)), + ), + ), + ); + section + .child( + div() + .flex() + .flex_row() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(format!("{} used", human_bytes(space_info.used()))) + .child(div().flex_1()) + .child(format!("{} total", human_bytes(space_info.total))), + ) + .children( + (!app.marks.is_empty()) + .then(|| review_button(app, reclaiming, theme, cx)), + ) +} + +/// The way to the review screen, where the saving is: it says what is +/// marked and what it frees, so the number that matters is the thing to +/// press. Outlined in the highlight, so it does not compete with the filled +/// "Mark for removal" above it. +fn review_button( + app: &Disktree, + reclaiming: u64, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> impl IntoElement { + let highlight = palette::highlight(theme); + let count = app.marks.len(); + div() + .id("review") + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .mt(space::XS) + .px(space::MD) + .py(space::SM) + .border_1() + .border_color(highlight) + .bg(highlight.opacity(0.1)) + .hover(move |style| style.bg(highlight.opacity(0.18))) + .active(move |style| style.bg(highlight.opacity(0.26))) + .on_click(cx.listener(|this, _, window, cx| { + this.screen = Screen::Review; + cx.notify(); + window.focus(&this.focus, cx); + })) + .child( + div() + .flex_1() + .min_w_0() + .text_size(text::BODY) + .text_color(highlight) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(format!( + "Review {count} marked · frees {}…", + human_bytes(reclaiming) + )), + ) + .child(gpui_omarchy::keycap("c", cx)) +} + +// ── key bar ───────────────────────────────────────────────────────────── + +/// The keys, quietly: outlines and light labels, there when needed. The key +/// to every other key and the scan's own numbers hold the trailing edge. +fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div { + // Most useful first, so a narrow window clips the least useful. + let hints: [(&str, &str); 10] = [ + ("space", "mark"), + ("enter", "open"), + ("\u{232b}", "up"), + ("c", "review"), + ("hjkl", "move"), + ("/", "find"), + ("[ ]", "depth"), + ("t", "mode"), + ("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::XS) + .border_t_1() + .border_color(theme.divider()) + .child(lane); + 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)), + ); + } + let scan = if app.scan.is_some() { + format!( + "scanning \u{00b7} {} entries \u{00b7} {}", + widgets::human_count(app.progress.files), + human_bytes(app.progress.bytes) + ) + } else { + let elapsed = app.scan_elapsed.map_or_else(String::new, |time| { + format!(" \u{00b7} {:.1} s", time.as_secs_f32()) + }); + format!( + "scan {} entries{elapsed}", + widgets::human_count(app.progress.files) + ) + }; + row.child(widgets::hint("?", "all keys", cx).flex_shrink_0()) + .child( + div() + .flex_shrink_0() + .text_size(text::CAPTION) + .text_color(theme.secondary.opacity(0.7)) + .child(scan), + ) } /// What the viewport shows while the first scan is running. @@ -283,54 +1535,6 @@ fn scanning_panel(app: &Disktree, theme: &Theme, cx: &gpui_kit::App) -> Div { 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() @@ -361,317 +1565,6 @@ fn find_field(app: &Disktree, theme: &Theme) -> Div { }) } -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(), @@ -693,171 +1586,6 @@ fn marks_ancestor( .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 { @@ -870,57 +1598,6 @@ fn progress_estimate(files: u64) -> f32 { } } -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( @@ -1803,7 +2480,7 @@ 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] = [ + let rows: [(&str, &str); 24] = [ ("space / x", "Mark or unmark the tile you point at"), ("ctrl-click", "Mark without moving the selection"), ("enter", "Open that directory, at any depth"), @@ -1820,8 +2497,9 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { ("ctrl = / - / 0", "Interface zoom"), ("/", "Find an entry by name"), ("c", "Review the marked list"), - ("t", "Rank by size or by file count"), + ("t", "Size, files or age: what areas and colours say"), ("r", "Scan again from the same root"), + ("g", "Scan the home directory or the whole disk"), ("d", "Disk usage or apparent size"), ("i", "Include or skip hidden entries"), ("p", "Show or hide the selection line"), diff --git a/crates/disktree-app/src/widgets.rs b/crates/disktree-app/src/widgets.rs index 5849eb5..3ba4137 100644 --- a/crates/disktree-app/src/widgets.rs +++ b/crates/disktree-app/src/widgets.rs @@ -35,14 +35,6 @@ pub fn short_value(node: &Node, metric: Metric) -> String { } } -/// 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, @@ -345,3 +337,174 @@ pub fn crumb( }) .child(label.into()) } + +/// A small uppercase label over a region or a figure. +pub fn eyebrow(label: impl Into, cx: &App) -> Div { + let theme = cx.omarchy(); + let label: SharedString = label.into(); + div() + .text_size(text::CAPTION) + .text_color(theme.secondary.opacity(0.7)) + .whitespace_nowrap() + .child(SharedString::from(label.to_uppercase())) +} + +/// An eyebrow over a value, for the top bar and the selection grid. +pub fn figure( + label: impl Into, + value: impl Into, + color: Hsla, + cx: &App, +) -> Div { + div() + .flex() + .flex_col() + .gap(space::XXS) + .min_w_0() + .child(eyebrow(label, cx)) + .child( + div() + .text_size(text::TITLE) + .text_color(color) + .whitespace_nowrap() + .overflow_hidden() + .child(value.into()), + ) +} + +/// A size split into number and unit, so the number can be set large: +/// `90.1 GiB` is `("90.1", "GiB")`. +pub fn split_size(text: &str) -> (String, String) { + text.split_once(' ').map_or_else( + || (text.to_string(), String::new()), + |(number, unit)| (number.to_string(), unit.to_string()), + ) +} + +/// How long ago a Unix time was, in the unit a person would use. +pub fn ago(now: i64, then: i64) -> String { + if then <= 0 { + return "unknown".to_string(); + } + let seconds = (now - then).max(0); + let plural = |count: i64, unit: &str| { + if count == 1 { + format!("1 {unit} ago") + } else { + format!("{count} {unit}s ago") + } + }; + match seconds { + 0..60 => "just now".to_string(), + 60..3_600 => plural(seconds / 60, "minute"), + 3_600..86_400 => plural(seconds / 3_600, "hour"), + 86_400..5_184_000 => plural(seconds / 86_400, "day"), + 5_184_000..63_072_000 => plural(seconds / 2_592_000, "month"), + _ => plural(seconds / 31_536_000, "year"), + } +} + +/// A thin bar: `fraction` of a track, in `color`. +pub fn bar(fraction: f32, color: Hsla, cx: &App) -> Div { + let theme = cx.omarchy(); + div() + .relative() + .w_full() + .h(crate::ui::size::METER) + .bg(theme.foreground.opacity(0.08)) + .child( + div() + .absolute() + .left_0() + .top_0() + .h_full() + .w(relative(fraction.clamp(0.0, 1.0))) + .bg(color), + ) +} + +/// A square of colour, for a legend or an identity. +pub fn swatch(color: Hsla) -> Div { + div() + .flex_shrink_0() + .size(crate::ui::size::SWATCH) + .bg(color) +} + +/// The hatch swatch that stands for reclaimable space in the legend. +pub fn hatch_swatch(color: Hsla, ground: Hsla) -> Div { + div() + .flex_shrink_0() + .size(crate::ui::size::SWATCH) + .bg(ground) + .child( + div() + .size_full() + .bg(gpui_kit::pattern_slash(color, 1.0, 3.0)), + ) +} + +/// A large number followed by its small unit, sharing one baseline. +/// +/// Flex baseline alignment does not line up text of different sizes here, +/// so both are set on bottom-aligned boxes exactly one line tall, and the +/// unit is lifted by the difference in their descents: a font's descent is +/// close to a fifth of its size. +pub fn measure( + number: impl Into, + number_size: gpui_kit::Rems, + unit: impl Into, + unit_size: gpui_kit::Rems, + cx: &App, +) -> Div { + let theme = cx.omarchy(); + let lift = gpui_kit::Rems((number_size.0 - unit_size.0) * DESCENT); + div() + .flex() + .flex_row() + .items_end() + .gap(space::SM) + .child( + div() + .text_size(number_size) + .line_height(number_size) + .font_weight(FontWeight::BOLD) + .text_color(theme.bright) + .child(number.into()), + ) + .child( + div() + .text_size(unit_size) + .line_height(unit_size) + .pb(lift) + .text_color(theme.secondary) + .whitespace_nowrap() + .child(unit.into()), + ) +} + +/// A font's descent as a share of its size, for lining up baselines. +const DESCENT: f32 = 0.2; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ages_read_in_the_unit_a_person_would_use() { + let now = 1_800_000_000; + assert_eq!(ago(now, now - 5), "just now"); + assert_eq!(ago(now, now - 120), "2 minutes ago"); + assert_eq!(ago(now, now - 3_600), "1 hour ago"); + assert_eq!(ago(now, now - 19 * 86_400), "19 days ago"); + assert_eq!(ago(now, now - 90 * 86_400), "3 months ago"); + assert_eq!(ago(now, now - 800 * 86_400), "2 years ago"); + assert_eq!(ago(now, 0), "unknown"); + } + + #[test] + fn sizes_split_into_number_and_unit() { + assert_eq!(split_size("90.1 GiB"), ("90.1".into(), "GiB".into())); + assert_eq!(split_size("0"), ("0".into(), String::new())); + } +}