diff --git a/AGENTS.md b/AGENTS.md index aa007950..662e8602 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -140,6 +140,7 @@ and `cargo build --release` directly; CI runs the gate on both systems. | parallel scan, arena, Protobuf cache DB, SWR | `crates/disktree-scanner/src/` (`walk.rs`, `tree.rs`, `db.rs`, `session.rs`) | | bounded-memory streaming walk | `crates/disktree-scanner/src/stream.rs` (wired into `disktree-core/src/remote_walk.rs`) | | terminal TUI and `--json` / `--ndjson` CLI | `crates/disktree-cli/src/` | +| visual terminal treemap, keys, and review | `crates/disktree-cli/src/treemap/` | | SSH protocol, discovery and transport | `crates/disktree-core/src/remote.rs` | | joining, splitting or comparing a scanned path | `crates/disktree-core/src/path_style.rs` | | arena-to-treemap projection and `ScanHandle` | `crates/disktree-core/src/scan.rs` | diff --git a/Cargo.lock b/Cargo.lock index 458f33cd..987d4fb1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1628,12 +1628,17 @@ dependencies = [ "crossterm", "disktree-core", "disktree-scanner", + "dunce", "ratatui", "rustc-hash 2.1.3", "rustix 1.1.4", "serde", "serde_json", "tempfile", + "toml 0.8.23", + "unicode-segmentation", + "unicode-width 0.2.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/README.md b/README.md index aa6321f5..d766fc1d 100644 --- a/README.md +++ b/README.md @@ -566,6 +566,37 @@ windowrule = float, class:^(disktree)$ windowrule = size 1400 900, class:^(disktree)$ ``` +## In the terminal + +![A nested treemap, selection details, and disk space in a 120-column terminal](assets/tui/120.png) + +Run the visual treemap with the `disktree-cli` release binary: + +```sh +disktree-cli treemap # scan your home directory +disktree-cli treemap ~/src # scan a chosen directory +disktree-cli treemap --disk # scan the volume containing your home +``` + +The treemap shows an inspector at 120 columns, a +[compact map](assets/tui/80.png) around 80, and a +[list](assets/tui/45.png) around 45. It scans the machine where it runs, +including in an SSH session, and follows Omarchy colours when available. +Use `--theme dark` or `--theme light` to override the palette. + +Use **h/j/k/l** or the arrow keys to move, **Enter** to open a directory, +**Backspace** to go up, and **?** for the key guide. **t** rotates Size, +Files, and Age. **i** and **d** change hidden and apparent size views from +the same scan. Use **V** to select a volume and **r** to scan again. + +**Space** marks a path and **c** opens review. From there **a** writes an +agent prompt to stdout after restoring the terminal, and **s** saves it +to a file. Local cleanup uses the shared removal guards and asks for +confirmation before permanent deletion. + +Build from source with `cargo build --release --locked -p disktree-cli`. +On macOS, give the terminal Full Disk Access to scan protected folders. + ## Develop ```sh @@ -585,6 +616,7 @@ gone while their neighbours are not. | path | what lives there | | --- | --- | | `crates/disktree-core` | scanning, the tree, the squarified layout, free space and removal — no UI | +| `crates/disktree-cli/src/treemap` | terminal treemap, navigation, themes, and review | | `crates/disktree-app/src/state.rs` | every action the interface can take, and the key map | | `crates/disktree-app/src/views.rs` | the screens | | `crates/disktree-app/src/treemap_view.rs` | painting the mosaic and its labels | diff --git a/assets/tui/120.png b/assets/tui/120.png new file mode 100644 index 00000000..4ab46374 Binary files /dev/null and b/assets/tui/120.png differ diff --git a/assets/tui/45.png b/assets/tui/45.png new file mode 100644 index 00000000..b78fbd8e Binary files /dev/null and b/assets/tui/45.png differ diff --git a/assets/tui/80.png b/assets/tui/80.png new file mode 100644 index 00000000..836cdfac Binary files /dev/null and b/assets/tui/80.png differ diff --git a/assets/tui/fixture.tar.gz b/assets/tui/fixture.tar.gz new file mode 100644 index 00000000..39cff6bd Binary files /dev/null and b/assets/tui/fixture.tar.gz differ diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index a84bad3c..decdbb22 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -12,7 +12,7 @@ use std::time::{Duration, Instant}; use disktree_core::access::file_table_readable; use disktree_core::filter::{Keep, filter}; -use disktree_core::insights::{Candidate, worth_a_look}; +use disktree_core::insights::{Candidate, INSIGHT_LIMIT, worth_a_look}; use disktree_core::path_style::PathStyle; use disktree_core::removal::{ Plan, RemovalEvent, RemovalHandle, RemovalMode, Target, TrashBackend, @@ -109,9 +109,6 @@ pub fn panel_width(pointer_x: f32, viewport: f32, rem: f32) -> f32 { width.clamp(PANEL_MIN_REMS, max) } -/// How many "worth a look" findings the panel lists. -const INSIGHT_LIMIT: usize = 6; - /// Duration of the tile freshness colour fade when a square becomes fresh. const FRESHNESS_FADE_MS: f32 = 200.0; /// Duration of smooth per-tile rectangle gliding when sizes update during a diff --git a/crates/disktree-cli/Cargo.toml b/crates/disktree-cli/Cargo.toml index af1c5df5..47a82c4c 100644 --- a/crates/disktree-cli/Cargo.toml +++ b/crates/disktree-cli/Cargo.toml @@ -23,6 +23,13 @@ ratatui = "0.29" rustc-hash = { workspace = true } serde = { version = "1", features = ["derive"] } serde_json = "1" +toml = "0.8" +unicode-segmentation = "1" +unicode-width = "0.2" + +[target.'cfg(windows)'.dependencies] +dunce = "1" +windows-sys = { version = "0.61", features = ["Win32_System_Console"] } [target.'cfg(target_os = "linux")'.dependencies] rustix = { version = "1.1", features = ["process"] } diff --git a/crates/disktree-cli/src/cli.rs b/crates/disktree-cli/src/cli.rs index e5c33587..17e794af 100644 --- a/crates/disktree-cli/src/cli.rs +++ b/crates/disktree-cli/src/cli.rs @@ -106,6 +106,9 @@ pub enum BackendArg { #[derive(Clone, Debug, Subcommand)] pub enum Command { + /// Explore a local directory as a visual treemap. + Treemap(crate::treemap::Args), + /// Mark one or more paths dirty in the cache DB (e.g. after deleting files) /// so subsequent runs revalidate them immediately. Invalidate { diff --git a/crates/disktree-cli/src/main.rs b/crates/disktree-cli/src/main.rs index 08f4a794..2d175c0c 100644 --- a/crates/disktree-cli/src/main.rs +++ b/crates/disktree-cli/src/main.rs @@ -5,6 +5,7 @@ mod cli; mod format; mod json_out; mod stdio; +mod treemap; mod tui; use std::io::{self, IsTerminal as _, Write as _}; @@ -184,9 +185,10 @@ fn run_subcommand( mode: StorageMode, policy: disktree_scanner::CachePolicy, ) -> Result<()> { - let scanner = Scanner::new(mode, policy)?; match command { + Command::Treemap(options) => return treemap::run(options), Command::Invalidate { paths, json } => { + let scanner = Scanner::new(mode, policy)?; let report = scanner.invalidate(&HostKey::Local, paths)?; if *json { #[derive(Serialize)] @@ -212,41 +214,47 @@ fn run_subcommand( ); } } - Command::Cache { action } => match action { - CacheAction::Status { json } => { - let stats = scanner.cache_stats()?; - if *json { - let mut stdout = io::stdout().lock(); - serde_json::to_writer_pretty(&mut stdout, &stats)?; - writeln!(stdout)?; - } else { - println!("mode: {:?}", scanner.active_mode()); - if let Some(path) = &stats.db_path { - println!("db_path: {}", path.display()); + Command::Cache { action } => { + let scanner = Scanner::new(mode, policy)?; + match action { + CacheAction::Status { json } => { + let stats = scanner.cache_stats()?; + if *json { + let mut stdout = io::stdout().lock(); + serde_json::to_writer_pretty(&mut stdout, &stats)?; + writeln!(stdout)?; + } else { + println!("mode: {:?}", scanner.active_mode()); + if let Some(path) = &stats.db_path { + println!("db_path: {}", path.display()); + } + println!( + "db_size: {}", + human_bytes(stats.db_bytes) + ); + println!("hosts: {}", stats.hosts); + println!("indexed_dirs: {}", stats.indexed_dirs); + println!("chunks: {}", stats.chunks); } - println!("db_size: {}", human_bytes(stats.db_bytes)); - println!("hosts: {}", stats.hosts); - println!("indexed_dirs: {}", stats.indexed_dirs); - println!("chunks: {}", stats.chunks); } - } - CacheAction::Clear { json } => { - scanner.clear_cache()?; - if *json { - println!(r#"{{"cleared":true}}"#); - } else { - println!("Cache cleared."); + CacheAction::Clear { json } => { + scanner.clear_cache()?; + if *json { + println!(r#"{{"cleared":true}}"#); + } else { + println!("Cache cleared."); + } } - } - CacheAction::Prune { older_than, json } => { - let pruned = scanner.prune_cache(*older_than)?; - if *json { - println!(r#"{{"pruned_chunks":{pruned}}}"#); - } else { - println!("Pruned {pruned} expired chunk(s)."); + CacheAction::Prune { older_than, json } => { + let pruned = scanner.prune_cache(*older_than)?; + if *json { + println!(r#"{{"pruned_chunks":{pruned}}}"#); + } else { + println!("Pruned {pruned} expired chunk(s)."); + } } } - }, + } } Ok(()) } diff --git a/crates/disktree-cli/src/treemap/app.rs b/crates/disktree-cli/src/treemap/app.rs new file mode 100644 index 00000000..2879569b --- /dev/null +++ b/crates/disktree-cli/src/treemap/app.rs @@ -0,0 +1,2335 @@ +//! Terminal session state. Filesystem decisions remain in `disktree-core`. + +use std::cell::{Cell, RefCell}; +use std::fs::OpenOptions; +use std::io; +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::rc::Rc; +use std::sync::Arc; +use std::sync::mpsc::{self, Receiver, TryRecvError}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use disktree_core::filter::{Matches, filter}; +use disktree_core::insights::{Candidate, INSIGHT_LIMIT, worth_a_look}; +use disktree_core::path_style::PathStyle; +use disktree_core::removal::{ + Plan, RemovalEvent, RemovalHandle, RemovalMode, Target, TrashBackend, + detect_trash_backend, plan, +}; +use disktree_core::scan::{ + ScanHandle, ScanOptions, ScanSnapshot, ScanUpdate, arena_to_node, +}; +use disktree_core::space::{ + SpaceInfo, Volume, device_for, space_info, volume_root_for, volumes, +}; +use disktree_core::tree::{Metric, Node, path_of}; +use disktree_core::treemap::{ + LayoutOptions, Rect as MapRect, Tile, TileKind, layout_filtered, +}; +use disktree_scanner::{ArenaNode, TreeArena}; +use ratatui::layout::Rect; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Screen { + #[default] + Explore, + Review, + Confirm, + Running, + Done, + Help, + Insights, + SavePrompt, + Volumes, +} + +/// The GUI's Size | Files | Age choice. Age keeps size-based geometry and +/// changes the mosaic's color encoding. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ViewMode { + #[default] + Size, + Files, + Age, +} + +impl ViewMode { + pub const fn next(self) -> Self { + match self { + Self::Size => Self::Files, + Self::Files => Self::Age, + Self::Age => Self::Size, + } + } + + pub const fn metric(self) -> Metric { + match self { + Self::Files => Metric::Files, + Self::Size | Self::Age => Metric::Bytes, + } + } + + pub const fn label(self) -> &'static str { + match self { + Self::Size => "Size", + Self::Files => "Files", + Self::Age => "Age", + } + } +} + +#[derive(Clone, Copy, Debug)] +enum Direction { + Left, + Right, + Up, + Down, +} + +impl Direction { + fn gap(self, from: Rect, target: Rect) -> Option { + let gap = match self { + Self::Left => f32::from(from.x) - f32::from(target.right()), + Self::Right => f32::from(target.x) - f32::from(from.right()), + Self::Up => f32::from(from.y) - f32::from(target.bottom()), + Self::Down => f32::from(target.y) - f32::from(from.bottom()), + }; + (gap >= -0.5).then_some(gap.max(0.0)) + } + + fn offset(self, from: Rect, target: Rect) -> f32 { + let overlap = |a: u16, a_end: u16, b: u16, b_end: u16| { + f32::from(a_end.min(b_end).saturating_sub(a.max(b))) + }; + match self { + Self::Left | Self::Right => { + f32::from(from.height.min(target.height)) + - overlap(from.y, from.bottom(), target.y, target.bottom()) + } + Self::Up | Self::Down => { + f32::from(from.width.min(target.width)) + - overlap(from.x, from.right(), target.x, target.right()) + } + } + .max(0.0) + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RunSummary { + pub total: usize, + pub removed: u64, + pub bytes: u64, + pub failed: usize, +} + +/// Direct child positions need no index allocation; filtered positions are +/// cached because checking every child on each animated frame is expensive. +#[derive(Clone, Debug)] +pub enum VisibleChildren { + All(usize), + Filtered(Rc>), +} + +impl VisibleChildren { + pub(crate) fn len(&self) -> usize { + match self { + Self::All(count) => *count, + Self::Filtered(indices) => indices.len(), + } + } + + pub(crate) fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub(crate) fn get(&self, position: usize) -> Option { + match self { + Self::All(count) => (position < *count).then_some(position), + Self::Filtered(indices) => indices.get(position).copied(), + } + } + + fn position(&self, child: usize) -> Option { + match self { + Self::All(count) => (child < *count).then_some(child), + Self::Filtered(indices) => indices.binary_search(&child).ok(), + } + } +} + +#[derive(Debug)] +pub struct App { + pub root: PathBuf, + pub options: ScanOptions, + pub mode: ViewMode, + pub tree: Option, + pub scan: Option, + pub progress: ScanSnapshot, + pub scan_error: Option, + pub current: Vec, + pub selected: Option>, + pub screen: Screen, + pub marks: Vec, + pub space: Option, + pub device: Option, + pub view_depth: u32, + pub scan_elapsed: Option, + pub scanned_at: i64, + pub trash_backend: TrashBackend, + pub removal_mode: RemovalMode, + pub run: Option, + pub run_cancelled: bool, + pub run_summary: RunSummary, + pub run_log: Vec<(PathBuf, Result<(), String>)>, + pub measured_gain: Option, + pub baseline_space: Option, + pub notice: Option, + pub search_open: bool, + pub search: String, + pub matches: Option, + pub list_view: bool, + pub list_scroll: usize, + pub scroll: usize, + pub insights: Vec, + pub insight_index: usize, + pub volumes: Vec, + pub volume_highlight: usize, + pub volumes_loading: bool, + pub save_path: String, + pub quit: bool, + pub stdout_prompt: Option, + viewport: Rect, + scan_started: Option, + arena: Option>, + scan_view: (Metric, bool, bool), + last_space_check: Instant, + marquee_started: Instant, + focused_marquee_started: Instant, + animation_wake: Cell>, + // Layout sorts children; only navigation, scans, filters and resize can + // change it, so animation frames can reuse the same tiles. + tiles_cache: RefCell>)>>, + children_cache: RefCell>>>, + volume_scan: Option>>, +} + +impl App { + pub fn new(root: PathBuf, options: ScanOptions) -> Self { + let trash_backend = detect_trash_backend(); + let mode = if options.metric == Metric::Files { + ViewMode::Files + } else { + ViewMode::Size + }; + let mut app = Self { + space: space_info(&root).ok(), + device: device_for(&root), + root, + mode, + arena: None, + scan_view: view_options(&options), + options, + tree: None, + scan: None, + progress: ScanSnapshot::default(), + scan_error: None, + current: Vec::new(), + selected: None, + screen: Screen::Explore, + marks: Vec::new(), + view_depth: 3, + scan_elapsed: None, + scanned_at: now_seconds(), + trash_backend, + removal_mode: if trash_backend.is_available() { + RemovalMode::Trash + } else { + RemovalMode::Permanent + }, + run: None, + run_cancelled: false, + run_summary: RunSummary::default(), + run_log: Vec::new(), + measured_gain: None, + baseline_space: None, + notice: None, + search_open: false, + search: String::new(), + matches: None, + list_view: false, + list_scroll: 0, + scroll: 0, + insights: Vec::new(), + insight_index: 0, + volumes: Vec::new(), + volume_highlight: 0, + volumes_loading: false, + save_path: String::new(), + quit: false, + stdout_prompt: None, + viewport: Rect::new(0, 0, 120, 35), + scan_started: None, + last_space_check: Instant::now(), + marquee_started: Instant::now(), + focused_marquee_started: Instant::now(), + animation_wake: Cell::new(None), + tiles_cache: RefCell::new(None), + children_cache: RefCell::new(None), + volume_scan: None, + }; + disktree_core::removal::prime_mount_points(); + app.start_scan(); + app + } + + pub fn start_scan(&mut self) { + if let Some(scan) = &self.scan { + scan.cancel(); + } + self.tree = None; + self.arena = None; + self.scan_error = None; + self.scan_elapsed = None; + self.scan_started = Some(Instant::now()); + self.progress = ScanSnapshot::default(); + self.current.clear(); + self.selected = None; + self.matches = None; + self.search.clear(); + self.search_open = false; + self.insights.clear(); + self.scroll = 0; + self.list_scroll = 0; + self.reset_marquee(); + self.invalidate_view_cache(); + self.scan_view = view_options(&self.options); + // Measure hidden entries too so both views use the same walk and + // removing a visible directory accounts for its hidden contents. + let mut scan_options = self.options; + scan_options.include_hidden = true; + self.scan_view.2 = true; + self.scan = Some(ScanHandle::spawn(self.root.clone(), scan_options)); + } + + pub fn tick(&mut self) -> bool { + let mut changed = false; + if let Some(receiver) = &self.volume_scan { + match receiver.try_recv() { + Ok(volumes) => { + self.volumes = volumes; + self.volumes_loading = false; + self.volume_scan = None; + changed = true; + } + Err(TryRecvError::Disconnected) => { + self.volumes_loading = false; + self.volume_scan = None; + self.notice = Some("Could not list volumes".to_string()); + changed = true; + } + Err(TryRecvError::Empty) => {} + } + } + if let Some(scan) = &self.scan { + let snapshot = scan.progress.snapshot(); + if self.progress != snapshot { + self.progress = snapshot; + changed = true; + } + if let Some(outcome) = scan.poll_update() { + self.progress = scan.progress.snapshot(); + self.scan_elapsed = + self.scan_started.take().map(|start| start.elapsed()); + self.scan = None; + match outcome { + ScanUpdate::Live { arena, mut node } => { + if view_options(&self.options) != self.scan_view { + node = project(&arena, &self.options); + } + self.refresh_marks(&arena); + self.arena = Some(arena); + self.insights = + worth_a_look(&node, now_seconds(), INSIGHT_LIMIT); + self.scanned_at = now_seconds(); + self.selected = first_child(&node, &[]); + self.tree = Some(node); + self.invalidate_view_cache(); + self.keep_selection_visible(); + self.reset_marquee(); + } + ScanUpdate::Error(error) => { + self.scan_error = Some(error.to_string()); + } + _ => { + self.scan_error = + Some("Scan ended without a complete tree".into()); + } + } + changed = true; + } + } + if let Some(run) = &self.run { + let mut finished = false; + while let Some(event) = run.poll() { + changed = true; + match event { + RemovalEvent::Start { total } => { + self.run_summary.total = total; + } + RemovalEvent::Item { + path, + bytes, + outcome, + } => { + if outcome.is_ok() { + self.run_summary.removed += 1; + self.run_summary.bytes += bytes; + } else { + self.run_summary.failed += 1; + } + self.run_log.push((path, outcome)); + } + RemovalEvent::Done { + removed, + bytes, + failed, + } => { + self.run_summary.removed = removed; + self.run_summary.bytes = bytes; + self.run_summary.failed = failed; + finished = true; + } + } + } + if finished { + self.run = None; + self.marks.retain(|target| { + !self.run_log.iter().any(|(path, outcome)| { + outcome.is_ok() && target.path.starts_with(path) + }) + }); + let _ = self.refresh_space(); + self.measured_gain = self.baseline_space.zip(self.space).map( + |(before, after)| { + i128::from(after.available) + - i128::from(before.available) + }, + ); + self.screen = Screen::Done; + self.start_scan(); + } + } + if self.last_space_check.elapsed() >= Duration::from_millis(1200) { + changed |= self.refresh_space(); + } + if self + .animation_wake + .get() + .is_some_and(|deadline| Instant::now() >= deadline) + { + changed = true; + } + changed + } + + fn refresh_space(&mut self) -> bool { + let old = self.space; + self.space = space_info(&self.root).ok(); + self.last_space_check = Instant::now(); + self.space != old + } + + fn refresh_marks(&mut self, arena: &TreeArena) { + self.marks.retain_mut(|target| { + let Some(node) = arena_node_at(arena, &target.path) else { + return false; + }; + target.bytes = node.effective_allocated_bytes(); + target.is_dir = node.is_dir(); + target.hidden = node.hidden(); + true + }); + } + + pub fn current_node(&self) -> Option<&Node> { + self.tree.as_ref()?.resolve(&self.current) + } + + pub fn selected_node(&self) -> Option<&Node> { + self.tree.as_ref()?.resolve(self.selected.as_deref()?) + } + + pub fn selected_path(&self) -> Option { + Some(path_of( + &self.root, + self.tree.as_ref()?, + self.selected.as_deref()?, + PathStyle::Native, + )) + } + + pub fn current_path(&self) -> Option { + Some(path_of( + &self.root, + self.tree.as_ref()?, + &self.current, + PathStyle::Native, + )) + } + + pub fn plan(&self) -> Plan { + plan(&self.marks, &self.root) + } + + pub fn marked_bytes(&self) -> u64 { + self.plan().bytes() + } + + pub fn is_marked(&self, path: &Path) -> bool { + self.marks.iter().any(|target| target.path == path) + } + + pub fn marked_ancestor(&self, path: &Path) -> Option<&Path> { + self.marks + .iter() + .map(|target| target.path.as_path()) + .find(|marked| *marked != path && path.starts_with(marked)) + } + + pub fn set_viewport(&mut self, width: u16, height: u16) { + self.viewport = Rect::new(0, 0, width, height); + self.invalidate_view_cache(); + self.keep_selection_visible(); + self.reset_marquee(); + } + + #[cfg(test)] + pub(crate) const fn viewport(&self) -> Rect { + self.viewport + } + + pub(crate) fn marquee_elapsed(&self) -> Duration { + self.marquee_started.elapsed() + } + + pub(crate) fn focused_marquee_elapsed(&self) -> Duration { + self.focused_marquee_started.elapsed() + } + + #[cfg(test)] + pub(crate) fn set_marquee_elapsed_for_test(&mut self, elapsed: Duration) { + self.marquee_started = Instant::now() + .checked_sub(elapsed) + .expect("test animation elapsed fits in Instant"); + self.focused_marquee_started = self.marquee_started; + self.animation_wake.set(None); + } + + fn reset_marquee(&mut self) { + let now = Instant::now(); + self.marquee_started = now; + self.focused_marquee_started = now; + self.animation_wake.set(None); + } + + fn reset_focused_marquee(&mut self) { + self.focused_marquee_started = Instant::now(); + self.animation_wake.set(None); + } + + pub(crate) fn begin_animation_frame(&self) { + self.animation_wake.set(None); + } + + pub(crate) fn schedule_animation(&self, delay: Duration) { + let deadline = Instant::now() + delay; + if self.animation_wake.get().is_none_or(|next| deadline < next) { + self.animation_wake.set(Some(deadline)); + } + } + + fn invalidate_view_cache(&self) { + self.tiles_cache.borrow_mut().take(); + self.children_cache.borrow_mut().take(); + } + + pub(crate) fn header_height(&self, width: u16) -> u16 { + if width < 60 || (self.screen == Screen::Explore && self.list_view) { + 2 + } else { + 3 + } + } + + pub(crate) fn body_area(&self, size: Rect) -> Rect { + let head = self.header_height(size.width); + Rect::new( + size.x, + size.y + head, + size.width, + size.height.saturating_sub(head + 2), + ) + } + + pub(crate) fn split_explore(area: Rect) -> (Rect, Rect, bool) { + if area.width >= 105 && area.height >= 18 { + // The side panel keeps enough cells for typical disk names. + let side_width = area.width.min(40); + let map = + Rect::new(area.x, area.y, area.width - side_width, area.height); + let side = Rect::new(map.right(), area.y, side_width, area.height); + (map, side, true) + } else { + let detail_height = if area.height >= 16 { 5 } else { 3 }; + let map = Rect::new( + area.x, + area.y, + area.width, + area.height.saturating_sub(detail_height), + ); + let detail = + Rect::new(area.x, map.bottom(), area.width, detail_height); + (map, detail, false) + } + } + + pub(crate) const fn is_list(&self, map: Rect) -> bool { + self.list_view || map.height < 11 || map.width < 60 + } + + fn map_area(&self) -> Rect { + Self::split_explore(self.body_area(self.viewport)).0 + } + + pub(crate) fn tiles(&self, area: Rect) -> Rc> { + if let Some((cached_area, tiles)) = self.tiles_cache.borrow().as_ref() + && *cached_area == area + { + return Rc::clone(tiles); + } + let Some(node) = self.current_node() else { + return Rc::new(Vec::new()); + }; + let options = LayoutOptions { + max_depth: self.view_depth, + padding: 1.0, + padding_outer: 1.0, + min_tile: 2.0, + max_children: 72, + header: 6.0, + header_inner: 4.0, + // A compact mosaic still has room for a named parent band at + // twelve cells. The wider view keeps more space for labels. + min_header_width: if area.width >= 105 { 20.0 } else { 12.0 }, + }; + let tiles = Rc::new(layout_filtered( + node, + &self.current, + MapRect::new( + 0.0, + 0.0, + f32::from(area.width), + f32::from(area.height) * 2.0, + ), + self.options.metric, + &options, + self.matches.as_ref(), + )); + *self.tiles_cache.borrow_mut() = Some((area, Rc::clone(&tiles))); + tiles + } + + pub(crate) fn tile_rect(tile: &Tile, area: Rect) -> Rect { + let x = area.x + tile.rect.x.max(0.0) as u16; + let y = area.y + (tile.rect.y.max(0.0) / 2.0) as u16; + let width = tile.rect.w.max(0.0) as u16; + let height = (tile.rect.h.max(0.0) / 2.0).ceil() as u16; + Rect::new(x, y, width, height).intersection(area) + } + + pub fn handle_key(&mut self, key: KeyEvent) { + let selected = self.selected.clone(); + let current = self.current.clone(); + let root = self.root.clone(); + let screen = self.screen; + let depth = self.view_depth; + let list_view = self.list_view; + let insight_index = self.insight_index; + let volume_highlight = self.volume_highlight; + self.handle_key_inner(key); + if self.selected != selected + || self.current != current + || self.root != root + || self.screen != screen + || self.view_depth != depth + || self.list_view != list_view + || self.insight_index != insight_index + || self.volume_highlight != volume_highlight + { + self.reset_focused_marquee(); + } + } + + fn handle_key_inner(&mut self, key: KeyEvent) { + if key.modifiers.contains(KeyModifiers::CONTROL) + && key.code == KeyCode::Char('c') + { + if self.screen == Screen::Running { + self.cancel_removal(); + } else { + self.quit = true; + } + return; + } + self.notice = None; + match self.screen { + Screen::Explore => self.on_explore_key(key), + Screen::Review => self.on_review_key(key), + Screen::Confirm => self.on_confirm_key(key), + Screen::Running => { + if key.code == KeyCode::Esc { + self.cancel_removal(); + } + } + Screen::Done => { + if matches!(key.code, KeyCode::Enter | KeyCode::Esc) { + self.screen = Screen::Explore; + } + } + Screen::Help => { + self.screen = Screen::Explore; + } + Screen::Insights => self.on_insights_key(key), + Screen::SavePrompt => self.on_save_key(key), + Screen::Volumes => self.on_volumes_key(key), + } + } + + fn on_explore_key(&mut self, key: KeyEvent) { + if self.search_open { + match key.code { + KeyCode::Esc => { + self.search_open = false; + self.search.clear(); + self.matches = None; + self.invalidate_view_cache(); + } + KeyCode::Enter => { + self.search_open = false; + self.apply_search(); + } + KeyCode::Backspace => { + self.search.pop(); + } + KeyCode::Char(ch) + if !key.modifiers.contains(KeyModifiers::CONTROL) => + { + self.search.push(ch); + } + _ => {} + } + return; + } + match key.code { + KeyCode::Char('q') => self.quit = true, + KeyCode::Char('?') => self.screen = Screen::Help, + KeyCode::Char('/') => { + self.search_open = true; + self.search.clear(); + self.matches = None; + self.invalidate_view_cache(); + } + KeyCode::Char('r') => self.start_scan(), + KeyCode::Char('[' | '-') => { + self.view_depth = self.view_depth.saturating_sub(1).max(1); + self.invalidate_view_cache(); + } + KeyCode::Char(']' | '+') => { + self.view_depth = (self.view_depth + 1).min(6); + self.invalidate_view_cache(); + } + KeyCode::Esc if self.scan.is_some() => { + if let Some(scan) = self.scan.take() { + scan.cancel(); + self.progress = scan.progress.snapshot(); + self.scan_elapsed = + self.scan_started.take().map(|start| start.elapsed()); + self.notice = Some("Scan stopped".to_string()); + } + } + KeyCode::Esc if self.matches.is_some() => { + self.matches = None; + self.search.clear(); + self.invalidate_view_cache(); + } + KeyCode::Esc | KeyCode::Backspace => self.ascend(), + KeyCode::Enter => self.descend(), + KeyCode::Left | KeyCode::Char('h') => { + self.move_direction(Direction::Left); + } + KeyCode::Right | KeyCode::Char('l') => { + self.move_direction(Direction::Right); + } + KeyCode::Down | KeyCode::Char('j') => { + self.move_direction(Direction::Down); + } + KeyCode::Up | KeyCode::Char('k') => { + self.move_direction(Direction::Up); + } + KeyCode::Tab => self.move_selection(1), + KeyCode::BackTab => self.move_selection(-1), + KeyCode::Char(' ' | 'x') => self.toggle_mark(), + KeyCode::Char('c') if !self.marks.is_empty() => { + self.scroll = 0; + self.screen = Screen::Review; + } + KeyCode::Char('c') => { + self.notice = Some("Mark a path with Space first".to_string()); + } + KeyCode::Char('w') => { + self.insight_index = 0; + self.screen = Screen::Insights; + } + KeyCode::Char('V') => self.open_volumes(), + KeyCode::Char('g') => self.go_to_disk(), + KeyCode::Char('v') => { + let map = self.map_area(); + if map.width < 60 || map.height < 11 { + self.notice = Some( + "This size uses the list; widen for the map" + .to_string(), + ); + } else { + self.list_view = !self.list_view; + self.keep_list_selection_visible(); + } + } + KeyCode::Char('t') => self.cycle_mode(), + KeyCode::Char('d') => { + self.options.apparent_size = !self.options.apparent_size; + self.reproject(); + } + KeyCode::Char('i') => { + self.options.include_hidden = !self.options.include_hidden; + self.reproject(); + } + _ => {} + } + self.keep_selection_visible(); + } + + fn on_review_key(&mut self, key: KeyEvent) { + match key.code { + KeyCode::Esc => self.screen = Screen::Explore, + KeyCode::Up | KeyCode::Char('k') => { + self.scroll = self.scroll.saturating_sub(1); + } + KeyCode::Down | KeyCode::Char('j') => { + self.scroll = self.scroll.saturating_add(1); + } + KeyCode::Char('m') => { + if self.trash_backend.is_available() { + self.removal_mode = RemovalMode::Trash; + } else { + self.notice = Some("Trash unavailable here".to_string()); + } + } + KeyCode::Char('p') => self.removal_mode = RemovalMode::Permanent, + KeyCode::Char('!') => { + self.marks.clear(); + self.screen = Screen::Explore; + } + KeyCode::Char('a') => self.handoff_to_stdout(), + KeyCode::Char('s') => { + if self.plan().is_empty() { + self.notice = + Some("No removable paths to save".to_string()); + } else { + self.save_path.clear(); + self.screen = Screen::SavePrompt; + } + } + KeyCode::Enter if !self.plan().is_empty() => { + if self.removal_mode == RemovalMode::Permanent { + self.screen = Screen::Confirm; + } else { + self.begin_removal(); + } + } + _ => {} + } + } + + fn on_confirm_key(&mut self, key: KeyEvent) { + match key.code { + KeyCode::Esc | KeyCode::Char('n') => self.screen = Screen::Review, + KeyCode::Char('y') => self.begin_removal(), + _ => {} + } + } + + fn on_insights_key(&mut self, key: KeyEvent) { + match key.code { + KeyCode::Esc | KeyCode::Char('w') => { + self.screen = Screen::Explore; + } + KeyCode::Down | KeyCode::Char('j') => { + if !self.insights.is_empty() { + self.insight_index = + (self.insight_index + 1) % self.insights.len(); + } + } + KeyCode::Up | KeyCode::Char('k') => { + if !self.insights.is_empty() { + self.insight_index = self + .insight_index + .checked_sub(1) + .unwrap_or(self.insights.len() - 1); + } + } + KeyCode::Enter => { + if let Some(crumbs) = self + .insights + .get(self.insight_index) + .map(|candidate| candidate.crumbs.clone()) + { + self.current = + crumbs[..crumbs.len().saturating_sub(1)].to_vec(); + self.selected = Some(crumbs); + self.matches = None; + self.screen = Screen::Explore; + self.invalidate_view_cache(); + } + } + _ => {} + } + } + + fn on_save_key(&mut self, key: KeyEvent) { + match key.code { + KeyCode::Esc => self.screen = Screen::Review, + KeyCode::Backspace => { + self.save_path.pop(); + } + KeyCode::Char(ch) + if !key.modifiers.contains(KeyModifiers::CONTROL) => + { + self.save_path.push(ch); + } + KeyCode::Enter => { + let path = if self.save_path.is_empty() { + PathBuf::from("disktree-agent-prompt.txt") + } else { + PathBuf::from(&self.save_path) + }; + let prompt = self.agent_prompt(); + let outcome = OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .and_then(|mut file| file.write_all(prompt.as_bytes())); + self.notice = Some(match outcome { + Ok(()) => { + format!("Agent prompt saved to {}", path.display()) + } + Err(error) => { + format!("Could not save {}: {error}", path.display()) + } + }); + self.screen = Screen::Review; + } + _ => {} + } + } + + fn apply_search(&mut self) { + let Some(node) = self.current_node() else { + return; + }; + self.matches = filter(node, &self.current, &self.search); + self.invalidate_view_cache(); + self.selected = self.visible_children().get(0).map(|index| { + let mut crumbs = self.current.clone(); + crumbs.push(index); + crumbs + }); + self.list_scroll = 0; + self.keep_selection_visible(); + if self.selected.is_none() { + self.notice = Some(format!("No matches for {}", self.search)); + } + } + + pub(crate) fn visible_children(&self) -> VisibleChildren { + let Some(node) = self.current_node() else { + return VisibleChildren::All(0); + }; + let Some(matches) = self.matches.as_ref() else { + return VisibleChildren::All(node.children.len()); + }; + if let Some(indices) = self.children_cache.borrow().as_ref() { + return VisibleChildren::Filtered(Rc::clone(indices)); + } + // The core filter has already recorded every kept ancestor. Read + // its direct children instead of walking a huge directory again. + let base_len = self.current.len(); + let mut indices: Vec = matches + .keep + .keys() + .filter_map(|crumbs| { + (crumbs.len() == base_len + 1 + && crumbs.starts_with(&self.current)) + .then_some(crumbs[base_len]) + }) + .collect(); + indices.sort_unstable(); + let indices = Rc::new(indices); + *self.children_cache.borrow_mut() = Some(Rc::clone(&indices)); + VisibleChildren::Filtered(indices) + } + + fn visible_map_nodes(&self, area: Rect) -> Vec<(Vec, Rect)> { + self.tiles(area) + .iter() + .filter_map(|tile| { + let TileKind::Node { crumbs } = &tile.kind else { + return None; + }; + let rect = Self::tile_rect(tile, area); + (rect.width > 0 && rect.height > 0) + .then(|| (crumbs.clone(), rect)) + }) + .collect() + } + + fn keep_list_selection_visible(&mut self) { + let map = self.map_area(); + if !self.is_list(map) { + return; + } + let visible = self.visible_children(); + let capacity = usize::from(map.height.saturating_sub(1)).max(1); + self.list_scroll = + self.list_scroll.min(visible.len().saturating_sub(capacity)); + let Some(position) = self.selected.as_ref().and_then(|crumbs| { + crumbs + .get(self.current.len()) + .and_then(|index| visible.position(*index)) + }) else { + return; + }; + if position < self.list_scroll { + self.list_scroll = position; + } else if position >= self.list_scroll + capacity { + self.list_scroll = position + 1 - capacity; + } + } + + fn keep_selection_visible(&mut self) { + let map = self.map_area(); + if self.is_list(map) { + let visible = self.visible_children(); + let selected = self.selected.as_ref().and_then(|crumbs| { + let index = *crumbs.get(self.current.len())?; + visible.position(index).map(|_| { + let mut direct = self.current.clone(); + direct.push(index); + direct + }) + }); + self.selected = selected.or_else(|| { + visible.get(0).map(|index| { + let mut direct = self.current.clone(); + direct.push(index); + direct + }) + }); + self.keep_list_selection_visible(); + return; + } + let visible = self.visible_map_nodes(map); + if !visible + .iter() + .any(|(crumbs, _)| self.selected.as_ref() == Some(crumbs)) + { + self.selected = visible.first().map(|(crumbs, _)| crumbs.clone()); + } + } + + fn move_selection(&mut self, step: isize) { + let map = self.map_area(); + if !self.is_list(map) { + let visible = self.visible_map_nodes(map); + if visible.is_empty() { + return; + } + let current = self.selected.as_ref().and_then(|selected| { + visible.iter().position(|(crumbs, _)| crumbs == selected) + }); + let depth = current + .map_or(self.current.len() + 1, |index| visible[index].0.len()); + let peers: Vec<&Vec> = visible + .iter() + .filter(|(crumbs, _)| crumbs.len() == depth) + .map(|(crumbs, _)| crumbs) + .collect(); + if peers.is_empty() { + return; + } + let position = current + .and_then(|index| { + peers.iter().position(|crumbs| **crumbs == visible[index].0) + }) + .map_or(0, |position| { + (position.cast_signed() + step) + .rem_euclid(peers.len().cast_signed()) + as usize + }); + self.selected = Some(peers[position].clone()); + return; + } + let visible = self.visible_children(); + if visible.is_empty() { + return; + } + let current = self.selected.as_ref().and_then(|crumbs| { + crumbs + .starts_with(&self.current) + .then(|| crumbs.get(self.current.len()).copied()) + .flatten() + }); + let position = current + .and_then(|index| visible.position(index)) + .map_or(0, |position| { + (position.cast_signed() + step) + .rem_euclid(visible.len().cast_signed()) + as usize + }); + let mut crumbs = self.current.clone(); + crumbs.push(visible.get(position).expect("visible position in range")); + self.selected = Some(crumbs); + self.keep_list_selection_visible(); + } + + fn move_direction(&mut self, direction: Direction) { + let map = self.map_area(); + if self.is_list(map) { + self.move_selection( + if matches!(direction, Direction::Left | Direction::Up) { + -1 + } else { + 1 + }, + ); + return; + } + let visible = self.visible_map_nodes(map); + let Some((from_crumbs, from_rect)) = + self.selected.as_ref().and_then(|selected| { + visible.iter().find(|(crumbs, _)| crumbs == selected) + }) + else { + self.selected = visible.first().map(|(crumbs, _)| crumbs.clone()); + return; + }; + let mut best: Option<(f32, Vec)> = None; + for (crumbs, rect) in &visible { + if crumbs.len() != from_crumbs.len() || crumbs == from_crumbs { + continue; + } + let Some(gap) = direction.gap(*from_rect, *rect) else { + continue; + }; + let score = direction.offset(*from_rect, *rect).mul_add(2.5, gap); + if best + .as_ref() + .is_none_or(|(score_best, _)| score < *score_best) + { + best = Some((score, crumbs.clone())); + } + } + if let Some((_, crumbs)) = best { + self.selected = Some(crumbs); + } else if matches!(direction, Direction::Left | Direction::Up) + && from_crumbs.len() > self.current.len() + 1 + { + let parent = &from_crumbs[..from_crumbs.len() - 1]; + if visible.iter().any(|(crumbs, _)| crumbs == parent) { + self.selected = Some(parent.to_vec()); + } + } + } + + fn descend(&mut self) { + if self.tree.is_none() { + self.notice = Some("Wait for the scan to finish".to_string()); + return; + } + let Some(crumbs) = self.selected.clone() else { + self.notice = Some("Select a directory to open".to_string()); + return; + }; + let Some(node) = + self.tree.as_ref().and_then(|tree| tree.resolve(&crumbs)) + else { + self.notice = + Some("Selection is no longer in the scan".to_string()); + return; + }; + if !node.is_dir() { + self.notice = Some("File selected; Space marks it".to_string()); + return; + } + if node.children.is_empty() { + self.notice = Some("Directory is empty".to_string()); + return; + } + self.current = crumbs; + self.selected = first_child(node, &self.current); + self.matches = None; + self.invalidate_view_cache(); + self.search.clear(); + self.scroll = 0; + self.list_scroll = 0; + self.keep_selection_visible(); + } + + fn ascend(&mut self) { + if self.current.is_empty() { + if volume_root_for(&self.root) + .is_some_and(|volume| same_path(&volume, &self.root)) + { + self.notice = Some( + "At the volume root; press V to choose a volume" + .to_string(), + ); + } else if let Some(parent) = + self.root.parent().map(Path::to_path_buf) + { + self.set_root(&parent); + } + return; + } + let old = self.current.clone(); + self.current.pop(); + self.selected = Some(old); + self.matches = None; + self.invalidate_view_cache(); + self.search.clear(); + self.scroll = 0; + self.list_scroll = 0; + self.keep_selection_visible(); + } + + fn set_root(&mut self, root: &Path) { + let Ok(root) = canonicalize_path(root) else { + self.notice = Some(format!("Cannot access {}", root.display())); + return; + }; + if !root.is_dir() { + self.notice = + Some(format!("{} is not a directory", root.display())); + return; + } + self.screen = Screen::Explore; + if same_path(&root, &self.root) { + self.current.clear(); + self.selected = + self.tree.as_ref().and_then(|tree| first_child(tree, &[])); + self.invalidate_view_cache(); + return; + } + let before = self.marks.len(); + self.marks.retain(|mark| mark.path.starts_with(&root)); + self.root = root; + self.space = space_info(&self.root).ok(); + self.device = device_for(&self.root); + self.start_scan(); + if self.marks.len() < before { + self.notice = + Some("Marks outside this scan were cleared".to_string()); + } + } + + fn go_to_disk(&mut self) { + if let Some(root) = volume_root_for(&self.root) { + self.set_root(&root); + } else { + self.notice = Some("Cannot find this volume's root".to_string()); + } + } + + fn open_volumes(&mut self) { + let root = self.root.clone(); + let (sender, receiver) = mpsc::channel(); + std::thread::spawn(move || { + let _ = sender.send(volume_choices(&root)); + }); + self.volumes.clear(); + self.volume_highlight = 0; + self.volumes_loading = true; + self.volume_scan = Some(receiver); + self.screen = Screen::Volumes; + } + + fn on_volumes_key(&mut self, key: KeyEvent) { + match key.code { + KeyCode::Esc => { + self.volume_scan = None; + self.volumes_loading = false; + self.screen = Screen::Explore; + } + KeyCode::Up | KeyCode::Char('k') if !self.volumes.is_empty() => { + self.volume_highlight = self + .volume_highlight + .checked_sub(1) + .unwrap_or(self.volumes.len() - 1); + } + KeyCode::Down | KeyCode::Char('j') if !self.volumes.is_empty() => { + self.volume_highlight = + (self.volume_highlight + 1) % self.volumes.len(); + } + KeyCode::Enter if self.volumes_loading => { + self.notice = Some("Still looking for volumes".to_string()); + } + KeyCode::Enter => { + let point = self + .volumes + .get(self.volume_highlight) + .map(|volume| volume.point.clone()); + if let Some(point) = point { + self.volume_scan = None; + self.volumes.clear(); + self.set_root(&point); + } else { + self.notice = Some("No readable volumes found".to_string()); + } + } + _ => {} + } + } + + fn toggle_mark(&mut self) { + let Some(node) = self.selected_node() else { + return; + }; + let Some(path) = self.selected_path() else { + return; + }; + if path == self.root { + self.notice = Some("The scanned root cannot be marked".to_string()); + return; + } + if let Some(index) = + self.marks.iter().position(|item| item.path == path) + { + self.marks.remove(index); + self.notice = Some(format!("Unmarked {}", path.display())); + return; + } + if let Some(ancestor) = self.marked_ancestor(&path) { + self.notice = + Some(format!("Already covered by {}", ancestor.display())); + return; + } + let entry = self + .arena + .as_ref() + .and_then(|arena| arena_node_at(arena, &path)); + let target = Target { + // Reclaim is allocated space even when the display shows lengths. + bytes: entry + .map_or(node.bytes, ArenaNode::effective_allocated_bytes), + is_dir: node.is_dir(), + hidden: entry.is_some_and(ArenaNode::hidden), + path: path.clone(), + }; + self.marks.retain(|item| !item.path.starts_with(&path)); + self.marks.push(target); + self.notice = Some(format!("Marked {}", path.display())); + } + + fn cycle_mode(&mut self) { + self.mode = self.mode.next(); + let metric = self.mode.metric(); + if self.options.metric != metric { + self.options.metric = metric; + self.reproject(); + } + } + + fn reproject(&mut self) { + let Some(arena) = self.arena.as_ref() else { + return; + }; + // Crumbs change when sibling order changes. Restore by path. + let directory = self.current_path(); + let selected = self.selected_path(); + self.tree = None; + self.tree = Some(project(arena, &self.options)); + self.refresh_view_after_change(directory, selected); + } + + fn refresh_view_after_change( + &mut self, + directory: Option, + selected: Option, + ) { + let Some(tree) = self.tree.as_ref() else { + return; + }; + self.current = directory + .and_then(|path| crumbs_for_path(&self.root, tree, &path)) + .unwrap_or_default(); + self.selected = selected + .and_then(|path| crumbs_for_path(&self.root, tree, &path)) + .or_else(|| { + tree.resolve(&self.current) + .and_then(|node| first_child(node, &self.current)) + }); + self.insights = worth_a_look(tree, now_seconds(), INSIGHT_LIMIT); + self.matches = None; + self.search.clear(); + self.search_open = false; + self.scroll = 0; + self.list_scroll = 0; + self.invalidate_view_cache(); + self.keep_selection_visible(); + } + + fn begin_removal(&mut self) { + let plan = self.plan(); + if plan.is_empty() { + self.notice = Some("No removable paths in the plan".to_string()); + self.screen = Screen::Review; + return; + } + self.baseline_space = self.space; + self.run_cancelled = false; + self.run_summary = RunSummary { + total: plan.targets.len(), + ..RunSummary::default() + }; + self.run_log.clear(); + self.run = Some(disktree_core::removal::spawn(plan, self.removal_mode)); + self.screen = Screen::Running; + } + + fn cancel_removal(&mut self) { + if let Some(run) = &self.run { + run.cancel(); + self.run_cancelled = true; + self.notice = Some("Stopping after the current path".to_string()); + } + } + + pub fn agent_prompt(&self) -> String { + let plan = self.plan(); + disktree_core::export::agent_prompt( + &plan.targets, + &self.root, + self.space, + ) + } + + fn handoff_to_stdout(&mut self) { + if self.plan().is_empty() { + self.notice = Some("No removable paths to hand off".to_string()); + return; + } + self.stdout_prompt = Some(self.agent_prompt()); + self.quit = true; + } +} + +fn first_child(node: &Node, base: &[usize]) -> Option> { + (!node.children.is_empty()).then(|| { + let mut crumbs = base.to_vec(); + crumbs.push(0); + crumbs + }) +} + +const fn view_options(options: &ScanOptions) -> (Metric, bool, bool) { + ( + options.metric, + options.apparent_size, + options.include_hidden, + ) +} + +fn project(arena: &TreeArena, options: &ScanOptions) -> Node { + arena_to_node( + arena, + options.apparent_size, + options.include_hidden, + options.dedup_hardlinks, + options.metric, + ) +} + +fn arena_node_at<'a>( + arena: &'a TreeArena, + path: &Path, +) -> Option<&'a ArenaNode> { + let root = arena.root_path(); + // Scanner canonicalization can add a verbatim prefix on Windows. + #[cfg(windows)] + let root = dunce::simplified(root); + let relative = path.strip_prefix(root).ok()?; + let parts = relative + .components() + .map(|part| part.as_os_str().to_string_lossy()); + let names: Vec<_> = parts.collect(); + let id = arena.find_relative(names.iter().map(AsRef::as_ref))?; + Some(arena.node(id)) +} + +fn crumbs_for_path( + root_path: &Path, + root: &Node, + path: &Path, +) -> Option> { + let relative = path.strip_prefix(root_path).ok()?; + let mut node = root; + let mut crumbs = Vec::new(); + for component in relative.components() { + let name = component.as_os_str().to_string_lossy(); + let index = node + .children + .iter() + .position(|child| child.name.as_ref() == name)?; + crumbs.push(index); + node = node.child(index)?; + } + Some(crumbs) +} + +fn now_seconds() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .ok() + .and_then(|duration| i64::try_from(duration.as_secs()).ok()) + .unwrap_or_default() +} + +fn same_path(left: &Path, right: &Path) -> bool { + left == right + || canonicalize_path(left) + .ok() + .zip(canonicalize_path(right).ok()) + .is_some_and(|(left, right)| left == right) +} + +pub fn canonicalize_path(path: &Path) -> io::Result { + #[cfg(windows)] + { + dunce::canonicalize(path) + } + #[cfg(not(windows))] + { + path.canonicalize() + } +} + +fn volume_choices(root: &Path) -> Vec { + let mut found = volumes(); + if let Some(current) = volume_root_for(root) + && !found + .iter() + .any(|volume| same_path(&volume.point, ¤t)) + { + found.push(Volume { + point: current.clone(), + device: device_for(¤t), + space: space_info(¤t).ok(), + }); + } + found.retain(|volume| !same_path(&volume.point, root)); + found +} + +#[cfg(test)] +mod tests { + use super::*; + use disktree_core::classify::Reclaim; + use disktree_core::insights::Finding; + use disktree_core::scan::scan; + use disktree_core::tree::Metric; + use ratatui::Terminal; + use ratatui::backend::TestBackend; + + fn fixture_dir() -> tempfile::TempDir { + // macOS keeps its default temporary directory under `/private`, + // which the removal guard correctly treats as system-owned. + #[cfg(target_os = "macos")] + { + let home = std::env::home_dir().expect("home directory"); + tempfile::Builder::new() + .prefix("disktree-tui-") + .tempdir_in(home) + .expect("tempdir in home") + } + #[cfg(not(target_os = "macos"))] + { + tempfile::tempdir().expect("tempdir") + } + } + + fn scanned_app(root: &Path, options: ScanOptions) -> App { + let mut app = App::new(root.to_path_buf(), options); + let deadline = Instant::now() + Duration::from_secs(5); + while app.scan.is_some() && Instant::now() < deadline { + app.tick(); + std::thread::sleep(Duration::from_millis(5)); + } + assert!(app.tree.is_some(), "scan failed: {:?}", app.scan_error); + app + } + + #[test] + fn marks_use_bytes_and_absorb_children() { + let temp = fixture_dir(); + let root = temp.path(); + std::fs::create_dir(root.join("cache")).expect("mkdir"); + std::fs::write(root.join("cache/file"), vec![b'x'; 1000]) + .expect("write"); + let options = ScanOptions { + apparent_size: true, + metric: Metric::Files, + ..ScanOptions::default() + }; + let tree = scan(root, options).expect("scan"); + let mut app = App::new(root.to_path_buf(), options); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.tree = Some(tree); + app.selected = Some(vec![0, 0]); + app.toggle_mark(); + app.selected = Some(vec![0]); + app.toggle_mark(); + assert_eq!(app.marks.len(), 1); + assert_eq!(app.marks[0].bytes, 1000); + assert_eq!(app.plan().bytes(), 1000); + } + + #[test] + fn metric_switch_reorders_without_rescan_and_keeps_paths() { + let temp = fixture_dir(); + let root = temp.path(); + std::fs::create_dir(root.join("large")).expect("large dir"); + std::fs::create_dir(root.join("many")).expect("many dir"); + std::fs::write(root.join("large/blob"), vec![b'x'; 10_000]) + .expect("large file"); + for index in 0..3 { + std::fs::write(root.join("many").join(index.to_string()), b"x") + .expect("small file"); + } + let options = ScanOptions { + apparent_size: true, + ..ScanOptions::default() + }; + let mut app = scanned_app(root, options); + let tree = app.tree.as_ref().expect("tree"); + app.current = + crumbs_for_path(root, tree, &root.join("large")).expect("large"); + app.selected = crumbs_for_path(root, tree, &root.join("large/blob")); + app.toggle_mark(); + let marked_bytes = app.marked_bytes(); + + app.handle_key(KeyEvent::new(KeyCode::Char('t'), KeyModifiers::NONE)); + assert_eq!(app.options.metric, Metric::Files); + assert!(app.scan.is_none(), "metric switch should reuse the tree"); + assert_eq!( + app.current_path().as_deref(), + Some(root.join("large").as_path()) + ); + assert_eq!( + app.selected_path().as_deref(), + Some(root.join("large/blob").as_path()) + ); + assert_eq!(app.marked_bytes(), marked_bytes); + assert_eq!( + app.tree.as_ref().expect("tree").children[0].name.as_ref(), + "many" + ); + + app.handle_key(KeyEvent::new(KeyCode::Char('t'), KeyModifiers::NONE)); + assert_eq!(app.mode, ViewMode::Age); + assert_eq!(app.options.metric, Metric::Bytes); + assert!(app.scan.is_none(), "age mode should reuse the tree"); + assert_eq!( + app.tree.as_ref().expect("tree").children[0].name.as_ref(), + "large" + ); + assert_eq!( + app.selected_path().as_deref(), + Some(root.join("large/blob").as_path()) + ); + app.handle_key(KeyEvent::new(KeyCode::Char('t'), KeyModifiers::NONE)); + assert_eq!(app.mode, ViewMode::Size); + assert!(app.scan.is_none()); + assert_eq!(app.marked_bytes(), marked_bytes); + } + + #[test] + fn apparent_toggle_reuses_scan_and_keeps_allocated_reclaim() { + let temp = fixture_dir(); + let root = temp.path(); + let file = root.join("sparse"); + std::fs::File::create(&file) + .expect("create") + .set_len(1024 * 1024) + .expect("sparse length"); + let options = ScanOptions { + apparent_size: true, + ..ScanOptions::default() + }; + let mut app = scanned_app(root, options); + // The list can select a sparse file even when it has no tile. + app.set_viewport(45, 13); + app.selected = + crumbs_for_path(root, app.tree.as_ref().expect("tree"), &file); + app.toggle_mark(); + let allocated = scan(root, ScanOptions::default()).expect("scan").bytes; + assert_eq!(app.marked_bytes(), allocated); + assert_eq!( + app.selected_node().expect("selected file").bytes, + 1024 * 1024 + ); + app.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); + assert!(app.scan.is_none()); + assert_eq!( + app.selected_node().expect("selected file").bytes, + allocated + ); + assert_eq!(app.marked_bytes(), allocated); + assert_eq!(app.selected_path().as_deref(), Some(file.as_path())); + app.handle_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE)); + assert!(app.scan.is_none()); + assert_eq!(app.marked_bytes(), allocated); + } + + #[test] + fn hidden_toggle_reuses_full_scan_and_restores_paths() { + let temp = fixture_dir(); + let root = temp.path(); + std::fs::create_dir(root.join(".private")).expect("hidden dir"); + std::fs::write(root.join(".private/secret"), b"secret") + .expect("hidden file"); + std::fs::write(root.join("visible"), b"visible").expect("visible file"); + let mut app = scanned_app(root, ScanOptions::default()); + let full_bytes = app.tree.as_ref().expect("tree").bytes; + app.selected = crumbs_for_path( + root, + app.tree.as_ref().expect("tree"), + &root.join(".private"), + ); + app.toggle_mark(); + let marked_path = app.marks[0].path.clone(); + app.handle_key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE)); + assert!(app.scan.is_none()); + assert!(app.tree.as_ref().expect("tree").bytes < full_bytes); + assert!(app.selected_path().is_some()); + assert_eq!(app.marks[0].path, marked_path); + app.handle_key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE)); + assert!(app.scan.is_none()); + assert_eq!(app.tree.as_ref().expect("tree").bytes, full_bytes); + assert_eq!(app.marks[0].path, marked_path); + assert!( + app.tree + .as_ref() + .expect("tree") + .child_named(".private") + .is_some() + ); + } + + #[test] + fn first_hidden_enable_reuses_scan() { + let temp = fixture_dir(); + std::fs::write(temp.path().join(".private"), b"secret") + .expect("hidden file"); + let options = ScanOptions { + include_hidden: false, + ..ScanOptions::default() + }; + let mut app = scanned_app(temp.path(), options); + assert!(app.tree.as_ref().expect("tree").children.is_empty()); + app.handle_key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE)); + assert!(app.scan.is_none()); + assert!( + app.tree + .as_ref() + .expect("tree") + .child_named(".private") + .is_some() + ); + } + + #[test] + fn agent_handoff_contains_only_accepted_marks() { + let temp = fixture_dir(); + let root = temp.path().join("scan"); + std::fs::create_dir(&root).expect("mkdir"); + std::fs::write(root.join("keep.txt"), b"data").expect("write"); + let mut app = App::new(root.clone(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.marks = vec![ + Target { + path: root.join("keep.txt"), + bytes: 4, + is_dir: false, + hidden: false, + }, + Target { + path: temp.path().join("outside"), + bytes: 100, + is_dir: false, + hidden: false, + }, + ]; + app.screen = Screen::Review; + app.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)); + assert!(app.quit); + let prompt = app.stdout_prompt.expect("agent prompt"); + assert!(prompt.contains("keep.txt")); + assert!(!prompt.contains("outside")); + } + + #[test] + fn filtering_keeps_selection_within_matching_children() { + let temp = fixture_dir(); + std::fs::write(temp.path().join("alpha"), b"a").expect("write"); + std::fs::write(temp.path().join("beta"), b"b").expect("write"); + let tree = scan(temp.path(), ScanOptions::default()).expect("scan"); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.tree = Some(tree); + app.search = "alpha".to_string(); + app.apply_search(); + let original = app.selected.clone(); + assert!(original.is_some()); + let first = app.visible_children(); + let second = app.visible_children(); + assert!(matches!( + (&first, &second), + (VisibleChildren::Filtered(left), VisibleChildren::Filtered(right)) + if Rc::ptr_eq(left, right) + )); + app.move_selection(1); + assert_eq!(app.selected, original); + app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + assert!(matches!(app.visible_children(), VisibleChildren::All(2))); + } + + #[test] + fn tile_layout_is_reused_until_a_layout_input_changes() { + let temp = fixture_dir(); + std::fs::create_dir(temp.path().join("Projects")).expect("mkdir"); + std::fs::write(temp.path().join("Projects/file"), b"data") + .expect("write"); + std::fs::write(temp.path().join("Downloads"), b"more").expect("write"); + let tree = scan(temp.path(), ScanOptions::default()).expect("scan"); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.tree = Some(tree); + app.set_viewport(120, 35); + let map = app.map_area(); + let first = app.tiles(map); + assert!(Rc::ptr_eq(&first, &app.tiles(map))); + let selected = app.selected.clone(); + app.handle_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)); + assert_ne!(selected, app.selected); + assert!(Rc::ptr_eq(&first, &app.tiles(map))); + app.handle_key(KeyEvent::new(KeyCode::Char(']'), KeyModifiers::NONE)); + let changed = app.tiles(map); + assert!(!Rc::ptr_eq(&first, &changed)); + assert!(Rc::ptr_eq(&changed, &app.tiles(map))); + } + + #[test] + fn filtered_rows_include_ancestors_of_nested_name_matches() { + let temp = fixture_dir(); + let nested = temp.path().join("Projects/Mozilla/profile"); + std::fs::create_dir_all(nested.parent().expect("parent")) + .expect("mkdir"); + std::fs::write(nested, b"data").expect("write"); + std::fs::write(temp.path().join("unrelated"), b"data").expect("write"); + let tree = scan(temp.path(), ScanOptions::default()).expect("scan"); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.tree = Some(tree); + app.search = "Mozilla".to_string(); + app.apply_search(); + let visible = app.visible_children(); + assert_eq!(visible.len(), 1); + let index = visible.get(0).expect("matching ancestor"); + assert_eq!( + app.current_node().expect("root").children[index] + .name + .as_ref(), + "Projects" + ); + } + + #[test] + fn a_search_can_reach_a_nested_empty_directory() { + let temp = fixture_dir(); + let parent = temp.path().join("Projects"); + let empty = parent.join("empty-match"); + std::fs::create_dir_all(&empty).expect("mkdir"); + let tree = scan(temp.path(), ScanOptions::default()).expect("scan"); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.tree = Some(tree); + app.set_viewport(45, 13); + app.search = "empty-match".to_string(); + app.apply_search(); + assert_eq!(app.visible_children().len(), 1); + assert_eq!(app.selected_path().as_deref(), Some(parent.as_path())); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(app.selected_path().as_deref(), Some(empty.as_path())); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(app.notice.as_deref(), Some("Directory is empty")); + } + + #[test] + fn depth_keys_follow_the_gui_range() { + let temp = fixture_dir(); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + for _ in 0..8 { + app.handle_key(KeyEvent::new( + KeyCode::Char('['), + KeyModifiers::NONE, + )); + } + assert_eq!(app.view_depth, 1); + for _ in 0..8 { + app.handle_key(KeyEvent::new( + KeyCode::Char(']'), + KeyModifiers::NONE, + )); + } + assert_eq!(app.view_depth, 6); + app.handle_key(KeyEvent::new(KeyCode::Char('-'), KeyModifiers::NONE)); + assert_eq!(app.view_depth, 5); + app.handle_key(KeyEvent::new(KeyCode::Char('+'), KeyModifiers::NONE)); + assert_eq!(app.view_depth, 6); + } + + #[test] + fn mosaic_navigation_only_selects_drawn_tiles() { + let temp = fixture_dir(); + for index in 0..100 { + std::fs::write( + temp.path().join(format!("item_{index:03}")), + vec![b'x'; 4096], + ) + .expect("write"); + } + let tree = scan(temp.path(), ScanOptions::default()).expect("scan"); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.tree = Some(tree); + app.selected = Some(vec![0]); + app.set_viewport(80, 24); + let drawn = app.visible_map_nodes(app.map_area()); + assert!(!drawn.is_empty()); + assert!(drawn.len() < 100); + + for _ in 0..100 { + app.handle_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)); + assert!( + drawn.iter().any(|(crumbs, _)| { + app.selected.as_ref() == Some(crumbs) + }) + ); + } + + let (from, from_rect) = drawn + .iter() + .find(|(crumbs, rect)| { + drawn.iter().any(|(other, target)| { + other != crumbs + && Direction::Right.gap(*rect, *target).is_some() + }) + }) + .expect("horizontal neighbours"); + app.selected = Some(from.clone()); + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + let selected = app.selected.as_ref().expect("selected"); + let target = drawn + .iter() + .find(|(crumbs, _)| crumbs == selected) + .expect("drawn target"); + assert!(Direction::Right.gap(*from_rect, target.1).is_some()); + assert!(app.current.is_empty()); + } + + #[test] + fn a_long_list_scrolls_with_the_selection() { + let temp = fixture_dir(); + for index in 0..40 { + std::fs::write( + temp.path().join(format!("item_{index:03}")), + vec![b'x'; 4096], + ) + .expect("write"); + } + let tree = scan(temp.path(), ScanOptions::default()).expect("scan"); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.tree = Some(tree); + app.selected = Some(vec![0]); + app.set_viewport(45, 13); + for _ in 0..20 { + app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); + } + assert!(app.list_scroll > 0); + let selected = app.selected_node().expect("selected").name.to_string(); + let mut terminal = + Terminal::new(TestBackend::new(45, 13)).expect("terminal"); + terminal + .draw(|frame| { + crate::treemap::render::draw( + frame, + &app, + &crate::treemap::theme::Palette::dark(), + ); + }) + .expect("draw"); + let map = app.map_area(); + let mut rendered = String::new(); + for y in map.y + 1..map.bottom() { + for x in map.x..map.right() { + rendered.push_str( + terminal + .backend() + .buffer() + .cell((x, y)) + .expect("cell") + .symbol(), + ); + } + } + assert!(rendered.contains(&selected)); + } + + #[test] + fn enter_opens_directories_and_explains_a_file_selection() { + let temp = fixture_dir(); + let root = temp.path().join("scan"); + let nested = root.join("Projects/app"); + std::fs::create_dir_all(&nested).expect("mkdir"); + std::fs::write(nested.join("main.rs"), b"code").expect("write"); + let tree = scan(&root, ScanOptions::default()).expect("scan"); + let mut app = App::new(root.clone(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.selected = first_child(&tree, &[]); + app.tree = Some(tree); + for name in ["Projects", "app"] { + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!( + app.current_path().expect("current"), + root.join(if name == "Projects" { + "Projects" + } else { + "Projects/app" + }) + ); + } + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!( + app.notice.as_deref(), + Some("File selected; Space marks it") + ); + assert_eq!(app.current_path(), Some(nested)); + app.handle_key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE)); + assert_eq!(app.current_path(), Some(root.join("Projects"))); + app.handle_key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE)); + assert_eq!(app.current_path(), Some(root)); + app.handle_key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE)); + assert_eq!(app.root, canonicalize_path(temp.path()).expect("parent")); + } + + #[test] + fn volume_picker_switches_roots_and_clears_outside_marks() { + let temp = fixture_dir(); + let first = temp.path().join("first"); + let second = temp.path().join("second"); + std::fs::create_dir_all(&first).expect("mkdir"); + std::fs::create_dir_all(&second).expect("mkdir"); + std::fs::write(first.join("marked"), b"data").expect("write"); + let mut app = App::new(first.clone(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.marks.push(Target { + path: first.join("marked"), + bytes: 4, + is_dir: false, + hidden: false, + }); + app.screen = Screen::Volumes; + app.volumes = [first, second.clone()] + .into_iter() + .map(|point| Volume { + point, + device: None, + space: None, + }) + .collect(); + app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(app.root, second); + assert_eq!(app.screen, Screen::Explore); + assert!(app.marks.is_empty()); + assert_eq!( + app.notice.as_deref(), + Some("Marks outside this scan were cleared") + ); + } + + #[test] + fn finished_scan_populates_insights_and_duration() { + let temp = fixture_dir(); + let cache = temp.path().join(".cache"); + std::fs::create_dir(&cache).expect("mkdir"); + let blob = std::fs::File::create(cache.join("blob")).expect("file"); + blob.set_len(128 * 1024 * 1024).expect("size"); + let project = temp.path().join("Projects/app"); + std::fs::create_dir_all(project.join("target")).expect("mkdir"); + std::fs::write(project.join("Cargo.toml"), b"[package]\n") + .expect("manifest"); + let build = std::fs::File::create(project.join("target/build.bin")) + .expect("file"); + build.set_len(96 * 1024 * 1024).expect("size"); + let temporary = temp.path().join("Downloads/tmp"); + std::fs::create_dir_all(&temporary).expect("mkdir"); + let session = + std::fs::File::create(temporary.join("session.bin")).expect("file"); + session.set_len(72 * 1024 * 1024).expect("size"); + let documents = temp.path().join("Documents"); + std::fs::create_dir(&documents).expect("mkdir"); + let personal = + std::fs::File::create(documents.join("annual.pdf")).expect("file"); + personal.set_len(200 * 1024 * 1024).expect("size"); + let options = ScanOptions { + apparent_size: true, + ..ScanOptions::default() + }; + let mut app = App::new(temp.path().to_path_buf(), options); + let deadline = Instant::now() + Duration::from_secs(5); + while app.scan.is_some() && Instant::now() < deadline { + app.tick(); + std::thread::sleep(Duration::from_millis(5)); + } + assert!(app.scan.is_none(), "scan finished"); + assert!(app.scan_error.is_none(), "scan succeeded"); + assert!(app.scan_elapsed.is_some(), "duration recorded"); + assert_eq!(app.progress.files, 5); + let tree = app.tree.as_ref().expect("tree"); + let findings: Vec<_> = app + .insights + .iter() + .map(|candidate| { + let node = tree.resolve(&candidate.crumbs).expect("finding"); + (node.name.to_string(), candidate.finding.clone()) + }) + .collect(); + assert_eq!( + findings, + vec![ + ( + ".cache".to_string(), + Finding::Reclaimable(Reclaim::Regenerable) + ), + ( + "target".to_string(), + Finding::Reclaimable(Reclaim::BuildOutput) + ), + ("tmp".to_string(), Finding::Reclaimable(Reclaim::Temporary)), + ] + ); + let mut terminal = + Terminal::new(TestBackend::new(120, 35)).expect("terminal"); + terminal + .draw(|frame| { + crate::treemap::render::draw( + frame, + &app, + &crate::treemap::theme::Palette::dark(), + ); + }) + .expect("draw"); + let output: String = terminal + .backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect(); + assert!(output.contains("WORTH A LOOK")); + assert!(output.contains(".cache")); + assert!(output.contains("target")); + assert!(output.contains("tmp")); + } + + #[test] + fn review_confirmation_removes_only_the_marked_path() { + let temp = fixture_dir(); + let selected = temp.path().join("selected"); + let neighbor = temp.path().join("neighbor"); + std::fs::write(&selected, vec![b'x'; 8192]).expect("write selected"); + std::fs::write(&neighbor, b"keep").expect("write neighbor"); + let tree = scan(temp.path(), ScanOptions::default()).expect("scan"); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.selected = tree + .children + .iter() + .position(|child| child.name.as_ref() == "selected") + .map(|index| vec![index]); + app.tree = Some(tree); + app.handle_key(KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE)); + assert_eq!(app.marks.len(), 1); + app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE)); + assert_eq!(app.screen, Screen::Review); + app.handle_key(KeyEvent::new(KeyCode::Char('p'), KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(app.screen, Screen::Confirm); + assert!(selected.exists()); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(app.screen, Screen::Confirm); + app.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); + assert_eq!(app.screen, Screen::Running); + let deadline = Instant::now() + Duration::from_secs(5); + while app.screen == Screen::Running && Instant::now() < deadline { + app.tick(); + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(app.screen, Screen::Done); + assert!(!selected.exists()); + assert!(neighbor.exists()); + assert_eq!(app.run_summary.failed, 0); + } + + #[test] + fn failed_removal_keeps_the_mark_for_review() { + let temp = fixture_dir(); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.marks.push(Target { + path: temp.path().join("missing"), + bytes: 100, + is_dir: false, + hidden: false, + }); + app.screen = Screen::Review; + app.removal_mode = RemovalMode::Permanent; + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + app.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)); + assert_eq!(app.screen, Screen::Running); + let deadline = Instant::now() + Duration::from_secs(5); + while app.screen == Screen::Running && Instant::now() < deadline { + app.tick(); + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(app.screen, Screen::Done); + assert_eq!(app.run_summary.failed, 1); + assert_eq!(app.marks.len(), 1); + } + + #[test] + fn control_c_during_removal_requests_stop_without_quitting() { + let temp = fixture_dir(); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.marks.push(Target { + path: temp.path().join("missing"), + bytes: 100, + is_dir: false, + hidden: false, + }); + app.removal_mode = RemovalMode::Permanent; + app.begin_removal(); + app.handle_key(KeyEvent::new( + KeyCode::Char('c'), + KeyModifiers::CONTROL, + )); + assert!(!app.quit); + assert!(app.run_cancelled); + } + + #[test] + fn saving_agent_prompt_creates_without_overwriting() { + let temp = fixture_dir(); + let selected = temp.path().join("selected"); + std::fs::write(&selected, b"content").expect("write selected"); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.marks.push(Target { + path: selected.clone(), + bytes: 7, + is_dir: false, + hidden: false, + }); + let output = temp.path().join("agent-prompt.txt"); + app.save_path = output.display().to_string(); + app.screen = Screen::SavePrompt; + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + let prompt = std::fs::read_to_string(&output).expect("saved prompt"); + assert!(prompt.contains(&selected.display().to_string())); + app.screen = Screen::SavePrompt; + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(std::fs::read_to_string(output).expect("prompt"), prompt); + assert!( + app.notice + .as_ref() + .is_some_and(|notice| notice.contains("Could not save")) + ); + } +} diff --git a/crates/disktree-cli/src/treemap/mod.rs b/crates/disktree-cli/src/treemap/mod.rs new file mode 100644 index 00000000..76939125 --- /dev/null +++ b/crates/disktree-cli/src/treemap/mod.rs @@ -0,0 +1,167 @@ +//! A terminal view over the disktree core. + +mod app; +mod render; +mod theme; +#[cfg(windows)] +mod windows_console; + +use std::fs::{File, OpenOptions}; +use std::io::{self, BufWriter, IsTerminal as _, Write as _}; +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use anyhow::{Context as _, Result, bail}; +use crossterm::event::{self, Event, KeyEventKind}; +use crossterm::execute; +use crossterm::terminal::{ + EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, + enable_raw_mode, +}; +use disktree_core::scan::ScanOptions; +use disktree_core::space::volume_root_for; +use ratatui::Terminal; +use ratatui::backend::CrosstermBackend; + +use self::app::{App, canonicalize_path}; +use self::theme::{ThemeChoice, ThemeState}; + +// Keep stdout free for the reviewed agent prompt, even when it is redirected. +#[cfg(windows)] +const TTY_OUTPUT: &str = "CONOUT$"; +#[cfg(not(windows))] +const TTY_OUTPUT: &str = "/dev/tty"; + +struct TerminalSession { + tty: File, +} + +impl TerminalSession { + fn enter() -> Result { + let mut tty = OpenOptions::new() + .write(true) + .open(TTY_OUTPUT) + .with_context(|| format!("open terminal output {TTY_OUTPUT}"))?; + enable_raw_mode().context("enable terminal raw mode")?; + if let Err(error) = execute!(tty, EnterAlternateScreen) { + let _ = disable_raw_mode(); + return Err(error.into()); + } + Ok(Self { tty }) + } + + fn writer(&self) -> io::Result { + self.tty.try_clone() + } +} + +impl Drop for TerminalSession { + fn drop(&mut self) { + let _ = execute!(self.tty, LeaveAlternateScreen); + let _ = disable_raw_mode(); + } +} + +pub fn run(args: &Args) -> Result<()> { + let root = match &args.path { + Some(path) => path.clone(), + None => std::env::home_dir().context("cannot find home directory")?, + }; + let root = canonicalize_path(&root) + .with_context(|| format!("cannot access {}", root.display()))?; + let root = if args.disk { + volume_root_for(&root).context("cannot find volume root")? + } else { + root + }; + if !root.is_dir() { + bail!("{} is not a directory", root.display()); + } + let options = ScanOptions { + apparent_size: args.apparent_size, + include_hidden: !args.no_hidden, + follow_links: args.follow_links, + ..ScanOptions::default() + }; + if !io::stdin().is_terminal() { + bail!("disktree-cli treemap needs an interactive terminal for input"); + } + #[cfg(windows)] + let _code_pages = windows_console::Utf8Console::enter() + .context("enable UTF-8 in the Windows console")?; + let mut app = App::new(root, options); + let mut theme = ThemeState::new(args.theme); + let stdout_prompt = { + let session = TerminalSession::enter()?; + // A full mosaic produces many small ANSI writes. Buffering them keeps + // classic Windows consoles from visibly painting one row at a time. + let output = BufWriter::with_capacity(256 * 1024, session.writer()?); + let mut terminal = Terminal::new(CrosstermBackend::new(output))?; + let size = terminal.size()?; + app.set_viewport(size.width, size.height); + // Compact maps begin with two levels; the depth keys can reveal more. + if size.width < 120 { + app.view_depth = 2; + } + let mut dirty = true; + let mut drew_first_frame = false; + // Fast scans can finish before the first frame. Give them a short + // window so the console paints the mosaic only once at startup. + let first_frame_by = Instant::now() + Duration::from_millis(180); + while !app.quit { + dirty |= app.tick(); + dirty |= theme.tick(); + if dirty + && (drew_first_frame + || app.scan.is_none() + || Instant::now() >= first_frame_by) + { + terminal + .draw(|frame| render::draw(frame, &app, theme.palette()))?; + dirty = false; + drew_first_frame = true; + } + if event::poll(Duration::from_millis(100))? { + match event::read()? { + Event::Key(key) if key.kind == KeyEventKind::Press => { + app.handle_key(key); + dirty = true; + } + Event::Resize(width, height) => { + terminal.clear()?; + app.set_viewport(width, height); + dirty = true; + } + _ => {} + } + } + } + app.stdout_prompt.take() + }; + if let Some(prompt) = stdout_prompt { + print!("{prompt}"); + io::stdout().flush()?; + } + Ok(()) +} + +#[derive(Clone, Debug, clap::Args)] +pub struct Args { + /// Directory to inspect (defaults to the home directory). + path: Option, + /// Scan the volume containing the selected directory. + #[arg(long)] + disk: bool, + /// Show apparent file length instead of allocated blocks. + #[arg(short = 'a', long)] + apparent_size: bool, + /// Start with hidden entries excluded from the view. + #[arg(short = 'H', long)] + no_hidden: bool, + /// Follow symbolic links while walking. + #[arg(short = 'l', long)] + follow_links: bool, + /// Override automatic Omarchy or system colors. + #[arg(long, value_enum, default_value = "auto")] + theme: ThemeChoice, +} diff --git a/crates/disktree-cli/src/treemap/render.rs b/crates/disktree-cli/src/treemap/render.rs new file mode 100644 index 00000000..599c1528 --- /dev/null +++ b/crates/disktree-cli/src/treemap/render.rs @@ -0,0 +1,2664 @@ +//! Compact terminal projection of disktree's mosaic and cleanup flow. + +use std::path::Path; +use std::time::Duration; + +use disktree_core::classify::Category; +use disktree_core::insights::Finding; +use disktree_core::path_style::PathStyle; +use disktree_core::removal::RemovalMode; +use disktree_core::size::{human_bytes, human_bytes_short, human_count}; +use disktree_core::tree::{Metric, path_of}; +use disktree_core::treemap::TileKind; +use ratatui::Frame; +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; +use ratatui::style::{Color, Modifier, Style}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Borders, Gauge, Paragraph}; +use unicode_segmentation::UnicodeSegmentation; +use unicode_width::UnicodeWidthStr; + +use super::app::{App, Screen, ViewMode}; +use super::theme::{ + ACCENT, AGE_LABELS, BG, MUTED, PANEL, Palette, RED, TEXT, age_bucket, + base_age_color, base_category_color as color, shade, +}; + +pub fn draw(frame: &mut Frame<'_>, app: &App, palette: &Palette) { + app.begin_animation_frame(); + draw_base(frame, app); + palette.apply(frame.buffer_mut()); +} + +fn draw_base(frame: &mut Frame<'_>, app: &App) { + let area = frame.area(); + frame.render_widget(Block::default().style(Style::default().bg(BG)), area); + if area.width < 45 || area.height < 13 { + centered(frame, area, "disktree needs at least 45 × 13 cells"); + return; + } + // The list names each category, so its header does not need a legend. + let head_height = app.header_height(area.width); + let head = Rect::new(area.x, area.y, area.width, head_height); + let body = app.body_area(area); + let foot = Rect::new(area.x, area.bottom() - 2, area.width, 2); + header(frame, app, head); + match app.screen { + Screen::Explore => explore(frame, app, body), + Screen::Review => review(frame, app, body), + Screen::Confirm => confirm(frame, app, body), + Screen::Running | Screen::Done => results(frame, app, body), + Screen::Help => help(frame, body), + Screen::Insights => insights(frame, app, body), + Screen::SavePrompt => save_prompt(frame, app, body), + Screen::Volumes => volume_picker(frame, app, body), + } + footer(frame, app, foot); +} + +fn header(frame: &mut Frame<'_>, app: &App, area: Rect) { + let path = app.current_path().unwrap_or_else(|| app.root.clone()); + let path = readable_path(&path.display().to_string()); + let depth_width: u16 = if app.screen == Screen::Explore { 16 } else { 0 }; + let wide_controls = app.screen == Screen::Explore && area.width >= 120; + let top_controls = wide_controls.then(|| header_controls(app, false)); + let top_controls_width = top_controls.as_ref().map_or(0, |controls| { + controls + .iter() + .map(|span| span.content.chars().count()) + .sum() + }); + let reserved = usize::from(depth_width) + + top_controls_width + + if wide_controls { 3 } else { 1 }; + let title_width = area + .width + .saturating_sub(u16::try_from(reserved).unwrap_or(u16::MAX)); + let path_width = usize::from(title_width).saturating_sub(16); + // A dark rule splits each colored cell into two panes. The blank cell + // makes the vertical gutter visible even when a font joins box edges. + let pane = Style::default().fg(BG).bg(ACCENT); + let title = Line::from(vec![ + Span::raw(" "), + Span::styled("━", pane), + Span::raw(" "), + Span::styled("━", pane), + Span::styled( + " disktree ", + Style::default().fg(ACCENT).add_modifier(Modifier::BOLD), + ), + Span::styled( + format!(" {}", focused_marquee(app, &path, path_width)), + Style::default().fg(TEXT), + ), + ]); + frame.render_widget( + Paragraph::new(title).style(Style::default().bg(BG)), + Rect::new(area.x, area.y, title_width, 1), + ); + if let Some(controls) = top_controls { + frame.render_widget( + Paragraph::new(Line::from(controls)).style(Style::default().bg(BG)), + Rect::new( + area.x + title_width + 1, + area.y, + u16::try_from(top_controls_width).unwrap_or(u16::MAX), + 1, + ), + ); + } + if depth_width > 0 && area.width >= depth_width { + frame.render_widget( + Paragraph::new(Line::from(vec![ + Span::styled("[", Style::default().fg(ACCENT).bg(PANEL)), + Span::raw(" "), + Span::styled("]", Style::default().fg(ACCENT).bg(PANEL)), + Span::raw(" "), + Span::styled("-", Style::default().fg(ACCENT).bg(PANEL)), + Span::raw("/"), + Span::styled("+", Style::default().fg(ACCENT).bg(PANEL)), + Span::styled(" Depth ", Style::default().fg(MUTED)), + Span::styled( + app.view_depth.to_string(), + Style::default().fg(TEXT).add_modifier(Modifier::BOLD), + ), + ])) + .style(Style::default().bg(BG)), + Rect::new(area.right() - depth_width, area.y, depth_width, 1), + ); + } + let scan = if app.scan.is_some() { + format!( + "scanning {} files · {} dirs", + human_count(app.progress.files), + human_count(app.progress.dirs) + ) + } else if let Some(node) = app.tree.as_ref() { + format!( + "{} · {} files · {} dirs", + human_bytes(node.bytes), + human_count(node.files), + human_count(u64::from(node.dirs)) + ) + } else { + app.scan_error + .clone() + .unwrap_or_else(|| "waiting".to_string()) + }; + let compact = area.width < 60; + let stats = if compact && app.scan.is_none() { + app.tree + .as_ref() + .map_or_else(|| scan.clone(), |node| human_bytes(node.bytes)) + } else { + scan + }; + if wide_controls { + put( + frame, + Rect::new(area.x, area.y + 1, area.width, 1), + format!(" {}", end_clip(&stats, usize::from(area.width - 1))), + Style::default().fg(MUTED).bg(BG), + ); + } else { + let controls = if app.screen == Screen::Explore { + header_controls(app, compact) + } else { + let measure = if app.options.apparent_size { + "apparent" + } else { + "disk" + }; + let hidden = if app.options.include_hidden { + "hidden" + } else { + "visible" + }; + vec![Span::styled( + format!( + "{} · {hidden} · {measure}", + app.mode.label().to_ascii_lowercase() + ), + Style::default().fg(MUTED), + )] + }; + let controls_width: usize = controls + .iter() + .map(|span| span.content.chars().count()) + .sum(); + let stats_width = usize::from(area.width) + .saturating_sub(controls_width + if compact { 4 } else { 6 }); + let separator = if compact { " │ " } else { " │ " }; + let mut line = vec![ + Span::styled( + format!(" {}", end_clip(&stats, stats_width)), + Style::default().fg(MUTED), + ), + Span::styled(separator, Style::default().fg(MUTED)), + ]; + line.extend(controls); + frame.render_widget( + Paragraph::new(Line::from(line)).style(Style::default().bg(BG)), + Rect::new(area.x, area.y + 1, area.width, 1), + ); + } + if area.height < 3 { + return; + } + if app.mode == ViewMode::Age { + age_legend(frame, area); + return; + } + // Keep every category visible as a complete label. Intermediate terminals + // have room for the mosaic, but not the desktop-length legend. + let short = [ + "Code", "Agent", "Tools", "Sync", "Git", "Media", "Docs", "Cache", + ]; + let (reclaim, separator) = if area.width >= 105 { + (" / Reclaimable", " ▪ ") + } else if area.width >= 77 { + (" / Reclaim", " ▪ ") + } else if area.width >= 61 { + (" / Reclaim", " ▪") + } else { + (" / Rclm", " ▪") + }; + let mut legend = vec![Span::styled(reclaim, Style::default().fg(MUTED))]; + legend.extend(Category::LEGEND.iter().enumerate().map( + |(index, category)| { + let label = if area.width >= 105 { + category.label() + } else { + short[index] + }; + Span::styled( + format!("{separator}{label}"), + Style::default().fg(color(*category)), + ) + }, + )); + let legend = Line::from(legend); + frame.render_widget( + Paragraph::new(legend).style(Style::default().bg(BG)), + Rect::new(area.x, area.y + 2, area.width, 1), + ); +} + +fn header_controls(app: &App, compact: bool) -> Vec> { + let measure = if app.options.apparent_size { + "Apparent" + } else { + "Disk" + }; + let hidden = if app.options.include_hidden { + "Hidden" + } else { + "Visible" + }; + let gap = if compact { " " } else { " · " }; + let label = Style::default().fg(TEXT); + let key = Style::default().fg(ACCENT).bg(PANEL); + vec![ + Span::styled("t", key), + Span::styled(format!(" {}", app.mode.label()), label), + Span::raw(gap), + Span::styled("i", key), + Span::styled(format!(" {hidden}"), label), + Span::raw(gap), + Span::styled("d", key), + Span::styled(format!(" {measure}"), label), + ] +} + +fn age_legend(frame: &mut Frame<'_>, area: Rect) { + let compact = area.width < 75; + let names = if compact { + ["Week", "Month", "6 months", "Year", "Older"] + } else { + AGE_LABELS + }; + let mut legend = vec![Span::styled(" / Age", Style::default().fg(MUTED))]; + legend.extend(names.into_iter().enumerate().map(|(index, name)| { + Span::styled( + format!(" ▪ {name}"), + Style::default().fg(base_age_color(index)), + ) + })); + frame.render_widget( + Paragraph::new(Line::from(legend)).style(Style::default().bg(BG)), + Rect::new(area.x, area.y + 2, area.width, 1), + ); +} + +fn explore(frame: &mut Frame<'_>, app: &App, area: Rect) { + if app.tree.is_none() { + if app.scan.is_some() || app.progress.cancelled { + scanning_panel(frame, app, area); + } else { + centered(frame, area, "No scan results. Press r to retry."); + } + return; + } + let (map, detail_area, side) = App::split_explore(area); + map_or_list(frame, app, map); + if side { + detail(frame, app, detail_area); + } else { + compact_detail(frame, app, detail_area); + } +} + +fn scanning_panel(frame: &mut Frame<'_>, app: &App, area: Rect) { + frame.render_widget( + Block::default().style(Style::default().bg(PANEL)), + area, + ); + let width = area.width.saturating_sub(4).min(72); + let x = area.x + (area.width - width) / 2; + let top = area.y + area.height.saturating_sub(7) / 2; + let cancelled = app.progress.cancelled && app.scan.is_none(); + let verb = if cancelled { + "Stopped reading " + } else { + "Reading " + }; + let path = readable_path(&app.root.display().to_string()); + let path = focused_marquee( + app, + &path, + usize::from(width).saturating_sub(verb.len()), + ); + frame.render_widget( + Paragraph::new(Line::from(vec![ + Span::styled(verb, Style::default().fg(ACCENT).bg(PANEL)), + Span::styled(path, Style::default().fg(TEXT).bg(PANEL)), + ])), + Rect::new(x, top, width, 1), + ); + + let files = human_count(app.progress.files); + let dirs = human_count(app.progress.dirs); + let bytes = human_bytes(app.progress.bytes); + let errors = human_count(app.progress.errors); + let compact = area.width < 65; + let lines = if compact { + vec![ + format!("{files} files · {dirs} directories"), + format!("{bytes} measured · {errors} unreadable"), + ] + } else { + vec![format!( + "{files} files {dirs} directories {bytes} measured {errors} unreadable" + )] + }; + for (index, line) in lines.into_iter().enumerate() { + put( + frame, + Rect::new(x, top + 2 + index as u16, width, 1), + end_clip(&line, usize::from(width)), + Style::default().fg(TEXT).bg(PANEL), + ); + } + + if !cancelled { + let meter_width = width.min(52); + let meter = Rect::new(x, top + 4, meter_width, 1); + fill(frame.buffer_mut(), meter, Style::default().bg(BG)); + let measured = (f32::from(meter_width) + * scan_activity(app.progress.files)) + .round() as u16; + fill( + frame.buffer_mut(), + Rect::new(x, meter.y, measured.min(meter_width), 1), + Style::default().bg(ACCENT), + ); + } + let explanation = if cancelled { + "Nothing is shown from a scan that did not finish." + } else if compact { + "Map and marks appear when the scan lands." + } else { + "The map, marks and disk meter appear when the scan lands." + }; + put( + frame, + Rect::new(x, top + 5, width, 1), + end_clip(explanation, usize::from(width)), + Style::default().fg(MUTED).bg(PANEL), + ); + let (key, action) = if cancelled { + ("r", " scan again") + } else { + ("Esc", " cancel scan") + }; + frame.render_widget( + Paragraph::new(Line::from(vec![ + Span::styled(key, Style::default().fg(ACCENT).bg(PANEL)), + Span::styled(action, Style::default().fg(MUTED).bg(PANEL)), + ])), + Rect::new(x, top + 6, width, 1), + ); +} + +/// The walk has no known total. Like the GUI, this is a moving activity +/// meter that approaches the end without claiming a completion percentage. +fn scan_activity(files: u64) -> f32 { + if files == 0 { + 0.06 + } else { + let scaled = files as f32 / (files as f32 + 20_000.0); + (0.1 + scaled * 0.85).min(0.99) + } +} + +fn map_or_list(frame: &mut Frame<'_>, app: &App, area: Rect) { + if app.is_list(area) { + ranked_list(frame, app, area); + } else { + treemap(frame, app, area); + } +} + +fn treemap(frame: &mut Frame<'_>, app: &App, area: Rect) { + // Six visible characters plus an ellipsis make a clipped name readable. + // Below that, the selected tile's detail line carries its full label. + const MIN_TILE_LABEL_COLUMNS: u16 = 7; + let Some(root) = app.tree.as_ref() else { + return; + }; + let tiles = app.tiles(area); + let buffer = frame.buffer_mut(); + let mut selected_rect = None; + for tile in tiles.iter() { + let rect = App::tile_rect(tile, area); + if rect.width == 0 || rect.height == 0 { + continue; + } + let (label, value, category, marked, reclaimable) = match &tile.kind { + TileKind::Node { crumbs } => { + let Some(item) = root.resolve(crumbs) else { + continue; + }; + ( + clean(&item.name), + item.value(app.options.metric), + item.category, + !app.marks.is_empty() + && app.is_marked(&path_of( + &app.root, + root, + crumbs, + PathStyle::Native, + )), + item.reclaim.is_some(), + ) + } + TileKind::Others { count, .. } => { + (format!("+{count} more"), 0, Category::Other, false, false) + } + }; + let selected = matches!(&tile.kind, + TileKind::Node { crumbs } if app.selected.as_ref() == Some(crumbs)); + let base = if app.mode == ViewMode::Age { + match &tile.kind { + TileKind::Node { crumbs } => root + .resolve(crumbs) + .and_then(|item| age_bucket(item.modified, app.scanned_at)) + .map_or_else(|| color(category), base_age_color), + TileKind::Others { .. } => color(category), + } + } else { + color(category) + }; + let bg = if marked { + Color::Rgb(92, 43, 54) + } else { + shade(base, 0.05_f32.mul_add(tile.depth as f32, 0.32)) + }; + fill(buffer, rect, Style::default().bg(bg).fg(TEXT)); + if reclaimable && !marked { + hatch(buffer, rect, shade(base, 0.68)); + } + if selected { + selected_rect = Some(rect); + } else if tile.depth == 0 { + top_border(buffer, rect, base); + } + let left = rect.x + u16::from(selected); + let top = rect.y + u16::from(selected && rect.height > 2); + let inner_width = rect.width.saturating_sub(1 + u16::from(selected)); + if inner_width >= MIN_TILE_LABEL_COLUMNS && top < rect.bottom() { + let label = if selected { + focused_marquee(app, &label, usize::from(inner_width)) + } else { + marquee(app, &label, usize::from(inner_width)) + }; + buffer.set_stringn( + left, + top, + label, + usize::from(inner_width), + Style::default().fg(TEXT).bg(bg).add_modifier( + if tile.depth == 0 { + Modifier::BOLD + } else { + Modifier::empty() + }, + ), + ); + if value > 0 { + let bottom = tile.header.map_or_else( + || rect.bottom(), + |header| area.y + (header.bottom() / 2.0).ceil() as u16, + ); + let bottom = bottom + .min(rect.bottom().saturating_sub(u16::from(selected))); + let size = match app.options.metric { + Metric::Bytes => human_bytes_short(value), + Metric::Files => human_count(value), + }; + if let Some((value, unit)) = fit_size_label( + &size, + usize::from(inner_width), + usize::from(bottom.saturating_sub(top + 1)), + ) { + let style = Style::default().fg(MUTED).bg(bg); + buffer.set_string(left, top + 1, value, style); + if let Some(unit) = unit { + buffer.set_string(left, top + 2, unit, style); + } + } + } + } + } + // Paint the selected edge last: rounded child tiles can reach its cells. + if let Some(rect) = selected_rect { + outline(buffer, rect, ACCENT); + } +} + +/// Prefer a compact unit before using a second terminal row. +fn fit_size_label( + size: &str, + width: usize, + rows: usize, +) -> Option<(String, Option)> { + if rows == 0 { + return None; + } + if size.len() <= width { + return Some((size.to_string(), None)); + } + let split = size.find(|ch: char| ch.is_ascii_alphabetic())?; + let (value, unit) = size.split_at(split); + let short = format!("{value}{}", unit.chars().next()?); + if short.len() <= width { + return Some((short, None)); + } + (rows >= 2 && value.len() <= width && unit.len() <= width) + .then(|| (value.to_string(), Some(unit.to_string()))) +} + +fn ranked_list(frame: &mut Frame<'_>, app: &App, area: Rect) { + let Some(node) = app.current_node() else { + return; + }; + let visible = app.visible_children(); + let total = visible.len(); + let capacity = usize::from(area.height.saturating_sub(1)); + let start = app.list_scroll.min(total.saturating_sub(capacity)); + let end = (start + capacity).min(total); + let range = if total == 0 { + "0/0".to_string() + } else { + format!("{}-{end}/{total}", start + 1) + }; + let hint = if area.width < 65 { + format!( + " CONTENTS {range} · {} files {} dirs", + human_count(node.files), + human_count(u64::from(node.dirs)) + ) + } else { + format!(" CONTENTS {range} arrows select · Enter open · Backspace up") + }; + let mut lines = vec![Line::styled(hint, Style::default().fg(MUTED))]; + for position in start..end { + let index = visible.get(position).expect("visible position in range"); + let child = &node.children[index]; + let mut crumbs = app.current.clone(); + crumbs.push(index); + let selected = app.selected.as_ref() == Some(&crumbs); + let marked = !app.marks.is_empty() + && app.tree.as_ref().is_some_and(|root| { + app.is_marked(&path_of( + &app.root, + root, + &crumbs, + PathStyle::Native, + )) + }); + let sigil = if marked { + "◆" + } else if selected { + "▸" + } else { + " " + }; + let size = match app.options.metric { + Metric::Bytes => human_bytes_short(child.bytes), + Metric::Files => human_count(child.files), + }; + let category_color = if app.mode == ViewMode::Age { + age_bucket(child.modified, app.scanned_at) + .map_or_else(|| color(child.category), base_age_color) + } else { + color(child.category) + }; + let style = + Style::default().fg(if selected { ACCENT } else { category_color }); + let label = if app.mode == ViewMode::Age { + let age = age_bucket(child.modified, app.scanned_at).map_or( + "Unknown", + |bucket| match bucket { + 0 => "Week", + 1 => "Month", + 2 => "6 months", + 3 => "Year", + _ => "Older", + }, + ); + format!(" [{age}]") + } else { + format!(" [{}]", child.category.label()) + }; + let name_width = + usize::from(area.width).saturating_sub(14 + label.len()); + lines.push(Line::from(vec![ + Span::styled(format!(" {sigil} "), style), + Span::styled(format!("{size:>8} "), Style::default().fg(MUTED)), + Span::styled( + if selected { + focused_marquee(app, &clean(&child.name), name_width) + } else { + marquee(app, &clean(&child.name), name_width) + }, + style, + ), + Span::styled(label, Style::default().fg(category_color)), + ])); + } + frame.render_widget( + Paragraph::new(lines).style(Style::default().bg(PANEL)), + area, + ); +} + +fn detail(frame: &mut Frame<'_>, app: &App, area: Rect) { + frame.render_widget( + Block::default().style(Style::default().bg(PANEL)), + area, + ); + let Some(node) = app.selected_node().or_else(|| app.current_node()) else { + return; + }; + let path = app.selected_path().unwrap_or_else(|| app.root.clone()); + let inner = Rect::new( + area.x + 1, + area.y + 1, + area.width.saturating_sub(2), + area.height.saturating_sub(2), + ); + if inner.height < 3 { + return; + } + let selected = Line::from(vec![Span::styled( + "SELECTION\n", + Style::default().fg(MUTED), + )]); + frame.render_widget( + Paragraph::new(selected), + Rect::new(inner.x, inner.y, inner.width, 1), + ); + put( + frame, + Rect::new(inner.x, inner.y + 2, inner.width, 1), + focused_marquee(app, &clean(&node.name), usize::from(inner.width)), + Style::default().fg(TEXT).add_modifier(Modifier::BOLD), + ); + put( + frame, + Rect::new(inner.x, inner.y + 3, inner.width, 1), + focused_marquee( + app, + &path_tail(&path, &app.root), + usize::from(inner.width), + ), + Style::default().fg(MUTED), + ); + put( + frame, + Rect::new(inner.x, inner.y + 5, inner.width, 1), + match app.options.metric { + Metric::Bytes => human_bytes(node.bytes), + Metric::Files => format!("{} files", human_count(node.files)), + }, + Style::default().fg(ACCENT).add_modifier(Modifier::BOLD), + ); + if inner.height >= 11 { + let value = node.value(app.options.metric); + let parent = app + .current_node() + .map_or(value, |parent| parent.value(app.options.metric)); + let share = if parent == 0 { + 0.0 + } else { + value as f64 / parent as f64 + }; + frame.render_widget( + Gauge::default() + .ratio(share.clamp(0.0, 1.0)) + .gauge_style(Style::default().fg(ACCENT).bg(BG)), + Rect::new(inner.x, inner.y + 6, inner.width, 1), + ); + put( + frame, + Rect::new(inner.x, inner.y + 8, inner.width, 1), + match app.options.metric { + Metric::Bytes => format!( + "{} files · {} dirs", + human_count(node.files), + human_count(u64::from(node.dirs)) + ), + Metric::Files => format!( + "{} · {} dirs", + human_bytes(node.bytes), + human_count(u64::from(node.dirs)) + ), + }, + Style::default().fg(MUTED), + ); + put( + frame, + Rect::new(inner.x, inner.y + 9, inner.width, 1), + if app.mode == ViewMode::Age { + age_bucket(node.modified, app.scanned_at) + .map_or("Age unknown", |bucket| AGE_LABELS[bucket]) + } else { + node.category.label() + }, + Style::default().fg(if app.mode == ViewMode::Age { + age_bucket(node.modified, app.scanned_at) + .map_or_else(|| color(node.category), base_age_color) + } else { + color(node.category) + }), + ); + } + if inner.height >= 20 && !app.insights.is_empty() { + let total: u64 = app.insights.iter().map(|item| item.bytes).sum(); + put( + frame, + Rect::new(inner.x, inner.y + 12, inner.width, 1), + "WORTH A LOOK", + Style::default().fg(MUTED), + ); + let total = human_bytes(total); + put( + frame, + Rect::new( + inner.right().saturating_sub(total.len() as u16), + inner.y + 12, + total.len() as u16, + 1, + ), + total, + Style::default().fg(ACCENT), + ); + for (index, candidate) in app.insights.iter().take(3).enumerate() { + let y = inner.y + 14 + index as u16 * 2; + if y + 1 >= inner.bottom().saturating_sub(5) { + break; + } + if let Some(root) = app.tree.as_ref() { + let path = path_of( + &app.root, + root, + &candidate.crumbs, + PathStyle::Native, + ); + let size = human_bytes_short(candidate.bytes); + let path_width = usize::from(inner.width) + .saturating_sub(text_width(&size) + 4); + let name = + marquee(app, &path_tail(&path, &app.root), path_width); + let category = root + .resolve(&candidate.crumbs) + .map_or(Category::Other, |node| node.category); + put( + frame, + Rect::new(inner.x, y, 1, 1), + " ", + Style::default().bg(color(category)), + ); + put( + frame, + Rect::new(inner.x + 2, y, path_width as u16, 1), + name, + Style::default().fg(TEXT), + ); + put( + frame, + Rect::new( + inner.right().saturating_sub(size.len() as u16), + y, + size.len() as u16, + 1, + ), + size, + Style::default().fg(TEXT), + ); + put( + frame, + Rect::new( + inner.x + 2, + y + 1, + inner.width.saturating_sub(2), + 1, + ), + end_clip( + &finding_reason(&candidate.finding), + usize::from(inner.width.saturating_sub(2)), + ), + Style::default().fg(MUTED), + ); + } + } + } + if inner.height >= 6 { + let y = inner.bottom() - 5; + disk_header(frame, app, Rect::new(inner.x, y, inner.width, 1)); + if let Some(space) = app.space { + put( + frame, + Rect::new(inner.x, y + 1, inner.width, 1), + format!("{} free", human_bytes(space.available)), + Style::default().fg(ACCENT).add_modifier(Modifier::BOLD), + ); + frame.render_widget( + Gauge::default() + .ratio(f64::from(space.used_fraction())) + .gauge_style(Style::default().fg(MUTED).bg(BG)), + Rect::new(inner.x, y + 2, inner.width, 1), + ); + put( + frame, + Rect::new(inner.x, y + 3, inner.width, 1), + format!( + "{} used / {} total", + human_bytes(space.used()), + human_bytes(space.total) + ), + Style::default().fg(MUTED), + ); + } + } +} + +fn compact_detail(frame: &mut Frame<'_>, app: &App, area: Rect) { + frame.render_widget( + Block::default().style(Style::default().bg(PANEL)), + area, + ); + if let Some(node) = app.selected_node() { + let suffix = match app.options.metric { + Metric::Bytes => format!( + " · {} · {} files", + human_bytes(node.bytes), + human_count(node.files) + ), + Metric::Files => format!( + " · {} files · {}", + human_count(node.files), + human_bytes(node.bytes) + ), + }; + let label_width = usize::from(area.width.saturating_sub(2)) + .saturating_sub(2 + text_width(&suffix)); + let label = focused_marquee(app, &clean(&node.name), label_width); + put( + frame, + Rect::new(area.x + 1, area.y, area.width.saturating_sub(2), 1), + format!("▸ {label}{suffix}"), + Style::default().fg(TEXT), + ); + } + let line = + Rect::new(area.x + 1, area.y + 1, area.width.saturating_sub(2), 1); + if area.height >= 5 || app.space.is_none() { + disk_header(frame, app, line); + } + if let Some(space) = app.space { + if area.height >= 5 { + put( + frame, + Rect::new(line.x, line.y + 1, line.width, 1), + format!("{} free", human_bytes(space.available)), + Style::default().fg(ACCENT).add_modifier(Modifier::BOLD), + ); + } else { + put( + frame, + line, + compact_disk_line( + app, + space.available, + usize::from(line.width), + ), + Style::default().fg(ACCENT), + ); + } + if area.height >= 3 { + let used = space.used_fraction(); + frame.render_widget( + Gauge::default() + .ratio(f64::from(used)) + .label(format!("{:.0}% used", used * 100.0)) + .gauge_style(Style::default().fg(MUTED).bg(BG)), + Rect::new( + area.x + 1, + area.y + if area.height >= 5 { 3 } else { 2 }, + area.width.saturating_sub(2), + 1, + ), + ); + } + if area.height >= 5 { + put( + frame, + Rect::new( + area.x + 1, + area.y + 4, + area.width.saturating_sub(2), + 1, + ), + format!( + "{} used / {} total", + human_bytes(space.used()), + human_bytes(space.total) + ), + Style::default().fg(MUTED), + ); + } + } else if area.height >= 5 { + put( + frame, + Rect::new(line.x, line.y + 1, line.width, 1), + "Free space is unavailable", + Style::default().fg(MUTED), + ); + } +} + +fn disk_path(app: &App) -> String { + app.device.as_ref().map_or_else( + || readable_path(&app.root.display().to_string()), + |path| readable_path(path), + ) +} + +fn compact_disk_line(app: &App, available: u64, width: usize) -> String { + let suffix = format!(" · {} free", human_bytes(available)); + let path_width = width.saturating_sub(5 + text_width(&suffix)); + format!("DISK {}{suffix}", marquee(app, &disk_path(app), path_width)) +} + +fn end_clip(value: &str, width: usize) -> String { + if text_width(value) <= width { + return value.to_string(); + } + if width == 0 { + return String::new(); + } + format!("{}…", prefix_cells(value, width - 1)) +} + +fn text_width(value: &str) -> usize { + if value.is_ascii() { + value.len() + } else { + UnicodeWidthStr::width(value) + } +} + +fn prefix_cells(value: &str, width: usize) -> String { + let mut result = String::new(); + let mut used = 0; + for part in value.graphemes(true) { + let cells = text_width(part); + if used + cells > width { + break; + } + result.push_str(part); + used += cells; + } + result +} + +fn marquee(app: &App, value: &str, width: usize) -> String { + marquee_at(app, value, width, app.marquee_elapsed()) +} + +fn focused_marquee(app: &App, value: &str, width: usize) -> String { + marquee_at(app, value, width, app.focused_marquee_elapsed()) +} + +fn marquee_at( + app: &App, + value: &str, + width: usize, + elapsed: Duration, +) -> String { + let (label, next) = sliding_window(value, width, elapsed); + if let Some(delay) = next { + app.schedule_animation(delay); + } + label +} + +/// Reveal the whole value in steps, with a pause at each end. The ellipsis +/// stays at the right edge while more text remains beyond the window. +fn sliding_window( + value: &str, + width: usize, + elapsed: Duration, +) -> (String, Option) { + if width == 0 { + return (String::new(), None); + } + let total = text_width(value); + if total <= width { + return (value.to_string(), None); + } + if width == 1 { + return ("…".to_string(), None); + } + if value.is_ascii() { + let (offset, next) = marquee_position(total - width, elapsed); + let remaining = total - offset; + let hidden_right = remaining > width; + let content_width = width - usize::from(hidden_right); + let mut visible = value[offset..offset + content_width].to_string(); + if hidden_right { + visible.push('…'); + } + return (visible, Some(next)); + } + let parts: Vec<(&str, usize)> = value + .graphemes(true) + .map(|part| (part, text_width(part))) + .collect(); + let mut remaining = total; + let mut end_start = 0; + while remaining > width && end_start < parts.len() { + remaining = remaining.saturating_sub(parts[end_start].1); + end_start += 1; + } + let (offset, next) = marquee_position(end_start, elapsed); + let remaining = parts[offset..] + .iter() + .map(|(_, cells)| cells) + .sum::(); + let hidden_right = remaining > width; + let content_width = width - usize::from(hidden_right); + let mut visible = String::new(); + let mut used = 0; + for &(part, cells) in &parts[offset..] { + if used + cells > content_width { + break; + } + visible.push_str(part); + used += cells; + } + if hidden_right { + visible.push('…'); + } + (visible, Some(next)) +} + +/// Return the visible grapheme offset and the next time its window changes. +fn marquee_position(steps: usize, elapsed: Duration) -> (usize, Duration) { + const PAUSE_MS: u128 = 800; + const STEP_MS: u128 = 200; + // A long path should reach its basename in seconds, even when it is + // hundreds of cells wider than the panel. + const MAX_SLIDE_MS: u128 = 5000; + let step_count = u128::try_from(steps).unwrap_or(u128::MAX); + let slide_ms = step_count.saturating_mul(STEP_MS).min(MAX_SLIDE_MS); + let cycle = PAUSE_MS.saturating_add(slide_ms).saturating_add(PAUSE_MS); + let phase = elapsed.as_millis() % cycle; + let (offset, next_ms) = if phase < PAUSE_MS { + (0, PAUSE_MS - phase) + } else if phase < PAUSE_MS + slide_ms { + let progress = phase - PAUSE_MS; + let moved = progress.saturating_mul(step_count) / slide_ms + 1; + let next_progress = moved.saturating_mul(slide_ms).div_ceil(step_count); + ( + usize::try_from(moved).unwrap_or(steps).min(steps), + next_progress.saturating_sub(progress).max(1), + ) + } else { + (steps, cycle - phase) + }; + ( + offset, + Duration::from_millis(u64::try_from(next_ms).unwrap_or(u64::MAX)), + ) +} + +fn disk_header(frame: &mut Frame<'_>, app: &App, area: Rect) { + let disk = marquee( + app, + &disk_path(app), + usize::from(area.width.saturating_sub(5)), + ); + frame.render_widget( + Paragraph::new(Line::from(vec![ + Span::styled("DISK ", Style::default().fg(ACCENT)), + Span::styled(disk, Style::default().fg(MUTED)), + ])), + area, + ); +} + +fn review(frame: &mut Frame<'_>, app: &App, area: Rect) { + let plan = app.plan(); + let mode = if app.removal_mode == RemovalMode::Trash { + format!( + "{} ({})", + app.removal_mode.label(), + app.trash_backend.label() + ) + } else { + app.removal_mode.label().to_string() + }; + let mut lines = vec![ + Line::styled( + " REVIEW MARKED PATHS", + Style::default().fg(ACCENT).add_modifier(Modifier::BOLD), + ), + Line::styled( + format!( + " {} targets · {} selected · {}", + plan.targets.len(), + human_bytes(plan.bytes()), + mode + ), + Style::default().fg(TEXT), + ), + Line::raw(""), + ]; + for target in plan + .targets + .iter() + .skip(app.scroll) + .take(usize::from(area.height)) + { + let prefix = format!(" ◆ {:>9} ", human_bytes_short(target.bytes)); + lines.push(Line::from(vec![ + Span::styled(prefix.clone(), Style::default().fg(ACCENT)), + Span::styled( + marquee( + app, + &readable_path(&target.path.display().to_string()), + usize::from(area.width).saturating_sub(text_width(&prefix)), + ), + Style::default().fg(TEXT), + ), + ])); + } + for blocked in plan + .blocked + .iter() + .take(usize::from(area.height).saturating_sub(lines.len())) + { + let suffix = format!(" — {}", clean(&blocked.reason)); + let path = marquee( + app, + &readable_path(&blocked.path.display().to_string()), + usize::from(area.width).saturating_sub(5 + text_width(&suffix)), + ); + lines.push(Line::styled( + format!(" ! {path}{suffix}"), + Style::default().fg(RED), + )); + } + if let Some(space) = app.space { + lines.push(Line::raw("")); + lines.push(Line::styled( + format!( + " DISK {} free → {} projected", + human_bytes(space.available), + human_bytes(space.after_removing(plan.reclaim()).available) + ), + Style::default().fg(ACCENT), + )); + } + for (bytes, reason) in [ + (plan.foreign(), "on other volumes"), + (plan.unattributed(), "on an unknown volume"), + ] { + if bytes > 0 { + lines.push(Line::styled( + format!( + " {} {reason}; excluded from projection", + human_bytes(bytes) + ), + Style::default().fg(MUTED), + )); + } + } + lines.push(Line::raw("")); + lines.push(Line::styled( + " a hand to agent (stdout) s save agent prompt Enter proceed", + Style::default().fg(MUTED), + )); + lines.push(Line::styled( + " m trash p permanent ! clear marks Esc explore", + Style::default().fg(MUTED), + )); + panel(frame, area, lines); +} + +fn confirm(frame: &mut Frame<'_>, app: &App, area: Rect) { + let lines = vec![ + Line::styled( + " CONFIRM PERMANENT DELETION", + Style::default().fg(RED).add_modifier(Modifier::BOLD), + ), + Line::raw(""), + Line::styled( + format!( + " {} paths · {} to remove", + app.plan().targets.len(), + human_bytes(app.marked_bytes()) + ), + Style::default().fg(TEXT), + ), + Line::raw(""), + Line::styled( + " This cannot be undone. Press y to delete; Esc cancels.", + Style::default().fg(RED), + ), + ]; + panel(frame, area, lines); +} + +fn results(frame: &mut Frame<'_>, app: &App, area: Rect) { + let done = app.screen == Screen::Done; + let heading = if done && app.run_cancelled { + " REMOVAL STOPPED" + } else if done { + " REMOVAL COMPLETE" + } else { + " REMOVING MARKED PATHS" + }; + let mut lines = vec![ + Line::styled( + heading, + Style::default().fg(ACCENT).add_modifier(Modifier::BOLD), + ), + Line::styled( + format!( + " {} of {} removed · {} failed", + app.run_summary.removed, + app.run_summary.total, + app.run_summary.failed + ), + Style::default().fg(TEXT), + ), + Line::raw(""), + ]; + for (path, outcome) in app + .run_log + .iter() + .rev() + .take(usize::from(area.height.saturating_sub(7))) + { + let (mark, style) = if outcome.is_ok() { + ("✓", Style::default().fg(ACCENT)) + } else { + ("!", Style::default().fg(RED)) + }; + let path = marquee( + app, + &readable_path(&path.display().to_string()), + usize::from(area.width).saturating_sub(4), + ); + lines.push(Line::styled(format!(" {mark} {path}"), style)); + } + if done { + lines.push(Line::raw("")); + let gain = app.measured_gain.map_or_else( + || "unavailable".to_string(), + |bytes| { + if bytes >= 0 { + human_bytes(bytes as u64) + } else { + format!("-{}", human_bytes(bytes.unsigned_abs() as u64)) + } + }, + ); + lines.push(Line::styled( + format!(" Measured change in free space: {gain}"), + Style::default().fg(ACCENT), + )); + lines.push(Line::styled( + " Enter or Esc returns to the map", + Style::default().fg(MUTED), + )); + } else { + lines.push(Line::styled( + " Esc stops after the current path", + Style::default().fg(MUTED), + )); + } + panel(frame, area, lines); +} + +fn insights(frame: &mut Frame<'_>, app: &App, area: Rect) { + let heading = " WORTH A LOOK"; + let total: u64 = app.insights.iter().map(|item| item.bytes).sum(); + let total = if total > 0 { + human_bytes(total) + } else { + String::new() + }; + let gap = usize::from(area.width) + .saturating_sub(text_width(heading) + text_width(&total)); + let mut lines = vec![ + Line::from(vec![ + Span::styled( + heading, + Style::default().fg(ACCENT).add_modifier(Modifier::BOLD), + ), + Span::raw(" ".repeat(gap)), + Span::styled(total, Style::default().fg(ACCENT)), + ]), + Line::raw(""), + ]; + if app.insights.is_empty() { + lines.push(Line::styled( + " No notable reclaimable paths in this scan.", + Style::default().fg(MUTED), + )); + } + let rows = usize::from(area.height.saturating_sub(6) / 2).max(1); + let start = app.insight_index.saturating_sub(rows / 2); + for (index, item) in app.insights.iter().enumerate().skip(start).take(rows) + { + let Some(root) = app.tree.as_ref() else { break }; + let path = path_of(&app.root, root, &item.crumbs, PathStyle::Native); + let selected = index == app.insight_index; + let name_color = if selected { ACCENT } else { TEXT }; + let category = root + .resolve(&item.crumbs) + .map_or(Category::Other, |node| node.category); + let size = human_bytes_short(item.bytes); + let path_width = + usize::from(area.width).saturating_sub(text_width(&size) + 8); + let path = path_tail(&path, &app.root); + let path = if selected { + focused_marquee(app, &path, path_width) + } else { + marquee(app, &path, path_width) + }; + let padding = " ".repeat(path_width.saturating_sub(text_width(&path))); + lines.push(Line::from(vec![ + Span::raw(" "), + Span::styled( + if selected { "▸" } else { " " }, + Style::default().fg(ACCENT), + ), + Span::raw(" "), + Span::styled("▪", Style::default().fg(color(category))), + Span::raw(" "), + Span::styled( + format!("{path}{padding}"), + Style::default().fg(name_color), + ), + Span::raw(" "), + Span::styled(size, Style::default().fg(TEXT)), + ])); + lines.push(Line::styled( + format!( + " {}", + end_clip( + &finding_reason(&item.finding), + usize::from(area.width).saturating_sub(6), + ) + ), + Style::default().fg(MUTED), + )); + } + lines.push(Line::raw("")); + lines.push(Line::styled( + " j/k select · Enter reveal · Esc close", + Style::default().fg(MUTED), + )); + panel(frame, area, lines); +} + +fn finding_reason(finding: &Finding) -> String { + match finding { + Finding::Reclaimable(reason) => reason.label().to_string(), + Finding::Worktrees { count, oldest_days } => { + format!("{count} worktrees · oldest {oldest_days} days") + } + Finding::StaleExperiments { count } => { + format!("{count} stale experiments") + } + } +} + +fn volume_picker(frame: &mut Frame<'_>, app: &App, area: Rect) { + let mut lines = vec![ + Line::styled( + " SCAN A VOLUME", + Style::default().fg(ACCENT).add_modifier(Modifier::BOLD), + ), + Line::styled( + " j/k select · Enter scan · Esc cancel", + Style::default().fg(MUTED), + ), + Line::raw(""), + ]; + if app.volumes_loading { + lines.push(Line::styled( + " Looking for mounted volumes…", + Style::default().fg(MUTED), + )); + } else if app.volumes.is_empty() { + lines.push(Line::styled( + " No other readable volumes found.", + Style::default().fg(MUTED), + )); + } else { + let rows = usize::from(area.height.saturating_sub(5)).max(1); + let start = app.volume_highlight.saturating_sub(rows / 2); + for (index, volume) in + app.volumes.iter().enumerate().skip(start).take(rows) + { + let selected = index == app.volume_highlight; + let free = volume.space.map_or_else( + || "free unknown".to_string(), + |space| format!("{} free", human_bytes(space.available)), + ); + let path = readable_path(&volume.point.display().to_string()); + let max_path = usize::from(area.width) + .saturating_sub(free.chars().count() + 7); + lines.push(Line::styled( + format!( + " {} {} {free}", + if selected { '>' } else { ' ' }, + if selected { + focused_marquee(app, &path, max_path) + } else { + marquee(app, &path, max_path) + } + ), + Style::default().fg(if selected { ACCENT } else { TEXT }), + )); + } + } + panel(frame, area, lines); +} + +fn save_prompt(frame: &mut Frame<'_>, app: &App, area: Rect) { + panel( + frame, + area, + vec![ + Line::styled(" SAVE AGENT PROMPT", Style::default().fg(ACCENT)), + Line::raw(""), + Line::styled( + format!( + " File: {}_", + if app.save_path.is_empty() { + "disktree-agent-prompt.txt".to_string() + } else { + clean(&app.save_path) + } + ), + Style::default().fg(TEXT), + ), + Line::raw(""), + Line::styled( + " Enter creates the file · Esc cancels", + Style::default().fg(MUTED), + ), + ], + ); +} + +fn help(frame: &mut Frame<'_>, area: Rect) { + if area.height < 18 { + panel( + frame, + area, + vec![ + Line::styled(" DISKTREE KEYS", Style::default().fg(ACCENT)), + guide_line(&[("arrows", "move"), ("Enter", "open")], BG), + guide_line( + &[("Backspace", "up"), ("Tab", "next"), ("Space", "mark")], + BG, + ), + guide_line(&[("c", "review"), ("/", "filter")], BG), + guide_line( + &[("m", "trash"), ("p", "delete"), ("a", "agent")], + BG, + ), + guide_line( + &[("v", "list"), ("V", "volumes"), ("g", "disk")], + BG, + ), + guide_line(&[("[ ] -/+", "depth"), ("w", "insights")], BG), + guide_line( + &[ + ("t", "size/files/age"), + ("i", "hidden"), + ("d", "disk/app"), + ], + BG, + ), + guide_line( + &[("r", "rescan"), ("q", "quit"), ("Esc", "close")], + BG, + ), + ], + ); + return; + } + panel( + frame, + area, + vec![ + Line::styled( + " DISKTREE KEYS", + Style::default().fg(ACCENT).add_modifier(Modifier::BOLD), + ), + Line::raw(""), + help_row("arrows / hjkl", "Move among visible tiles"), + help_row("Tab / Shift-Tab", "Next / previous visible tile"), + help_row("Enter", "Open a directory"), + help_row("Backspace", "Go to parent"), + help_row("Space", "Mark or unmark selection"), + help_row("c", "Review marked paths"), + help_row("w", "Worth a look"), + help_row("/", "Filter by name"), + help_row("v", "Toggle map/scrolling list"), + help_row("V", "Choose a volume or drive"), + help_row("g", "Scan this disk from its root"), + help_row("[ / ] or - / +", "Show fewer / more tile levels"), + help_row("t", "Size / Files / Age"), + help_row("i / d", "Hidden entries / disk or apparent size"), + help_row("r", "Rescan"), + help_row("q / Ctrl-C", "Quit"), + Line::raw(""), + Line::styled( + " Press any key to close", + Style::default().fg(MUTED), + ), + ], + ); +} + +fn help_row(key: &str, label: &str) -> Line<'static> { + Line::from(vec![ + Span::raw(" "), + Span::styled( + format!(" {key} "), + Style::default() + .fg(ACCENT) + .bg(BG) + .add_modifier(Modifier::BOLD), + ), + Span::styled( + format!( + "{}{label}", + " ".repeat(16_usize.saturating_sub(key.chars().count() + 2)) + ), + Style::default().fg(TEXT), + ), + ]) +} + +fn guide_line(hints: &[(&str, &str)], key_bg: Color) -> Line<'static> { + guide_line_with_gap(hints, key_bg, 2) +} + +fn guide_line_with_gap( + hints: &[(&str, &str)], + key_bg: Color, + gap: usize, +) -> Line<'static> { + let mut spans = vec![Span::raw(" ")]; + for (key, label) in hints { + spans.push(Span::styled( + format!("{key} "), + Style::default() + .fg(ACCENT) + .bg(key_bg) + .add_modifier(Modifier::BOLD), + )); + spans.push(Span::styled( + format!("{label}{}", " ".repeat(gap)), + Style::default().fg(MUTED), + )); + } + Line::from(spans) +} + +/// Leave out entire key hints when the terminal is too narrow for them. +fn guide_line_fit( + hints: &[(&str, &str)], + width: usize, + key_bg: Color, +) -> Line<'static> { + let mut used = 1; + let fit: Vec<_> = hints + .iter() + .copied() + .take_while(|(key, label)| { + let cells = text_width(key) + text_width(label) + 2; + if used + cells > width { + return false; + } + used += cells; + true + }) + .collect(); + guide_line_with_gap(&fit, key_bg, 1) +} + +fn footer(frame: &mut Frame<'_>, app: &App, area: Rect) { + frame.render_widget(Block::default().style(Style::default().bg(BG)), area); + let line = if app.search_open { + Line::raw(format!(" /{}_", clean(&app.search))) + } else if let Some(notice) = &app.notice { + Line::raw(format!(" {}", clean(notice))) + } else { + let short = area.width < 65; + let hints: &[(&str, &str)] = match app.screen { + Screen::Explore if short => &[ + ("?", "help"), + ("Space", "mark"), + ("Enter", "open"), + ("hjkl", "move"), + ], + Screen::Explore if area.width >= 100 => &[ + ("?", "help"), + ("Space", "mark"), + ("Enter", "open"), + ("Backspace", "up"), + ("c", "review"), + ("hjkl", "move"), + ("/", "filter"), + ("[ ]", "depth"), + ("V", "volumes"), + ("r", "rescan"), + ("w", "look"), + ("v", "list"), + ], + Screen::Explore => &[ + ("?", "help"), + ("Space", "mark"), + ("Enter", "open"), + ("Bksp", "up"), + ("c", "review"), + ("hjkl", "move"), + ("/", "filter"), + ("w", "look"), + ("v", "list"), + ], + Screen::Review if short => &[ + ("a", "agent"), + ("m", "trash"), + ("p", "delete"), + ("Enter", "go"), + ], + Screen::Review => &[ + ("a", "agent prompt"), + ("s", "save prompt"), + ("Enter", "proceed"), + ("Esc", "explore"), + ], + Screen::Confirm => &[("y", "confirm"), ("Esc", "cancel")], + Screen::Running => &[("Esc", "stop after current path")], + Screen::Done => &[("Enter", "return to map")], + Screen::Help | Screen::Insights => &[("Esc", "close")], + Screen::Volumes => { + &[("j/k", "select"), ("Enter", "scan"), ("Esc", "cancel")] + } + Screen::SavePrompt => { + &[("Enter", "create file"), ("Esc", "cancel")] + } + }; + guide_line_fit(hints, usize::from(area.width), PANEL) + }; + frame.render_widget( + Paragraph::new(line).style(Style::default().fg(MUTED).bg(BG)), + Rect::new(area.x, area.y, area.width, 1), + ); + let scan = scan_footer(app, area.width); + let scan_width = u16::try_from(scan.chars().count()) + .unwrap_or(u16::MAX) + .min(area.width); + let left_width = area.width.saturating_sub(scan_width.saturating_add(1)); + let free = app.space.map_or_else( + || "free unknown".to_string(), + |space| format!("{} free", human_bytes(space.available)), + ); + let mut status = format!(" {free}"); + if !app.marks.is_empty() { + let projection = if area.width < 65 { "est" } else { "projected" }; + let full = format!( + "{status} · {} marked · {} {projection}", + app.marks.len(), + human_bytes(app.plan().reclaim()) + ); + let short = format!("{status} · {} marked", app.marks.len()); + if full.chars().count() <= usize::from(left_width) { + status = full; + } else if short.chars().count() <= usize::from(left_width) { + status = short; + } + } + put( + frame, + Rect::new(area.x, area.y + 1, left_width, 1), + status, + Style::default().fg(ACCENT), + ); + put( + frame, + Rect::new(area.right() - scan_width, area.y + 1, scan_width, 1), + scan, + Style::default().fg(MUTED), + ); +} + +fn scan_footer(app: &App, width: u16) -> String { + let count = + human_count(app.progress.files.saturating_add(app.progress.dirs)); + let short = width < 65; + if app.scan.is_some() { + return if short { + format!("scanning · {count}") + } else { + format!( + "scanning · {count} entries · {}", + human_bytes(app.progress.bytes) + ) + }; + } + if app.progress.cancelled { + return format!("scan stopped · {count}"); + } + if app.scan_error.is_some() { + return "scan failed".to_string(); + } + if let Some(elapsed) = app.scan_elapsed { + return if short { + format!("scan {count} · {:.1}s", elapsed.as_secs_f32()) + } else { + format!("scan {count} entries · {:.1}s", elapsed.as_secs_f32()) + }; + } + format!("scan {count} entries") +} + +fn panel(frame: &mut Frame<'_>, area: Rect, lines: Vec>) { + frame.render_widget( + Paragraph::new(lines) + .style(Style::default().fg(TEXT).bg(PANEL)) + .block( + Block::default() + .borders(Borders::TOP) + .border_style(Style::default().fg(MUTED)), + ), + area, + ); +} + +fn centered(frame: &mut Frame<'_>, area: Rect, message: &str) { + let y = area.y + area.height / 2; + put( + frame, + Rect::new(area.x + 2, y, area.width.saturating_sub(4), 1), + message, + Style::default().fg(MUTED), + ); +} + +fn put( + frame: &mut Frame<'_>, + area: Rect, + value: impl Into, + style: Style, +) { + if area.width > 0 && area.height > 0 { + frame.render_widget(Paragraph::new(value.into()).style(style), area); + } +} + +fn fill(buffer: &mut Buffer, rect: Rect, style: Style) { + for y in rect.y..rect.bottom() { + for x in rect.x..rect.right() { + buffer[(x, y)].set_symbol(" ").set_style(style); + } + } +} + +fn hatch(buffer: &mut Buffer, rect: Rect, color: Color) { + for y in rect.y..rect.bottom() { + for x in rect.x..rect.right() { + if (x + y * 2) % 5 == 0 { + buffer[(x, y)].set_symbol("/").set_fg(color); + } + } + } +} + +fn top_border(buffer: &mut Buffer, rect: Rect, color: Color) { + for x in rect.x..rect.right() { + buffer[(x, rect.y)].set_symbol("─").set_fg(color); + } +} + +fn outline(buffer: &mut Buffer, rect: Rect, color: Color) { + for x in rect.x..rect.right() { + buffer[(x, rect.y)].set_symbol("─").set_fg(color); + if rect.height > 1 { + buffer[(x, rect.bottom() - 1)].set_symbol("─").set_fg(color); + } + } + for y in rect.y..rect.bottom() { + buffer[(rect.x, y)].set_symbol("│").set_fg(color); + if rect.width > 1 { + buffer[(rect.right() - 1, y)].set_symbol("│").set_fg(color); + } + } +} + +fn path_tail(path: &Path, root: &Path) -> String { + path.strip_prefix(root).map_or_else( + |_| readable_path(&path.display().to_string()), + |tail| { + format!( + ".{}{}", + std::path::MAIN_SEPARATOR, + clean(&tail.display().to_string()) + ) + }, + ) +} + +fn readable_path(path: &str) -> String { + let path = clean(path); + if let Some(rest) = path.strip_prefix(r"\\?\UNC\") { + return format!(r"\\{rest}"); + } + path.strip_prefix(r"\\?\").unwrap_or(&path).to_string() +} + +fn clean(text: &str) -> String { + text.chars() + .map(|ch| if ch.is_control() { '�' } else { ch }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use disktree_core::insights::Candidate; + use disktree_core::removal::Target; + use disktree_core::scan::{ScanOptions, scan}; + use ratatui::Terminal; + use ratatui::backend::TestBackend; + use std::time::Duration; + + #[test] + fn scan_panel_uses_the_gui_reading_and_activity_grammar() { + let temp = tempfile::tempdir().expect("tempdir"); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + app.progress = disktree_core::scan::ScanSnapshot { + files: 1200, + dirs: 40, + bytes: 50 * 1024 * 1024, + errors: 2, + ..Default::default() + }; + for (width, height) in [(45, 13), (80, 24), (120, 35)] { + let mut terminal = Terminal::new(TestBackend::new(width, height)) + .expect("terminal"); + terminal + .draw(|frame| draw(frame, &app, &Palette::dark())) + .expect("draw"); + let output: String = terminal + .backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect(); + for phrase in [ + "━ ━ disktree", + "Reading", + "files", + "directories", + "50 MiB measured", + "2 unreadable", + "Esc cancel scan", + ] { + assert!(output.contains(phrase), "width {width}: {phrase}"); + } + assert!(!output.contains('%'), "activity is not a percent"); + let body = app.body_area(Rect::new(0, 0, width, height)); + let meter_y = body.y + body.height.saturating_sub(7) / 2 + 4; + let meter_x = (width - width.saturating_sub(4).min(72)) / 2; + let fill = terminal + .backend() + .buffer() + .cell((meter_x, meter_y)) + .expect("meter cell"); + assert_eq!(fill.bg, ACCENT); + } + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.progress.cancelled = true; + let mut terminal = + Terminal::new(TestBackend::new(45, 13)).expect("terminal"); + terminal + .draw(|frame| draw(frame, &app, &Palette::dark())) + .expect("cancelled draw"); + let output: String = terminal + .backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect(); + assert!(output.contains("Stopped reading")); + assert!(output.contains("r scan again")); + } + + #[test] + fn wide_controls_share_the_title_row_with_depth() { + let temp = tempfile::tempdir().expect("tempdir"); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.tree = + Some(scan(temp.path(), ScanOptions::default()).expect("scan")); + for (width, height) in [(80, 24), (120, 35)] { + let mut terminal = Terminal::new(TestBackend::new(width, height)) + .expect("terminal"); + terminal + .draw(|frame| draw(frame, &app, &Palette::dark())) + .expect("draw"); + let row = |y| { + (0..width) + .map(|x| { + terminal + .backend() + .buffer() + .cell((x, y)) + .expect("cell") + .symbol() + .to_string() + }) + .collect::() + }; + let title = row(0); + let status = row(1); + let guide = row(height - 2); + assert!(guide.contains("hjkl move"), "{guide}"); + if width == 120 { + for control in ["t Size", "i Hidden", "d Disk", "Depth 3"] { + assert!(title.contains(control), "{title}"); + } + assert!(!status.contains("t Size"), "{status}"); + let mut last = 0; + for hint in [ + "? help", + "Space mark", + "Enter open", + "Backspace up", + "c review", + "hjkl move", + "/ filter", + "[ ] depth", + "V volumes", + "r rescan", + "w look", + "v list", + ] { + let position = guide.find(hint).expect("footer hint"); + assert!(position >= last, "footer order: {guide}"); + last = position + hint.len(); + } + } else { + assert!(!title.contains("t Size"), "{title}"); + assert!(status.contains("t Size"), "{status}"); + } + } + } + + #[test] + fn screens_render_at_compact_and_wide_sizes() { + let temp = tempfile::tempdir().expect("tempdir"); + let root = temp.path(); + std::fs::create_dir(root.join("cache")).expect("mkdir"); + std::fs::write(root.join("cache/large"), vec![b'x'; 8192]) + .expect("write"); + std::fs::write(root.join("file"), vec![b'y'; 2048]).expect("write"); + let tree = scan(root, ScanOptions::default()).expect("scan"); + let mut app = App::new(root.to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.selected = Some(vec![0]); + app.tree = Some(tree); + app.space = Some(disktree_core::space::SpaceInfo { + total: 100, + free: 25, + available: 25, + }); + app.marks.push(Target { + path: root.join("cache"), + bytes: 8192, + is_dir: true, + hidden: false, + }); + for (width, height) in + [(45, 13), (60, 24), (65, 24), (80, 24), (120, 35)] + { + let device = if width >= 80 { + "/dev/mapper/ubuntu--vg-ubuntu--lv" + } else { + "/dev/test0" + }; + app.device = Some(device.to_string()); + let mut terminal = Terminal::new(TestBackend::new(width, height)) + .expect("terminal"); + for screen in [ + Screen::Explore, + Screen::Review, + Screen::Confirm, + Screen::Running, + Screen::Done, + Screen::Help, + Screen::Insights, + Screen::SavePrompt, + Screen::Volumes, + ] { + app.screen = screen; + terminal + .draw(|frame| draw(frame, &app, &Palette::dark())) + .expect("draw"); + let output: String = terminal + .backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect(); + assert!(output.contains("disktree")); + if screen == Screen::Explore { + assert!(output.contains("hjkl move"), "width {width}"); + for control in ["t Size", "i Hidden", "d Disk"] { + assert!( + output.contains(control), + "width {width}: {control}" + ); + } + assert!(output.contains(&format!("DISK {device}"))); + assert!(output.contains("1 marked")); + if width <= 80 { + assert!(output.contains("75% used")); + assert!(output.contains("? help"), "width {width}"); + if width == 80 { + assert!(output.contains("v list")); + assert!(output.contains("w look")); + } + if (60..=80).contains(&width) { + let legend: String = (0..width) + .map(|x| { + terminal + .backend() + .buffer() + .cell((x, 2)) + .expect("legend cell") + .symbol() + .to_string() + }) + .collect(); + for label in [ + "Code", "Agent", "Tools", "Sync", "Git", + "Media", "Docs", "Cache", + ] { + assert!(legend.contains(label), "{legend}"); + } + assert!(legend.contains(if width == 60 { + "Rclm" + } else { + "Reclaim" + })); + } + let key = terminal + .backend() + .buffer() + .cell((2, height - 2)) + .expect("guide key"); + assert_eq!(key.fg, ACCENT); + assert_eq!(key.bg, PANEL); + } + if width >= 80 { + assert!(output.contains("25 B free")); + assert!(output.contains("75 B used / 100 B total")); + assert!(output.contains("projected")); + } + } + if width == 45 && screen == Screen::Review { + assert!(output.contains("a agent")); + assert!(output.contains("p delete")); + } + if width == 45 && screen == Screen::Help { + assert!(output.contains("Space mark")); + } + } + } + } + + #[test] + fn compact_header_shows_all_changed_control_states() { + let temp = tempfile::tempdir().expect("tempdir"); + let options = ScanOptions { + metric: disktree_core::tree::Metric::Files, + apparent_size: true, + include_hidden: false, + ..ScanOptions::default() + }; + let mut app = App::new(temp.path().to_path_buf(), options); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + let mut terminal = + Terminal::new(TestBackend::new(45, 13)).expect("terminal"); + terminal + .draw(|frame| draw(frame, &app, &Palette::dark())) + .expect("draw"); + let header: String = (0..45) + .map(|x| { + terminal + .backend() + .buffer() + .cell((x, 1)) + .expect("header cell") + .symbol() + .to_string() + }) + .collect(); + for control in ["t Files", "i Visible", "d Apparent"] { + assert!(header.contains(control), "{header}"); + } + } + + #[test] + fn age_mode_names_its_scale_at_narrow_and_wide_sizes() { + let temp = tempfile::tempdir().expect("tempdir"); + std::fs::write(temp.path().join("fresh"), b"fresh") + .expect("fresh file"); + std::fs::write(temp.path().join("old"), b"old").expect("old file"); + let mut tree = scan(temp.path(), ScanOptions::default()).expect("scan"); + let scanned_at = 100_000_000; + for child in &mut tree.children { + child.modified = if child.name.as_ref() == "fresh" { + scanned_at - 3 * 86_400 + } else { + scanned_at - 500 * 86_400 + }; + } + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.tree = Some(tree); + app.mode = ViewMode::Age; + app.scanned_at = scanned_at; + app.selected = Some(vec![0]); + for (width, height) in [(45, 13), (80, 24), (120, 35)] { + let mut terminal = Terminal::new(TestBackend::new(width, height)) + .expect("terminal"); + terminal + .draw(|frame| draw(frame, &app, &Palette::dark())) + .expect("draw"); + let output: String = terminal + .backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect(); + assert!(output.contains("t Age"), "width {width}: {output}"); + if width == 45 { + assert!(output.contains("[Week]"), "{output}"); + assert!(output.contains("[Older]"), "{output}"); + } else { + assert!(output.contains("This week"), "{output}"); + assert!(output.contains("Older"), "{output}"); + } + } + } + + #[test] + fn volume_picker_shows_drives_and_windows_paths_read_normally() { + assert_eq!(readable_path(r"\\?\R:\"), r"R:\"); + assert_eq!(readable_path(r"\\?\UNC\server\share"), r"\\server\share"); + let temp = tempfile::tempdir().expect("tempdir"); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.screen = Screen::Volumes; + app.volumes = vec![disktree_core::space::Volume { + point: Path::new(r"R:\").to_path_buf(), + device: None, + space: Some(disktree_core::space::SpaceInfo { + total: 100, + free: 25, + available: 25, + }), + }]; + let mut terminal = + Terminal::new(TestBackend::new(80, 24)).expect("terminal"); + terminal + .draw(|frame| draw(frame, &app, &Palette::dark())) + .expect("draw"); + let output: String = terminal + .backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect(); + assert!(output.contains("SCAN A VOLUME")); + assert!(output.contains(r"R:\")); + assert!(output.contains("25 B free")); + } + + #[test] + fn empty_footer_and_insights_leave_room_for_scan_metadata() { + let temp = tempfile::tempdir().expect("tempdir"); + std::fs::write(temp.path().join("file"), b"small").expect("file"); + let tree = scan(temp.path(), ScanOptions::default()).expect("scan"); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.tree = Some(tree); + app.selected = Some(vec![0]); + app.progress.files = 1; + app.progress.dirs = 1; + app.scan_elapsed = Some(Duration::from_millis(1230)); + let mut terminal = + Terminal::new(TestBackend::new(120, 35)).expect("terminal"); + terminal + .draw(|frame| draw(frame, &app, &Palette::dark())) + .expect("draw"); + let output: String = terminal + .backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect(); + assert!(output.contains("Depth 3")); + assert!(output.contains("scan 2 entries · 1.2s")); + assert!(!output.contains("marked")); + assert!(!output.contains("projected")); + assert!(!output.contains("WORTH A LOOK")); + } + + #[test] + fn tile_sizes_keep_units_whole() { + assert_eq!( + fit_size_label("980KiB", 5, 2), + Some(("980K".to_string(), None)) + ); + assert_eq!( + fit_size_label("1.9MiB", 4, 2), + Some(("1.9M".to_string(), None)) + ); + assert_eq!( + fit_size_label("980KiB", 6, 1), + Some(("980KiB".to_string(), None)) + ); + assert_eq!( + fit_size_label("980KiB", 3, 2), + Some(("980".to_string(), Some("KiB".to_string()))) + ); + assert_eq!(fit_size_label("980KiB", 3, 1), None); + assert_eq!(fit_size_label("980KiB", 2, 2), None); + } + + #[test] + fn narrow_disk_line_keeps_the_free_value_whole() { + let temp = tempfile::tempdir().expect("tempdir"); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.device = Some("/dev/mapper/ubuntu--vg-ubuntu--lv".to_string()); + let line = compact_disk_line(&app, 34 * 1024 * 1024 * 1024, 43); + assert!(line.chars().count() <= 43); + assert!(line.starts_with("DISK /dev/")); + assert!(line.contains('…')); + assert!(line.ends_with(" · 34 GiB free")); + } + + #[test] + fn sliding_window_reveals_both_ends_with_right_edge_ellipsis() { + let value = "abcdefghij"; + assert_eq!(sliding_window(value, 5, Duration::ZERO).0, "abcd…"); + assert_eq!( + sliding_window(value, 5, Duration::from_millis(800)).0, + "bcde…" + ); + assert_eq!( + sliding_window(value, 5, Duration::from_millis(1800)).0, + "fghij" + ); + assert_eq!( + sliding_window(value, 5, Duration::from_millis(2600)).0, + "abcd…" + ); + assert_eq!( + sliding_window(value, 5, Duration::ZERO).1, + Some(Duration::from_millis(800)) + ); + assert_eq!( + sliding_window(value, 5, Duration::from_millis(800)).1, + Some(Duration::from_millis(200)) + ); + assert_eq!( + sliding_window(value, 5, Duration::from_millis(1800)).1, + Some(Duration::from_millis(800)) + ); + assert_eq!(end_clip("Mozilla", 5), "Mozi…"); + let long = format!("{}-final-name", "a".repeat(100)); + let tail = sliding_window(&long, 12, Duration::from_millis(5800)).0; + assert!(tail.ends_with("-final-name"), "{tail}"); + assert!(!tail.contains('…'), "{tail}"); + let unicode = "a👩‍💻bcdef"; + for step in 0..20 { + let label = + sliding_window(unicode, 5, Duration::from_millis(step * 200)).0; + assert!(text_width(&label) <= 5, "{label}"); + assert!(!label.contains('�'), "{label}"); + assert!(!label.contains('…') || label.ends_with('…'), "{label}"); + } + } + + #[test] + fn unselected_tile_border_uses_a_console_line_glyph() { + let mut buffer = Buffer::empty(Rect::new(0, 0, 6, 2)); + top_border(&mut buffer, Rect::new(0, 0, 6, 2), ACCENT); + let border: String = (0..6) + .map(|x| buffer[(x, 0)].symbol().to_string()) + .collect(); + assert_eq!(border, "──────"); + } + + #[test] + fn unselected_tile_and_worth_a_look_path_keep_moving() { + let temp = tempfile::tempdir().expect("tempdir"); + let long_name = "MozillaProfilesAndLocalApplicationCachesWithLongNames"; + for name in ["Selected", long_name] { + let directory = temp.path().join(name); + std::fs::create_dir(&directory).expect("mkdir"); + std::fs::write(directory.join("file"), vec![b'x'; 8192]) + .expect("file"); + } + let tree = scan( + temp.path(), + ScanOptions { + apparent_size: true, + ..ScanOptions::default() + }, + ) + .expect("scan"); + let mut app = + App::new(temp.path().to_path_buf(), ScanOptions::default()); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + let long_index = tree + .children + .iter() + .position(|node| node.name.as_ref() == long_name) + .expect("long node"); + let selected_index = usize::from(long_index == 0); + app.insights = vec![Candidate { + crumbs: vec![long_index], + bytes: 8192, + finding: Finding::Worktrees { + count: 1, + oldest_days: 40, + }, + }]; + app.tree = Some(tree); + app.selected = Some(vec![selected_index]); + app.set_viewport(120, 35); + let body = app.body_area(app.viewport()); + let (map, side, _) = App::split_explore(body); + let tile = app + .tiles(map) + .iter() + .find(|tile| { + matches!(&tile.kind, TileKind::Node { crumbs } if crumbs == &vec![long_index]) + }) + .map(|tile| App::tile_rect(tile, map)) + .expect("unselected tile"); + let worth_y = side.y + 15; + let mut terminal = + Terminal::new(TestBackend::new(120, 35)).expect("terminal"); + let row = + |terminal: &Terminal, x: u16, y: u16, width: u16| { + (x..x + width) + .map(|column| { + terminal + .backend() + .buffer() + .cell((column, y)) + .expect("cell") + .symbol() + .to_string() + }) + .collect::() + }; + app.set_marquee_elapsed_for_test(Duration::ZERO); + terminal + .draw(|frame| draw(frame, &app, &Palette::dark())) + .expect("initial draw"); + let first_tile = row(&terminal, tile.x, tile.y, tile.width); + let first_worth = row(&terminal, side.x, worth_y, side.width); + let reason = row(&terminal, side.x, worth_y + 1, side.width); + assert!(reason.contains("1 worktrees · oldest 40 days"), "{reason}"); + app.set_marquee_elapsed_for_test(Duration::from_millis(1200)); + terminal + .draw(|frame| draw(frame, &app, &Palette::dark())) + .expect("later draw"); + let later_tile = row(&terminal, tile.x, tile.y, tile.width); + let later_worth = row(&terminal, side.x, worth_y, side.width); + assert_ne!(first_tile, later_tile); + assert_ne!(first_worth, later_worth); + assert!(first_tile.contains("Mozilla"), "{first_tile}"); + assert!(first_worth.contains("Mozilla"), "{first_worth}"); + assert!(first_worth.contains('…'), "{first_worth}"); + assert!(later_worth.contains('…'), "{later_worth}"); + assert!(later_worth.contains("8.0KiB"), "{later_worth}"); + app.handle_key(crossterm::event::KeyEvent::new( + crossterm::event::KeyCode::Tab, + crossterm::event::KeyModifiers::NONE, + )); + assert!(app.marquee_elapsed() >= Duration::from_millis(1200)); + assert!(app.focused_marquee_elapsed() < Duration::from_millis(100)); + + app.screen = Screen::Insights; + for (width, height) in [(45, 13), (80, 24)] { + app.set_viewport(width, height); + app.set_marquee_elapsed_for_test(Duration::ZERO); + let mut narrow = Terminal::new(TestBackend::new(width, height)) + .expect("terminal"); + narrow + .draw(|frame| draw(frame, &app, &Palette::dark())) + .expect("insights draw"); + let insights: String = narrow + .backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect(); + assert!(insights.contains("WORTH A LOOK")); + assert!(insights.contains("8.0 KiB")); + assert!(insights.contains("oldest 40 days")); + assert!(insights.contains("Mozilla")); + } + } + + #[test] + fn narrow_list_uses_its_legend_row_for_a_fifth_entry() { + let temp = tempfile::tempdir().expect("tempdir"); + for (name, bytes) in [ + ("Media", 5000), + ("Documents", 4000), + ("Projects", 3000), + ("misc", 2000), + ("fifth", 1000), + ] { + let path = temp.path().join(name); + std::fs::create_dir(&path).expect("mkdir"); + let file = if name == "Media" { + path.join("photos/video.mp4") + } else { + path.join("file") + }; + std::fs::create_dir_all(file.parent().expect("parent")) + .expect("parent dir"); + std::fs::write(file, vec![b'x'; bytes]).expect("file"); + } + let options = ScanOptions { + apparent_size: true, + ..ScanOptions::default() + }; + let tree = scan(temp.path(), options).expect("scan"); + let mut app = App::new(temp.path().to_path_buf(), options); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.tree = Some(tree); + app.selected = Some(vec![0]); + let mut terminal = + Terminal::new(TestBackend::new(45, 13)).expect("terminal"); + terminal + .draw(|frame| draw(frame, &app, &Palette::dark())) + .expect("draw"); + let output: String = terminal + .backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect(); + let header: String = (0..45) + .map(|x| { + terminal + .backend() + .buffer() + .cell((x, 1)) + .expect("header cell") + .symbol() + .to_string() + }) + .collect(); + assert!(header.contains("t Size")); + assert!(header.contains("i Hidden")); + assert!(header.contains("d Apparent")); + assert!(output.contains("files")); + assert!(output.contains("dirs")); + assert!(output.contains("Media [Media]"), "{output}"); + assert!(output.contains("fifth [Other]"), "{output}"); + assert!(!output.contains("Reclaimable")); + } + + #[test] + fn nested_tiles_remain_visible_at_terminal_widths() { + let temp = tempfile::tempdir().expect("tempdir"); + for relative in + ["Projects/app/src/main.rs", "Projects/site/pages/index.html"] + { + let path = temp.path().join(relative); + std::fs::create_dir_all(path.parent().expect("parent")) + .expect("mkdir"); + std::fs::write(path, vec![b'x'; 8192]).expect("write"); + } + let options = ScanOptions { + apparent_size: true, + ..ScanOptions::default() + }; + let tree = scan(temp.path(), options).expect("scan"); + let mut app = App::new(temp.path().to_path_buf(), options); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.tree = Some(tree); + app.selected = Some(vec![0]); + + for (width, height) in [(80, 24), (120, 35)] { + let mut terminal = Terminal::new(TestBackend::new(width, height)) + .expect("terminal"); + terminal + .draw(|frame| draw(frame, &app, &Palette::dark())) + .expect("draw"); + let output: String = terminal + .backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect(); + assert!(output.contains("app"), "app tile at {width} columns"); + assert!(output.contains("site"), "site tile at {width} columns"); + if width >= 120 { + assert!(output.contains("src"), "third level at {width}"); + assert!(output.contains("pages"), "third level at {width}"); + } + } + } + + #[test] + fn compact_mosaic_shows_children_with_several_peer_directories() { + let temp = tempfile::tempdir().expect("tempdir"); + for relative in [ + "Projects/app/file", + ".cache/browser/file", + "Media/video/file", + "Documents/reports/file", + "Downloads/tmp/file", + ] { + let path = temp.path().join(relative); + std::fs::create_dir_all(path.parent().expect("parent")) + .expect("mkdir"); + std::fs::write(path, vec![b'x'; 8192]).expect("write"); + } + let options = ScanOptions { + apparent_size: true, + ..ScanOptions::default() + }; + let tree = scan(temp.path(), options).expect("scan"); + let mut app = App::new(temp.path().to_path_buf(), options); + if let Some(scan) = app.scan.take() { + scan.cancel(); + } + app.tree = Some(tree); + app.view_depth = 2; + app.set_viewport(80, 24); + let map = App::split_explore(app.body_area(app.viewport())).0; + let root = app.tree.as_ref().expect("tree"); + let visible: Vec<_> = app + .tiles(map) + .iter() + .filter_map(|tile| match &tile.kind { + TileKind::Node { crumbs } if crumbs.len() == 2 => { + root.resolve(crumbs).map(|node| node.name.to_string()) + } + _ => None, + }) + .collect(); + for child in ["app", "browser", "video", "reports", "tmp"] { + assert!(visible.iter().any(|name| name == child), "{visible:?}"); + } + } +} diff --git a/crates/disktree-cli/src/treemap/theme.rs b/crates/disktree-cli/src/treemap/theme.rs new file mode 100644 index 00000000..9b69e535 --- /dev/null +++ b/crates/disktree-cli/src/treemap/theme.rs @@ -0,0 +1,501 @@ +//! Terminal colors. Omarchy is an optional palette source, not a dependency. +//! +//! The renderer paints with a small reference palette, then maps its color +//! roles onto this palette. That keeps the mosaic's geometry and labels +//! independent of whether the terminal has an Omarchy theme. + +use std::fs; +use std::path::Path; +use std::time::{Duration, Instant}; + +use disktree_core::classify::Category; +use ratatui::buffer::Buffer; +use ratatui::style::Color; + +pub const BG: Color = Color::Rgb(18, 20, 32); +pub const PANEL: Color = Color::Rgb(28, 32, 50); +pub const TEXT: Color = Color::Rgb(213, 220, 239); +pub const MUTED: Color = Color::Rgb(132, 145, 179); +pub const ACCENT: Color = Color::Rgb(229, 184, 105); +pub const RED: Color = Color::Rgb(221, 111, 119); +const MARKED: Color = Color::Rgb(92, 43, 54); + +/// Automatic Omarchy/system colors, or an explicit terminal appearance. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)] +pub enum ThemeChoice { + #[default] + Auto, + Dark, + Light, +} + +/// What the active terminal colors mean to the renderer. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Palette { + background: Color, + panel: Color, + text: Color, + muted: Color, + accent: Color, + red: Color, + categories: [Color; 9], + light: bool, +} + +impl Palette { + pub(crate) const fn dark() -> Self { + Self { + background: BG, + panel: PANEL, + text: TEXT, + muted: MUTED, + accent: ACCENT, + red: RED, + categories: [ + base_category_color(Category::Code), + base_category_color(Category::AgentScratch), + base_category_color(Category::Toolchain), + base_category_color(Category::Synced), + base_category_color(Category::Git), + base_category_color(Category::Media), + base_category_color(Category::Documents), + base_category_color(Category::Cache), + base_category_color(Category::Other), + ], + light: false, + } + } + + const fn light() -> Self { + Self { + background: Color::Rgb(255, 252, 240), + panel: Color::Rgb(234, 231, 218), + text: Color::Rgb(26, 29, 38), + muted: Color::Rgb(100, 104, 113), + accent: Color::Rgb(38, 90, 161), + red: Color::Rgb(169, 53, 58), + categories: [ + Color::Rgb(48, 95, 176), + Color::Rgb(170, 90, 41), + Color::Rgb(49, 128, 87), + Color::Rgb(35, 119, 142), + Color::Rgb(171, 65, 81), + Color::Rgb(118, 71, 153), + Color::Rgb(100, 103, 111), + Color::Rgb(141, 112, 36), + Color::Rgb(126, 128, 132), + ], + light: true, + } + } + + fn from_omarchy(source: &str) -> Option { + let doc: toml::Value = source.parse().ok()?; + let table = doc.as_table()?; + let background = color_key(table, &["background", "bg", "color0"])?; + let text = color_key(table, &["foreground", "fg", "color7"])?; + let light = match table.get("mode").and_then(toml::Value::as_str) { + Some("light") => true, + Some("dark") => false, + _ => is_light(background), + }; + let fallback = if light { Self::light() } else { Self::dark() }; + let panel = color_key( + table, + &["lighter_background", "lighter_bg", "dark_background"], + ) + .unwrap_or_else(|| mix(background, text, 0.07)); + let muted = color_key(table, &["dark_foreground", "dark_fg", "color8"]) + .unwrap_or_else(|| mix(background, text, 0.55)); + let accent = color_key( + table, + if light { + &["accent", "blue", "color4"] + } else { + &["yellow", "color3", "accent"] + }, + ) + .unwrap_or(fallback.accent); + let red = color_key(table, &["red", "color1"]).unwrap_or(fallback.red); + let pairs: [&[&str]; 9] = [ + &["blue", "color4"], + &["orange", "color11", "color3"], + &["green", "color2"], + &["cyan", "color6"], + &["red", "color1"], + &["magenta", "color5"], + &["light_foreground", "light_fg", "color7"], + &["yellow", "color3"], + &["muted", "color8"], + ]; + let categories = std::array::from_fn(|index| { + color_key(table, pairs[index]).unwrap_or(fallback.categories[index]) + }); + Some(Self { + background, + panel, + text, + muted, + accent, + red, + categories, + light, + }) + } + + pub fn apply(&self, buffer: &mut Buffer) { + let area = buffer.area; + for y in area.y..area.bottom() { + for x in area.x..area.right() { + if let Some(cell) = buffer.cell_mut((x, y)) { + cell.fg = self.map(cell.fg); + cell.bg = self.map(cell.bg); + } + } + } + } + + fn map(&self, source: Color) -> Color { + for (from, to) in [ + (BG, self.background), + (PANEL, self.panel), + (TEXT, self.text), + (MUTED, self.muted), + (ACCENT, self.accent), + (RED, self.red), + ( + MARKED, + mix( + self.background, + self.red, + if self.light { 0.18 } else { 0.4 }, + ), + ), + ] { + if source == from { + return to; + } + } + for (index, category) in Category::LEGEND + .into_iter() + .chain([Category::Other]) + .enumerate() + { + let base = base_category_color(category); + let mapped = self.categories[index]; + if source == base { + return mapped; + } + if source == shade(base, 0.68) { + return mix(self.background, mapped, 0.6); + } + for depth in 0..3 { + let factor = 0.05_f32.mul_add(depth as f32, 0.32); + if source == shade(base, factor) { + let amount = if self.light { + 0.03_f32.mul_add(depth as f32, 0.15) + } else { + 0.04_f32.mul_add(depth as f32, 0.27) + }; + return mix(self.background, mapped, amount); + } + } + } + for bucket in 0..AGE_LABELS.len() { + let base = base_age_color(bucket); + let mapped = mix( + self.accent, + self.muted, + bucket as f32 / (AGE_LABELS.len() - 1) as f32, + ); + if source == base { + return mapped; + } + if source == shade(base, 0.68) { + return mix(self.background, mapped, 0.6); + } + for depth in 0..3 { + let factor = 0.05_f32.mul_add(depth as f32, 0.32); + if source == shade(base, factor) { + let amount = if self.light { + 0.03_f32.mul_add(depth as f32, 0.15) + } else { + 0.04_f32.mul_add(depth as f32, 0.27) + }; + return mix(self.background, mapped, amount); + } + } + } + source + } +} + +/// Read the optional current theme periodically. Omarchy swaps a symlink +/// when its theme changes, so reading the current path also catches swaps. +#[derive(Debug)] +pub struct ThemeState { + choice: ThemeChoice, + palette: Palette, + last_check: Instant, +} + +impl ThemeState { + pub fn new(choice: ThemeChoice) -> Self { + let mut state = Self { + choice, + palette: Palette::dark(), + last_check: Instant::now(), + }; + let _ = state.refresh(); + state + } + + pub const fn palette(&self) -> &Palette { + &self.palette + } + + pub fn tick(&mut self) -> bool { + if self.last_check.elapsed() < Duration::from_secs(2) { + return false; + } + self.refresh() + } + + fn refresh(&mut self) -> bool { + let next = match self.choice { + ThemeChoice::Dark => Palette::dark(), + ThemeChoice::Light => Palette::light(), + ThemeChoice::Auto => std::env::home_dir() + .as_deref() + .and_then(load_omarchy) + .unwrap_or_else(system_fallback), + }; + self.last_check = Instant::now(); + if self.palette == next { + return false; + } + self.palette = next; + true + } +} + +fn load_omarchy(home: &Path) -> Option { + let primary = home.join(".local/state/omarchy/current"); + let legacy = home.join(".config/omarchy/current"); + let active = if fs::symlink_metadata(&primary).is_ok() { + primary + } else { + legacy + }; + let source = fs::read_to_string(active.join("theme/colors.toml")).ok()?; + Palette::from_omarchy(&source) +} + +fn color_key(table: &toml::value::Table, names: &[&str]) -> Option { + names.iter().find_map(|name| { + table + .get(*name) + .and_then(toml::Value::as_str) + .and_then(hex_color) + }) +} + +fn hex_color(source: &str) -> Option { + let hex = source.strip_prefix('#')?; + let rgb = hex.get(..6)?; + if hex.len() != 6 && hex.len() != 8 { + return None; + } + Some(Color::Rgb( + u8::from_str_radix(&rgb[0..2], 16).ok()?, + u8::from_str_radix(&rgb[2..4], 16).ok()?, + u8::from_str_radix(&rgb[4..6], 16).ok()?, + )) +} + +fn system_fallback() -> Palette { + if terminal_wants_light().unwrap_or_else(system_wants_light) { + Palette::light() + } else { + Palette::dark() + } +} + +fn terminal_wants_light() -> Option { + let value = std::env::var("COLORFGBG").ok()?; + let background = value.rsplit([';', ':']).next()?.parse::().ok()?; + Some(background == 7 || background >= 15) +} + +#[cfg(target_os = "macos")] +fn system_wants_light() -> bool { + std::process::Command::new("defaults") + .args(["read", "-g", "AppleInterfaceStyle"]) + .output() + .is_ok_and(|result| { + !result.status.success() || result.stdout != b"Dark\n" + }) +} + +#[cfg(windows)] +fn system_wants_light() -> bool { + std::process::Command::new("reg") + .args([ + "query", + r"HKCU\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", + "/v", + "AppsUseLightTheme", + ]) + .output() + .is_ok_and(|result| { + result.status.success() + && String::from_utf8_lossy(&result.stdout).contains("0x1") + }) +} + +#[cfg(not(any(target_os = "macos", windows)))] +fn system_wants_light() -> bool { + std::env::var("GTK_THEME") + .is_ok_and(|theme| theme.to_ascii_lowercase().contains("light")) +} + +fn is_light(color: Color) -> bool { + let Color::Rgb(r, g, b) = color else { + return false; + }; + u32::from(r) * 299 + u32::from(g) * 587 + u32::from(b) * 114 >= 128_000 +} + +fn mix(from: Color, to: Color, amount: f32) -> Color { + let (Color::Rgb(fr, fg, fb), Color::Rgb(tr, tg, tb)) = (from, to) else { + return from; + }; + let channel = |start: u8, end: u8| { + (f32::from(end) - f32::from(start)) + .mul_add(amount, f32::from(start)) + .round() as u8 + }; + Color::Rgb(channel(fr, tr), channel(fg, tg), channel(fb, tb)) +} + +pub const fn base_category_color(category: Category) -> Color { + match category { + Category::Code => Color::Rgb(93, 139, 212), + Category::AgentScratch => Color::Rgb(208, 141, 93), + Category::Toolchain => Color::Rgb(79, 182, 144), + Category::Synced => Color::Rgb(83, 170, 193), + Category::Git => Color::Rgb(197, 93, 116), + Category::Media => Color::Rgb(151, 101, 194), + Category::Documents => Color::Rgb(155, 163, 180), + Category::Cache => Color::Rgb(197, 169, 83), + Category::Other => Color::Rgb(112, 123, 149), + } +} + +/// The GUI's five age bands, newest first. +pub const AGE_LABELS: [&str; 5] = [ + "This week", + "This month", + "Six months", + "This year", + "Older", +]; + +pub const fn age_bucket(modified: i64, scanned_at: i64) -> Option { + if modified <= 0 { + return None; + } + let days = scanned_at.saturating_sub(modified) / 86_400; + Some(match days { + ..=7 => 0, + 8..=30 => 1, + 31..=182 => 2, + 183..=365 => 3, + _ => 4, + }) +} + +pub const fn base_age_color(bucket: usize) -> Color { + match bucket { + 0 => Color::Rgb(230, 186, 106), + 1 => Color::Rgb(203, 177, 122), + 2 => Color::Rgb(176, 163, 138), + 3 => Color::Rgb(151, 150, 151), + _ => Color::Rgb(134, 140, 150), + } +} + +pub fn shade(color: Color, factor: f32) -> Color { + let Color::Rgb(r, g, b) = color else { + return BG; + }; + Color::Rgb( + (f32::from(r) * factor) as u8, + (f32::from(g) * factor) as u8, + (f32::from(b) * factor) as u8, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn semantic_dark_and_light_themes_map_roles() { + let dark = Palette::from_omarchy( + "mode = 'dark'\nbackground = '#1a1b26'\nforeground = '#a9b1d6'\n\ + yellow = '#e0af68'\nblue = '#7aa2f7'\n", + ) + .expect("theme"); + assert!(!dark.light); + assert_eq!(dark.map(ACCENT), Color::Rgb(224, 175, 104)); + assert_eq!( + dark.map(base_category_color(Category::Code)), + Color::Rgb(122, 162, 247) + ); + let light = Palette::from_omarchy( + "mode = 'light'\nbackground = '#FFFCF0'\nforeground = '#100F0F'\n\ + accent = '#205EA6'\n", + ) + .expect("theme"); + assert!(light.light); + assert_eq!(light.map(BG), Color::Rgb(255, 252, 240)); + assert_eq!(light.map(TEXT), Color::Rgb(16, 15, 15)); + assert_eq!(light.map(ACCENT), Color::Rgb(32, 94, 166)); + } + + #[test] + fn ansi_theme_and_legacy_location_work() { + let temp = tempfile::tempdir().expect("tempdir"); + let file = temp + .path() + .join(".config/omarchy/current/theme/colors.toml"); + fs::create_dir_all(file.parent().expect("parent")).expect("mkdir"); + fs::write( + &file, + "color0 = '#101010'\ncolor7 = '#eeeeee'\ncolor4 = '#8899cc'\n", + ) + .expect("write"); + let palette = load_omarchy(temp.path()).expect("legacy theme"); + assert_eq!(palette.map(BG), Color::Rgb(16, 16, 16)); + assert_eq!( + palette.map(base_category_color(Category::Code)), + Color::Rgb(136, 153, 204) + ); + let primary = temp.path().join(".local/state/omarchy/current"); + fs::create_dir_all(&primary).expect("primary"); + assert!(load_omarchy(temp.path()).is_none()); + } + + #[test] + fn invalid_color_does_not_create_a_partial_theme() { + assert!( + Palette::from_omarchy( + "background = 'oops'\nforeground = '#ffffff'" + ) + .is_none() + ); + assert_eq!(hex_color("#11223344"), Some(Color::Rgb(17, 34, 51))); + assert_eq!(hex_color("#11GG33"), None); + } +} diff --git a/crates/disktree-cli/src/treemap/windows_console.rs b/crates/disktree-cli/src/treemap/windows_console.rs new file mode 100644 index 00000000..c917af36 --- /dev/null +++ b/crates/disktree-cli/src/treemap/windows_console.rs @@ -0,0 +1,57 @@ +//! Set the code pages used by a classic Windows console while the TUI runs. + +#![allow( + unsafe_code, + reason = "Win32 console code-page calls have no safe standard-library wrapper" +)] + +use std::io; + +use windows_sys::Win32::System::Console::{ + GetConsoleCP, GetConsoleOutputCP, SetConsoleCP, SetConsoleOutputCP, +}; + +const UTF8: u32 = 65_001; + +#[derive(Debug)] +pub struct Utf8Console { + input: u32, + output: u32, +} + +impl Utf8Console { + pub fn enter() -> io::Result { + // SAFETY: both calls take no arguments and read this process's console. + let (input, output) = unsafe { (GetConsoleCP(), GetConsoleOutputCP()) }; + if input == 0 || output == 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: 65001 is the documented UTF-8 code page identifier. + if input != UTF8 && unsafe { SetConsoleCP(UTF8) } == 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: 65001 is the documented UTF-8 code page identifier. + if output != UTF8 && unsafe { SetConsoleOutputCP(UTF8) } == 0 { + let error = io::Error::last_os_error(); + if input != UTF8 { + // SAFETY: `input` was read from this console above. + unsafe { SetConsoleCP(input) }; + } + return Err(error); + } + Ok(Self { input, output }) + } +} + +impl Drop for Utf8Console { + fn drop(&mut self) { + if self.output != UTF8 { + // SAFETY: `output` was read from this console on entry. + unsafe { SetConsoleOutputCP(self.output) }; + } + if self.input != UTF8 { + // SAFETY: `input` was read from this console on entry. + unsafe { SetConsoleCP(self.input) }; + } + } +} diff --git a/crates/disktree-core/src/filter.rs b/crates/disktree-core/src/filter.rs index fb717a9a..74e85eaa 100644 --- a/crates/disktree-core/src/filter.rs +++ b/crates/disktree-core/src/filter.rs @@ -109,8 +109,10 @@ fn visit( total.0 = child.bytes.saturating_add(total.0); total.1 += child.files; } else if !child.children.is_empty() { + let count_before = matches.count; let (bytes, files) = visit(child, crumbs, matches); - if bytes > 0 || files > 0 { + // An empty matching directory still needs a reachable ancestor. + if matches.count > count_before { matches .keep .insert(crumbs.clone(), Keep::Partial { bytes, files }); @@ -242,6 +244,30 @@ mod tests { assert!(found.keep.is_empty()); } + #[test] + fn a_nested_empty_directory_keeps_its_ancestors() { + let mut root = dir( + "root", + vec![ + dir("parent", vec![dir("empty-match", vec![])]), + file("unrelated", 10), + ], + ); + aggregate(&mut root, Metric::Bytes); + let found = filter(&root, &[], "empty-match").expect("needle"); + let parent = crumbs_of(&root, &["parent"]); + let empty = crumbs_of(&root, &["parent", "empty-match"]); + + assert_eq!(found.count, 1); + assert_eq!((found.bytes, found.files), (0, 0)); + assert_eq!( + found.keep(&parent), + Some(Keep::Partial { bytes: 0, files: 0 }) + ); + assert_eq!(found.keep(&empty), Some(Keep::Whole)); + assert_eq!(found.keep(&crumbs_of(&root, &["unrelated"])), None); + } + #[test] fn case_is_ignored_without_allocating() { assert!(contains_ignoring_case("Cargo.TOML", "toml")); diff --git a/crates/disktree-core/src/insights.rs b/crates/disktree-core/src/insights.rs index 7b2b3396..e9649c0a 100644 --- a/crates/disktree-core/src/insights.rs +++ b/crates/disktree-core/src/insights.rs @@ -14,6 +14,9 @@ const DAY: i64 = 86_400; /// An experiment untouched this long is worth a look. pub const STALE_DAYS: i64 = 30; +/// Maximum findings shown by either interface. +pub const INSIGHT_LIMIT: usize = 6; + /// Smaller than this is not worth a line. const MIN_BYTES: u64 = 64 * 1024 * 1024; diff --git a/crates/disktree-core/src/treemap.rs b/crates/disktree-core/src/treemap.rs index 993a5dbf..e55ba04a 100644 --- a/crates/disktree-core/src/treemap.rs +++ b/crates/disktree-core/src/treemap.rs @@ -122,6 +122,8 @@ pub struct LayoutOptions { /// open. A directory drawn closed has no band: its label sits in its /// corner, over nothing but its own fill. pub header_inner: f32, + /// Width needed to reserve a readable header and draw children beneath it. + pub min_header_width: f32, } impl Default for LayoutOptions { @@ -134,6 +136,7 @@ impl Default for LayoutOptions { padding_outer: 3.0, header: 20.0, header_inner: 15.0, + min_header_width: 44.0, } } } @@ -321,7 +324,7 @@ fn header_band( options.header_inner }; let body = rect.h - height; - if rect.w < 44.0 || body < options.min_tile * 3.0 { + if rect.w < options.min_header_width || body < options.min_tile * 3.0 { return None; } Some(Rect::new(rect.x, rect.y, rect.w, height)) @@ -584,6 +587,23 @@ mod tests { assert_eq!(hit_tile.crumbs(), &[0]); } + #[test] + fn a_narrower_presentation_can_keep_a_header() { + let root = dir("root", vec![dir("big", vec![file("inside", 100)])]); + let area = Rect::new(0.0, 0.0, 30.0, 100.0); + let default = + layout(&root, &[], area, Metric::Bytes, &LayoutOptions::default()); + assert_eq!(default.len(), 1, "GUI width keeps this tile whole"); + + let options = LayoutOptions { + min_header_width: 20.0, + ..LayoutOptions::default() + }; + let narrow = layout(&root, &[], area, Metric::Bytes, &options); + assert_eq!(narrow.len(), 2, "terminal width shows the child"); + assert!(narrow[0].header.is_some()); + } + #[test] fn a_tile_without_room_for_a_header_stays_whole() { let root = dir("root", vec![dir("big", vec![file("inside", 100)])]); diff --git a/crates/disktree-scanner/src/windows.rs b/crates/disktree-scanner/src/windows.rs index 51762ec9..d422d1cf 100644 --- a/crates/disktree-scanner/src/windows.rs +++ b/crates/disktree-scanner/src/windows.rs @@ -36,7 +36,7 @@ use windows_sys::Win32::Storage::FileSystem::{ FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, FileIdExtdDirectoryInfo, FindFirstVolumeW, FindNextVolumeW, FindVolumeClose, GetDiskFreeSpaceExW, GetFileInformationByHandleEx, - GetVolumeInformationW, GetVolumePathNameW, + GetLogicalDriveStringsW, GetVolumeInformationW, GetVolumePathNameW, GetVolumePathNamesForVolumeNameW, SYNCHRONIZE, }; @@ -534,11 +534,10 @@ pub fn volume_root(path: &Path) -> Option { Some(PathBuf::from(OsString::from_wide(&root[..end]))) } -/// Every place a volume is mounted: drive roots such as `D:\`, and folders -/// a volume is mounted on, such as `C:\Data\Disk2\`. The mount table -/// Windows has in place of `/proc/self/mounts`. +/// Every drive letter and volume mount point. Logical drives include mapped +/// network letters that the local volume mount enumeration does not list. pub fn mount_points() -> Vec { - let mut points = Vec::new(); + let mut points = logical_drive_roots(); // A volume GUID path, `\\?\Volume{…}\`, is 49 units with its NUL. let mut volume = [0_u16; 64]; let length = u32::try_from(volume.len()).unwrap_or(u32::MAX); @@ -548,7 +547,11 @@ pub fn mount_points() -> Vec { return points; } loop { - points.extend(volume_paths(&volume)); + for point in volume_paths(&volume) { + if !points.iter().any(|known| same(known, &point)) { + points.push(point); + } + } // SAFETY: `find` is a live search handle, and `volume` is writable // for the length passed. if unsafe { FindNextVolumeW(find, volume.as_mut_ptr(), length) } == 0 { @@ -560,6 +563,33 @@ pub fn mount_points() -> Vec { points } +fn logical_drive_roots() -> Vec { + // SAFETY: a zero length asks for the buffer size without writing data. + let needed = unsafe { GetLogicalDriveStringsW(0, std::ptr::null_mut()) }; + let Some(length) = + usize::try_from(needed).ok().filter(|&length| length > 0) + else { + return Vec::new(); + }; + let mut names = vec![0_u16; length.saturating_add(1)]; + let Ok(capacity) = u32::try_from(names.len()) else { + return Vec::new(); + }; + // SAFETY: `names` is writable for `capacity` UTF-16 units. + let copied = + unsafe { GetLogicalDriveStringsW(capacity, names.as_mut_ptr()) }; + if copied == 0 + || usize::try_from(copied).unwrap_or(usize::MAX) >= names.len() + { + return Vec::new(); + } + names + .split(|&unit| unit == 0) + .take_while(|name| !name.is_empty()) + .map(|name| PathBuf::from(OsString::from_wide(name))) + .collect() +} + /// The paths the volume named by the NUL-terminated `volume` is mounted at. fn volume_paths(volume: &[u16]) -> Vec { let mut names = vec![0_u16; 1024];