diff --git a/AGENTS.md b/AGENTS.md index a567ce80..12414c65 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,6 +58,9 @@ and `cargo build --release` directly; CI runs the gate on both systems. press keys — so a screen that panics while painting fails a test. * **Never delete anything outside a marked path.** See `removal.rs`; the guards are load-bearing and are covered by tests. +* **A remote scan is read-only.** Its tree holds another machine's paths, and + the same path may exist here. While `Disktree::remote` is set nothing may + mark, remove, reveal or probe a path; see `Disktree::set_remote`. ## Invariants @@ -120,6 +123,12 @@ and `cargo build --release` directly; CI runs the gate on both systems. | what Windows lists, measures and compares differently | `crates/disktree-core/src/windows.rs` — `unsafe` for Win32 | | reading a whole NTFS drive from its file table | `crates/disktree-core/src/mft.rs` | | a key, a screen transition, a mark | `crates/disktree-app/src/state.rs` | +| a view choice kept between launches | `crates/disktree-app/src/settings.rs` | +| which theme is in force | `crates/disktree-app/src/appearance.rs` | +| a Start menu or desktop shortcut, on Windows | `crates/disktree-app/src/shortcut.rs` | +| what a filter matches: name, kind, size | `crates/disktree-core/src/filter.rs` | +| listing another machine over SSH | `crates/disktree-core/src/remote.rs` | +| GiB or GB, and how a size is written | `crates/disktree-core/src/size.rs` | | spacing, type and size | `crates/disktree-app/src/ui.rs` — tokens only, no `px` in layout | | the mosaic's painting or labels | `crates/disktree-app/src/treemap_view.rs` | | layout of a screen | `crates/disktree-app/src/views.rs` | diff --git a/README.md b/README.md index 80442695..5f456fe7 100644 --- a/README.md +++ b/README.md @@ -136,12 +136,28 @@ disktree --help # options: apparent size, follow links, skip hidden, … ### The screen - **Top:** the trail from `/`, then what is measured — **Size**, **Files** or - **Age**, **Hidden files**, **Apparent size**, and the depth drawn. In the + **Age**, **Hidden files**, **Apparent size**, and the depth drawn; at the + end, the settings (theme, deeper levels, and on Windows a shortcut on the + Start menu or the desktop) and the way to GitHub. The disk button beside + the name opens a page of every disk, with its name, size and room. Click + the empty space beside the trail, or press `ctrl l`, and the trail becomes + a text field holding the path: copy it, or type or paste another and press + Enter to go there. In the tree a crumb goes there, and its ▾ lists its siblings, largest first with their share and size, to jump sideways (arrows and Enter work too). Above the scanned root a crumb is dimmer, and clicking it widens the scan to there (see below). -- **Under it:** the scan totals, the filter when one is typed, and the legend. +- **Under it:** the scan totals, **Filter** and **Name**, and the legend. + Filter narrows the mosaic to the kinds of data that are ticked, any number + of them, and to files between a **Min** and a **Max** size, each typed + with its own unit, up to the terabyte, and emptied by the cross in its + field. The button counts what is in force and the menu reads it back as + a sentence. The menu works from the keyboard: Tab and Shift+Tab walk it, + Space ticks, Enter applies, Esc closes. Name is the filter `/` opens, + and Esc there drops the name alone. The two combine. The settings page + also chooses + whether sizes read in GiB (1024s) or GB (1000s), and says which version + and build this is. - **Mosaic:** colour is the *kind* of data — code, agent scratch, toolchains, synced files, git, media, documents, caches — at one muted level, lighter with depth. A diagonal hatch is space that can be had back @@ -226,8 +242,10 @@ and shows how much free space was actually gained. | `esc` while scanning | stop the scan | | `v` | scan another mounted volume | | `ctrl o` (`⌘O` on macOS) | choose another directory to scan | +| `ctrl l` (`⌘L` on macOS) | type or paste a path to go to; `esc` puts the trail back | | `g` | the whole disk | | `p` | show or hide the selection line | +| `T` | the system's theme, light or dark | | `o` | show it in Finder, File Explorer or the file manager | | right-click | show that tile in Finder, File Explorer or the file manager | | `?` | every key | @@ -238,6 +256,18 @@ rescan, ⌘[ and ⌘] for back and forward, and ⌘Q, ⌘H and ⌘W (closing the window quits); other ⌘ chords are left to the system. On Linux and Windows the same work with ctrl, with F5 to rescan too. +Every hint in the bar along the bottom is also a button for its key. The +key list, the settings and the page of disks close with `esc`, their Close +button, or a click outside them. + +The depth stops at 6 levels unless the settings allow 10: deeper draws many +more tiles, most too small to read, and is slow on a whole disk. + +The theme, the depth, Size / Files / Age, hidden files, apparent size and +the panel's width are remembered between launches, in `disktree/settings` +beside the Power Efficiency preset; an option on the command line still +overrules what was saved. + On the review screen: `m` trash, `p` permanent, `!` unmark all, `enter` commits, `esc` goes back. Or hand the list on instead of acting on it: `s` saves it as a text file, one path per line, and `a` copies a prompt for a @@ -270,11 +300,30 @@ and removes duplicate hardlinks. ## Switching volumes -Press `v` (or click **Volumes** beside the disk name in the side panel) to -bring up the volume picker. It lists every candidate volume mounted on the -system together with its free space, ordered fullest first, filtering out -pseudo-filesystems and duplicate btrfs/APFS mount points. Selecting any -entry resets the scan root directly to that volume. +Press `v`, or click the disk's name or **Volumes** beside it in the side +panel, to bring up the volume picker. When the scan is of a whole volume, +its crumb in the trail (`C:\` or `/`) opens it too. It lists every +candidate volume mounted on the system together with its free space, by +name, filtering out pseudo-filesystems and duplicate btrfs/APFS mount +points. Selecting any entry resets the scan root directly to that volume. + +## Another machine, over SSH + +The page of disks has an address field: `user@host:/path`, or +`ssh://user@host:2222/path`, scans that directory on another machine. The +path field (`ctrl l`) takes the same address. The other machine runs +`find` and the tree is built from what it lists, so nothing is installed +there, but it has to have GNU `find`: a Linux machine, not macOS or a BSD. + +The connection is your own `ssh`: its keys, agent, config and +`known_hosts`. disktree never asks for a password, and a host it has not +seen before is refused rather than trusted, so connect once from a +terminal first. + +A remote scan is **read-only**. Its paths are the other machine's, and the +same path may exist on this one, so nothing can be marked or removed, and +the file manager, git and the free-space meter are off until a local +directory is scanned again. ## The whole disk diff --git a/crates/disktree-app/build.rs b/crates/disktree-app/build.rs index b3e6868e..ce98de76 100644 --- a/crates/disktree-app/build.rs +++ b/crates/disktree-app/build.rs @@ -2,6 +2,8 @@ fn main() { use std::{env, fs, path::PathBuf, process::Command}; + build_number(); + let icon = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()) .join("../../assets/disktree.ico") .canonicalize() @@ -62,4 +64,38 @@ fn main() { } #[cfg(not(windows))] -fn main() {} +fn main() { + build_number(); +} + +/// Which build this is, for the settings page: the number of commits it +/// was built from and the last one's short name, `412.6c8d4ce`. A build +/// from a source archive has no history to count and says so. +fn build_number() { + let git = |args: &[&str]| { + std::process::Command::new("git") + .args(args) + .output() + .ok() + .filter(|output| output.status.success()) + .and_then(|output| String::from_utf8(output.stdout).ok()) + .map(|text| text.trim().to_owned()) + .filter(|text| !text.is_empty()) + }; + let build = git(&["rev-list", "--count", "HEAD"]) + .zip(git(&["rev-parse", "--short", "HEAD"])) + .map_or_else( + || "unknown".to_owned(), + |(count, commit)| format!("{count}.{commit}"), + ); + println!("cargo:rustc-env=DISKTREE_BUILD={build}"); + // Every commit, checkout and merge appends to this log, so the number + // is never left over from an older one. git is asked where it is: in + // a worktree it is not under `.git` here. Only a log that exists is + // named, since cargo takes a missing one as changed on every build. + if let Some(log) = git(&["rev-parse", "--git-path", "logs/HEAD"]) + .filter(|log| std::path::Path::new(log).exists()) + { + println!("cargo:rerun-if-changed={log}"); + } +} diff --git a/crates/disktree-app/src/appearance.rs b/crates/disktree-app/src/appearance.rs index 274bce65..ade02843 100644 --- a/crates/disktree-app/src/appearance.rs +++ b/crates/disktree-app/src/appearance.rs @@ -4,12 +4,84 @@ //! are none, and gpui-omarchy would then stay on its dark default whatever //! the system is set to; there the app follows the system appearance instead, //! with the crate's own dark and light palettes, and switches when it does. +//! +//! Either can be overruled: a [`ThemeChoice`] of light or dark stays put +//! whatever the desktop does, until the choice goes back to the system's. use std::path::Path; use gpui_kit::{App, Window, WindowAppearance}; use gpui_omarchy::Theme; +/// Whose palette is drawn: the system's, or one picked here. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ThemeChoice { + /// The Omarchy theme, or the system's light or dark setting. + #[default] + System, + Light, + Dark, +} + +impl ThemeChoice { + pub const ALL: [Self; 3] = [Self::System, Self::Light, Self::Dark]; + + pub const fn key(self) -> &'static str { + match self { + Self::System => "system", + Self::Light => "light", + Self::Dark => "dark", + } + } + + pub const fn name(self) -> &'static str { + match self { + Self::System => "System", + Self::Light => "Light", + Self::Dark => "Dark", + } + } + + pub fn parse(value: &str) -> Option { + Self::ALL.into_iter().find(|choice| choice.key() == value) + } + + /// The choice after this one, for a control that steps through them. + #[must_use] + pub const fn next(self) -> Self { + match self { + Self::System => Self::Light, + Self::Light => Self::Dark, + Self::Dark => Self::System, + } + } +} + +/// The choice in force, where the appearance observer can see it: a system +/// that turns dark at dusk must not repaint a window that was told light. +struct Chosen(ThemeChoice); + +impl gpui_kit::Global for Chosen {} + +/// Draw with `choice` from now on. `appearance` is the window's, used when +/// the choice is the system's and there is no Omarchy theme to follow. +pub fn choose( + choice: ThemeChoice, + appearance: WindowAppearance, + home: Option<&Path>, + cx: &mut App, +) { + cx.set_global(Chosen(choice)); + match choice { + ThemeChoice::Light => Theme::flexoki_light().apply(cx), + ThemeChoice::Dark => Theme::tokyo_night().apply(cx), + ThemeChoice::System if follows_system(home) => apply(appearance, cx), + // Back to the Omarchy theme files, which an explicit theme stopped + // watching. + ThemeChoice::System => Theme::follow_system(cx), + } +} + /// Whether the system appearance, rather than an Omarchy theme, decides the /// colours: unless an Omarchy theme is installed, on macOS and Windows, and /// on a Linux desktop that states a preference. @@ -52,7 +124,14 @@ pub fn apply(appearance: WindowAppearance, cx: &mut App) { /// Follow `window`'s appearance from now on. pub fn follow(window: &Window) { window - .observe_window_appearance(|window, cx| apply(window.appearance(), cx)) + .observe_window_appearance(|window, cx| { + let chosen = cx + .try_global::() + .map_or(ThemeChoice::System, |chosen| chosen.0); + if chosen == ThemeChoice::System { + apply(window.appearance(), cx); + } + }) .detach(); } @@ -60,6 +139,19 @@ pub fn follow(window: &Window) { mod tests { use super::*; + #[test] + fn the_theme_control_steps_through_every_choice_and_back() { + let mut choice = ThemeChoice::default(); + for expected in + [ThemeChoice::Light, ThemeChoice::Dark, ThemeChoice::System] + { + choice = choice.next(); + assert_eq!(choice, expected); + assert_eq!(ThemeChoice::parse(choice.key()), Some(choice)); + } + assert_eq!(ThemeChoice::parse("plaid"), None); + } + #[test] fn a_linux_desktop_is_followed_only_if_it_states_a_preference() { let native = cfg!(any(target_os = "macos", windows)); diff --git a/crates/disktree-app/src/main.rs b/crates/disktree-app/src/main.rs index 92fa2f76..52b96396 100644 --- a/crates/disktree-app/src/main.rs +++ b/crates/disktree-app/src/main.rs @@ -17,6 +17,8 @@ mod git; mod marks; mod palette; mod power; +mod settings; +mod shortcut; mod state; #[cfg(test)] mod tests; @@ -100,7 +102,15 @@ fn run() -> Result<()> { eprintln!("Cannot load Power Efficiency: {error}; using Balanced"); power::PowerEfficiency::default() }); - let args = parse_args_with_power(std::env::args_os().skip(1), saved)?; + let settings_path = settings::path(); + let chosen = settings_path + .as_deref() + .map_or_else(|| Ok(settings::Settings::default()), settings::load) + .unwrap_or_else(|error| { + eprintln!("Cannot load settings: {error}; using the defaults"); + settings::Settings::default() + }); + let args = parse_args_with(std::env::args_os().skip(1), saved, &chosen)?; // When the app executable is reached through the command-line symlink, // cmux sends SIGTERM to its foreground process group as AppKit takes @@ -136,8 +146,15 @@ fn run() -> Result<()> { app_menu::install(cx); let home = std::env::home_dir(); let native_look = appearance::follows_system(home.as_deref()); - if native_look { - appearance::apply(cx.window_appearance(), cx); + // An Omarchy theme is already followed; anything else is put + // in force here, a saved light or dark over either. + if native_look || chosen.theme != appearance::ThemeChoice::System { + appearance::choose( + chosen.theme, + cx.window_appearance(), + home.as_deref(), + cx, + ); } let options = args.options.clone(); let root_for_app = root.clone(); @@ -186,6 +203,8 @@ fn run() -> Result<()> { cx, ); app.power_choice = args.power; + app.settings_path.clone_from(&settings_path); + app.apply_settings(&chosen); app }) }, @@ -209,17 +228,39 @@ fn parse_args(args: impl Iterator) -> Result { parse_args_with_power(args, power::PowerEfficiency::default()) } +#[cfg(test)] fn parse_args_with_power( + args: impl Iterator, + preset: power::PowerEfficiency, +) -> Result { + parse_args_with(args, preset, &settings::Settings::default()) +} + +/// Saved choices are where the options start; a flag then overrules one. +fn parse_args_with( mut args: impl Iterator, preset: power::PowerEfficiency, + saved: &settings::Settings, ) -> Result { let mut root: Option = None; let mut options = ScanOptions { threads: preset.policy(power::cpu_threads()), + apparent_size: saved.apparent_size, + include_hidden: saved.include_hidden, + metric: if saved.mode == 1 { + disktree_core::tree::Metric::Files + } else { + disktree_core::tree::Metric::Bytes + }, ..ScanOptions::default() }; let mut power = Some(preset); - let mut depth = 3_u32; + let mut depth = saved.depth; + let deepest = if saved.deep_levels { + state::DEEP_LEVELS + } else { + state::USUAL_LEVELS + }; let mut disk = false; // `std::env::args` panics on a name that is not Unicode, and a path is // any name: a restart as administrator hands the root back exactly as @@ -248,8 +289,8 @@ fn parse_args_with_power( let value = text(args.next(), "--depth needs a number")?; depth = value.parse().context("--depth needs a number")?; anyhow::ensure!( - (1..=6).contains(&depth), - "--depth must be 1 to 6" + (1..=deepest).contains(&depth), + "--depth must be 1 to {deepest}" ); } "--power-efficiency" => { @@ -355,7 +396,7 @@ fn parse_args_with_power( Ok(Args { root, options, - depth: depth.clamp(1, 6), + depth: depth.clamp(1, deepest), power, }) } @@ -431,6 +472,32 @@ mod argument_tests { assert_eq!(args.options.threads.system_cpu_limit, None); } + #[test] + fn saved_view_choices_are_where_the_flags_start() { + let saved = settings::Settings { + depth: 5, + include_hidden: false, + apparent_size: true, + mode: 1, + ..settings::Settings::default() + }; + let preset = power::PowerEfficiency::default(); + let args = + parse_args_with(arguments(&[]), preset, &saved).expect("saved"); + assert_eq!(args.depth, 5); + assert!(!args.options.include_hidden); + assert!(args.options.apparent_size); + assert_eq!(args.options.metric, disktree_core::tree::Metric::Files); + let args = parse_args_with( + arguments(&["--depth", "2", "--metric", "bytes"]), + preset, + &saved, + ) + .expect("flags"); + assert_eq!(args.depth, 2); + assert_eq!(args.options.metric, disktree_core::tree::Metric::Bytes); + } + #[test] fn saved_power_is_loaded_before_cli_overrides() { use power::PowerEfficiency as Power; diff --git a/crates/disktree-app/src/palette.rs b/crates/disktree-app/src/palette.rs index 1f5ad7e7..d6f3ba10 100644 --- a/crates/disktree-app/src/palette.rs +++ b/crates/disktree-app/src/palette.rs @@ -130,12 +130,16 @@ pub const fn highlight(theme: &Theme) -> Hsla { theme.warning } -/// Text on a filled highlight. -pub const fn on_highlight(theme: &Theme) -> Hsla { - if dark(theme) { - theme.background +/// Text on a filled highlight: whichever end of the theme stands further +/// from the fill. A light theme's highlight is a dark amber, and the dark +/// text that suits its pages was nearly lost on it. +pub fn on_highlight(theme: &Theme) -> Hsla { + let fill = highlight(theme).l; + let (ground, ink) = (theme.background, theme.bright); + if (ground.l - fill).abs() >= (ink.l - fill).abs() { + ground } else { - theme.bright + ink } } diff --git a/crates/disktree-app/src/settings.rs b/crates/disktree-app/src/settings.rs new file mode 100644 index 00000000..e552973c --- /dev/null +++ b/crates/disktree-app/src/settings.rs @@ -0,0 +1,233 @@ +//! View choices kept between launches: the theme, what is measured and how +//! deep it is drawn, and the side panel. +//! +//! One `key=value` per line, beside the Power Efficiency preset. Reading is +//! lenient on purpose: a key this build does not know, or a value it cannot +//! use, is skipped and the rest still apply, so an older and a newer build +//! can share the file, and a hand edit gone wrong costs one setting instead +//! of all of them. The command line still wins over anything saved. + +use std::io::{self, Write as _}; +use std::path::{Path, PathBuf}; + +use crate::appearance::ThemeChoice; +use crate::state::{ + DEEP_LEVELS, PANEL_MAX_REMS, PANEL_MIN_REMS, PANEL_REMS, USUAL_LEVELS, +}; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Settings { + pub theme: ThemeChoice, + /// Levels drawn at once: 1 to 6, or to 10 with `deep_levels`. + pub depth: u32, + pub include_hidden: bool, + pub apparent_size: bool, + /// The Size | Files | Age choice, as the control indexes it. + pub mode: usize, + /// The side panel's width, in rem. + pub panel_rems: f32, + /// Whether the side panel is shown at all. + pub show_selection: bool, + /// Whether more than six levels may be drawn at once. + pub deep_levels: bool, + /// Whether sizes are written in GB, thousands, rather than GiB, 1024s. + pub decimal_units: bool, +} + +impl Default for Settings { + fn default() -> Self { + Self { + theme: ThemeChoice::default(), + depth: 3, + include_hidden: true, + apparent_size: false, + mode: 0, + panel_rems: PANEL_REMS, + show_selection: true, + deep_levels: false, + decimal_units: false, + } + } +} + +impl Settings { + /// Read `text`, keeping the default for anything missing or unusable. + pub fn parse(text: &str) -> Self { + let mut settings = Self::default(); + let flag = |value: &str| match value { + "true" => Some(true), + "false" => Some(false), + _ => None, + }; + for line in text.lines() { + let Some((key, value)) = line.split_once('=') else { + continue; + }; + let value = value.trim(); + match key.trim() { + "theme" => { + if let Some(theme) = ThemeChoice::parse(value) { + settings.theme = theme; + } + } + "depth" => { + if let Ok(depth) = value.parse::() + && (1..=DEEP_LEVELS).contains(&depth) + { + settings.depth = depth; + } + } + "hidden" => { + if let Some(on) = flag(value) { + settings.include_hidden = on; + } + } + "apparent-size" => { + if let Some(on) = flag(value) { + settings.apparent_size = on; + } + } + "mode" => { + if let Some(index) = + MODES.iter().position(|mode| *mode == value) + { + settings.mode = index; + } + } + "panel-width" => { + // A width outside the limits a drag keeps to would + // open a panel the handle could not have made. + if let Ok(rems) = value.parse::() + && (PANEL_MIN_REMS..=PANEL_MAX_REMS).contains(&rems) + { + settings.panel_rems = rems; + } + } + "panel" => { + if let Some(on) = flag(value) { + settings.show_selection = on; + } + } + "units" => match value { + "gb" => settings.decimal_units = true, + "gib" => settings.decimal_units = false, + _ => {} + }, + "deep-levels" => { + if let Some(on) = flag(value) { + settings.deep_levels = on; + } + } + _ => {} + } + } + // The lines come in any order, so the depth is held to what the + // file as a whole allows only once all of it is read. + if !settings.deep_levels { + settings.depth = settings.depth.min(USUAL_LEVELS); + } + settings + } + + fn text(&self) -> String { + format!( + "theme={}\ndepth={}\nhidden={}\napparent-size={}\nmode={}\n\ + panel-width={:.2}\npanel={}\ndeep-levels={}\nunits={}\n", + self.theme.key(), + self.depth, + self.include_hidden, + self.apparent_size, + MODES[self.mode.min(MODES.len() - 1)], + self.panel_rems, + self.show_selection, + self.deep_levels, + if self.decimal_units { "gb" } else { "gib" }, + ) + } +} + +/// The Size | Files | Age choice by name, in the control's order, so the +/// file still means the same if the control is ever reordered. +const MODES: [&str; 3] = ["size", "files", "age"]; + +/// Beside the Power Efficiency preset, in the same per-user directory. +pub fn path() -> Option { + crate::power::settings_path().map(|path| path.with_file_name("settings")) +} + +/// The saved settings, or the defaults when nothing was saved yet. +pub fn load(path: &Path) -> io::Result { + match std::fs::read_to_string(path) { + Ok(text) => Ok(Settings::parse(&text)), + Err(error) if error.kind() == io::ErrorKind::NotFound => { + Ok(Settings::default()) + } + Err(error) => Err(error), + } +} + +pub fn save(path: &Path, settings: &Settings) -> io::Result<()> { + let parent = path.parent().ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "no settings directory") + })?; + std::fs::create_dir_all(parent)?; + // Replaced whole, as the preset beside it is: a failed write leaves + // the previous choices, and a reader never sees half a file. + let mut file = tempfile::NamedTempFile::new_in(parent)?; + file.write_all(settings.text().as_bytes())?; + file.persist(path).map_err(|error| error.error)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn saved_choices_come_back_as_they_were() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("config/settings"); + assert_eq!(load(&path).expect("missing"), Settings::default()); + let chosen = Settings { + theme: ThemeChoice::Light, + depth: 5, + include_hidden: false, + apparent_size: true, + mode: 2, + panel_rems: 30.5, + show_selection: false, + deep_levels: false, + decimal_units: true, + }; + save(&path, &chosen).expect("save"); + assert_eq!(load(&path).expect("load"), chosen); + assert!(save(dir.path(), &chosen).is_err()); + } + + #[test] + fn one_bad_line_costs_one_setting() { + let settings = Settings::parse( + "theme=plaid\ndepth=4\nfrom-a-newer-build=yes\nnot a setting\n\ + hidden=maybe\nmode=files\npanel-width=900\n", + ); + assert_eq!( + settings, + Settings { + depth: 4, + mode: 1, + ..Settings::default() + } + ); + } + + #[test] + fn a_depth_the_view_cannot_draw_is_not_taken() { + assert_eq!(Settings::parse("depth=0").depth, 3); + assert_eq!(Settings::parse("depth=6").depth, 6); + // Past six only for whoever unlocked it, whichever line is first. + assert_eq!(Settings::parse("depth=9").depth, 6); + assert_eq!(Settings::parse("depth=9\ndeep-levels=true").depth, 9); + assert_eq!(Settings::parse("deep-levels=true\ndepth=10").depth, 10); + assert_eq!(Settings::parse("deep-levels=true\ndepth=11").depth, 3); + } +} diff --git a/crates/disktree-app/src/shortcut.rs b/crates/disktree-app/src/shortcut.rs new file mode 100644 index 00000000..084c8195 --- /dev/null +++ b/crates/disktree-app/src/shortcut.rs @@ -0,0 +1,102 @@ +//! A shortcut to this program where a Windows user looks for one: the Start +//! menu and the desktop. +//! +//! The Windows download is a bare executable in a zip, with no installer to +//! put it anywhere, so the settings page offers to. Linux has `make +//! install` and its desktop entry, and macOS its app bundle. + +use std::io; +use std::path::PathBuf; + +/// Where a shortcut can be put. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Place { + StartMenu, + Desktop, +} + +impl Place { + /// The place in words, for a notice. + pub const fn name(self) -> &'static str { + match self { + Self::StartMenu => "the Start menu", + Self::Desktop => "the desktop", + } + } + + /// The name Windows knows the folder by. Asked for by name, never + /// built from the profile's path: the desktop is often moved into + /// `OneDrive`, and only the system knows where it went. + #[cfg(windows)] + const fn folder(self) -> &'static str { + match self { + Self::StartMenu => "Programs", + Self::Desktop => "Desktop", + } + } +} + +/// Write `disktree.lnk` in `place`, pointing at this executable, and return +/// where it is. One that is already there is replaced, so the shortcut +/// follows the program when it is moved and the button is pressed again. +#[cfg(windows)] +pub fn create(place: Place) -> io::Result { + use std::os::windows::process::CommandExt as _; + use std::process::Command; + + /// `CREATE_NO_WINDOW`: no console flashes up behind the settings page. + const NO_WINDOW: u32 = 0x0800_0000; + + let target = std::env::current_exe()?; + // A `.lnk` is written by the shell's own COM object, and PowerShell is + // the way to it that every Windows has. The target goes through the + // environment, never into the script's text, so no path can be read + // as code. + // The link's path comes back as UTF-8 whatever the console's code page: + // a desktop moved into OneDrive is often named in the user's language. + let script = format!( + "$ErrorActionPreference = 'Stop'; \ + [Console]::OutputEncoding = [Text.Encoding]::UTF8; \ + $folder = [Environment]::GetFolderPath('{}'); \ + $link = Join-Path $folder 'disktree.lnk'; \ + $shortcut = (New-Object -ComObject WScript.Shell)\ + .CreateShortcut($link); \ + $shortcut.TargetPath = $env:DISKTREE_SHORTCUT_TARGET; \ + $shortcut.Description = 'A treemap of what is using your disk'; \ + $shortcut.Save(); \ + [Console]::Out.Write($link)", + place.folder() + ); + // By its full path: a `powershell.exe` earlier on PATH is not the one + // to hand this to. + let system = std::env::var_os("SystemRoot") + .map(PathBuf::from) + .ok_or_else(|| io::Error::other("SystemRoot is not set"))?; + let output = Command::new( + system.join("System32/WindowsPowerShell/v1.0/powershell.exe"), + ) + .args(["-NoProfile", "-NonInteractive", "-Command", &script]) + .env("DISKTREE_SHORTCUT_TARGET", &target) + .creation_flags(NO_WINDOW) + .output()?; + if !output.status.success() { + let said = String::from_utf8_lossy(&output.stderr); + return Err(io::Error::other( + said.lines() + .next() + .unwrap_or("PowerShell failed") + .to_owned(), + )); + } + let link = String::from_utf8_lossy(&output.stdout).trim().to_owned(); + if link.is_empty() { + return Err(io::Error::other("no shortcut was written")); + } + Ok(PathBuf::from(link)) +} + +/// Only Windows keeps shortcuts this way. +#[cfg(not(windows))] +pub fn create(_place: Place) -> io::Result { + Err(io::Error::from(io::ErrorKind::Unsupported)) +} diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index ee351f3a..9adf197b 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -25,15 +25,18 @@ use disktree_core::tree::{Metric, Node, path_of}; use disktree_core::treemap::{ LayoutOptions, Rect, Tile, TileKind, hit, layout_filtered, }; +use gpui_kit::base::input::{InputEvent, InputState}; use gpui_kit::{ - Context, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, - MouseMoveEvent, NavigationDirection, Pixels, Point, Render, ScrollDelta, - ScrollWheelEvent, Size, Window, px, size, + AppContext as _, Context, Entity, FocusHandle, KeyDownEvent, MouseButton, + MouseDownEvent, MouseMoveEvent, NavigationDirection, Pixels, Point, Render, + ScrollDelta, ScrollHandle, ScrollWheelEvent, Size, Window, px, size, }; use gpui_omarchy::Status; use rustc_hash::{FxHashMap, FxHashSet}; +use crate::appearance::ThemeChoice; use crate::git::GitState; +use crate::settings::Settings; use crate::marks::{Marks, display_path, is_hidden}; use crate::treemap_view::{Mosaic, TileDeco}; @@ -99,8 +102,31 @@ 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; +/// Where the source and the issue tracker are, for the button that goes +/// there. +pub const REPOSITORY: &str = "https://github.com/tobi/disktree"; + +/// How many "worth a look" findings the panel lists, and how many once +/// "Show more" is asked for: the rest of what the scan found plausible. +pub const INSIGHT_LIMIT: usize = 6; +const INSIGHT_MORE: usize = 30; + +/// The units a size can be typed in, in the Filter menu: each a step of +/// the one before, in whichever of GiB and GB sizes are being shown in. +/// Up to the terabyte: a disk image or a backup set is a file that big. +pub fn size_units() -> [&'static str; 4] { + if disktree_core::size::decimal_units() { + ["kB", "MB", "GB", "TB"] + } else { + ["KiB", "MiB", "GiB", "TiB"] + } +} + +/// How many levels can be drawn at once. Past six a whole disk is tens of +/// thousands of tiles too small to read and slow to lay out, so the levels +/// beyond are there only for whoever asks for them in the settings. +pub const USUAL_LEVELS: u32 = 6; +pub const DEEP_LEVELS: u32 = 10; /// Which screen the app is showing. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -455,6 +481,52 @@ pub struct Disktree { pub scan_elapsed: Option, /// Unix seconds when the tree landed: the "now" ages are measured from. pub scanned_at: i64, + /// Where the view choices are saved. `None` keeps them for this run + /// only: no settings directory, or a test that must not write to one. + pub settings_path: Option, + pub theme_choice: ThemeChoice, + /// The path field in the top bar, built the first time it is opened. + pub path_input: Option>, + /// The trail is a text field just now: see [`Self::open_path_bar`]. + pub path_open: bool, + /// Whether [`DEEP_LEVELS`] may be drawn, rather than [`USUAL_LEVELS`]. + pub deep_levels: bool, + /// The settings page is over the window. + pub settings_open: bool, + /// The page of every disk is over the window; it shares the picker's + /// list and highlight. + pub home_open: bool, + /// The Filter button's menu is open. + pub filter_menu: bool, + /// The kinds of data the Filter menu has ticked: any of them is shown. + /// Kept apart from the name typed after `/`, which the field shows. + pub filter_kinds: Vec, + /// The least and the most a file may hold, in bytes, from the menu. + pub filter_least: Option, + pub filter_most: Option, + /// Which unit each of the menu's two size fields is read in, the + /// least then the most: an index into [`size_units`]. Each has its + /// own, so "from 500 MiB to 4 GiB" is typed as it is said. + pub size_unit: [usize; 2], + /// The dropdowns those units are picked from, built each time the + /// menu opens so they list the units the setting then asks for. + pub unit_selects: Option<[Entity; 2]>, + /// What is wrong with a typed size and which field it is in, the + /// least (`0`) or the most (`1`): said beside that field, in words, + /// until it is put right. + pub size_error: Option<(usize, String)>, + /// The machine being scanned over SSH, when it is not this one. While + /// set, the tree's paths are that machine's, and nothing that acts on + /// a local path is offered: see [`Self::set_remote`]. + pub remote: Option, + /// The address field on the page of disks. + pub ssh_input: Option>, + /// The menu's least and most fields, built the first time it opens. + pub size_inputs: Option<(Entity, Entity)>, + /// "Worth a look" lists [`INSIGHT_MORE`] findings instead of the few. + pub insights_all: bool, + /// Where the panel's lists are scrolled to, shared with their bar. + pub panel_scroll: ScrollHandle, } impl Disktree { @@ -491,7 +563,7 @@ impl Disktree { view: View::default(), transition: None, layout_options: LayoutOptions { - max_depth: depth.clamp(1, 6), + max_depth: depth.clamp(1, DEEP_LEVELS), ..LayoutOptions::default() }, cache: None, @@ -551,7 +623,34 @@ impl Disktree { scan_root: PathBuf::new(), scan_elapsed: None, scanned_at: now_seconds(), + settings_path: None, + theme_choice: ThemeChoice::default(), + path_input: None, + path_open: false, + deep_levels: false, + settings_open: false, + home_open: false, + filter_menu: false, + filter_kinds: Vec::new(), + filter_least: None, + filter_most: None, + // Megabytes: the unit most "large files" are counted in. + size_unit: [1, 1], + unit_selects: None, + size_error: None, + remote: None, + ssh_input: None, + size_inputs: None, + insights_all: false, + panel_scroll: ScrollHandle::new(), }; + // The panel's width changes continuously under a drag, so it is + // written down once, on the way out, with everything else. + cx.on_app_quit(|this, _| { + this.save_settings(); + std::future::ready(()) + }) + .detach(); tree.device = device_for(&tree.root_path); tree.full_disk_access = tree .home @@ -597,6 +696,7 @@ impl Disktree { /// Scan a different root from scratch. Marks are kept; a mark outside /// the new root is shown as kept back, never removed. pub fn set_root(&mut self, root: PathBuf, cx: &mut Context<'_, Self>) { + self.remote = None; self.space = space_info(&root).ok(); self.device = device_for(&root); // "Whole disk" means the disk of what is on screen, which a new root @@ -609,12 +709,97 @@ impl Disktree { self.start_scan(cx); } + /// Scan a directory on another machine, over SSH, to look at. + /// + /// The tree that comes back holds that machine's paths. Nothing here + /// may then treat one as a path on this machine: the same `/var/log` + /// may well exist on both, and removing it here because it was marked + /// there would delete the wrong files. So marks are dropped and + /// marking refused, and so are the file manager, git and the free + /// space meter, until a local root is scanned again. + pub fn set_remote( + &mut self, + remote: disktree_core::remote::Remote, + cx: &mut Context<'_, Self>, + ) { + self.marks.clear(); + self.space = None; + self.space_baseline = None; + self.device = Some(remote.target.clone()); + self.disk_root = None; + self.file_table = false; + self.root_path = PathBuf::from(&remote.path); + self.notice = Some(( + format!("{remote} over ssh \u{00b7} a remote scan is read-only"), + Status::Neutral, + )); + self.remote = Some(remote); + self.screen = Screen::Explore; + self.home_open = false; + self.start_scan(cx); + } + + /// Whether what is on screen is another machine's, and so may only be + /// looked at. Says so when `doing` something that would act on it. + fn read_only(&mut self, doing: &str, cx: &mut Context<'_, Self>) -> bool { + let Some(remote) = &self.remote else { + return false; + }; + self.notice = Some(( + format!( + "{doing} is not offered for {}: a remote scan is read-only", + remote.target + ), + Status::Warning, + )); + cx.notify(); + true + } + + /// Enter in the address field on the page of disks. + pub fn connect_ssh(&mut self, cx: &mut Context<'_, Self>) { + let Some(input) = self.ssh_input.clone() else { + return; + }; + let typed = input.read(cx).value().to_string(); + if let Some(remote) = disktree_core::remote::Remote::parse(&typed) { + self.focus_request = Some(FocusTarget::Root); + self.set_remote(remote, cx); + } else { + self.notice = Some(( + "an address looks like user@host:/path".into(), + Status::Warning, + )); + cx.notify(); + } + } + + fn on_ssh_event( + &mut self, + _: &Entity, + event: &InputEvent, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) { + if matches!(event, InputEvent::PressEnter { .. }) && self.home_open { + self.connect_ssh(cx); + self.apply_focus(window, cx); + } + } + /// Go up to `above`, a directory containing the scanned root. /// /// Memoized: the tree already measured is handed to the walk and reused /// where it is reached, so only what is new at the wider level is read, /// and the current view stays on screen until the wider tree lands. pub fn widen_to(&mut self, above: PathBuf, cx: &mut Context<'_, Self>) { + // A wider look at another machine is another listing of it: the + // tree in hand cannot be handed to a walk of this one. + if let Some(remote) = &self.remote { + let wider = remote.at(&above.to_string_lossy()); + self.set_remote(wider, cx); + return; + } let Some(tree) = self.tree.clone() else { self.set_root(above, cx); return; @@ -650,14 +835,48 @@ impl Disktree { /// is left alone until a volume is picked; picking calls [`set_root`], /// which cancels it. pub fn open_volumes(&mut self, cx: &mut Context<'_, Self>) { + self.volumes_open = true; + self.focus_request = Some(FocusTarget::Dialog); + self.load_volumes(false, cx); + } + + /// The home page: every disk with its name, size and room, as a file + /// manager's own first page shows them, the one being scanned too. + pub fn open_home( + &mut self, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) { + if !self.can_start_over() { + return; + } + if self.ssh_input.is_none() { + let input = cx.new(|cx| InputState::new(window, cx)); + cx.subscribe_in(&input, window, Self::on_ssh_event).detach(); + self.ssh_input = Some(input); + } + self.notice = None; + self.home_open = true; + self.filter_menu = false; + self.load_volumes(true, cx); + } + + /// Leave the page of disks without choosing one. + pub fn close_home(&mut self, cx: &mut Context<'_, Self>) { + self.home_open = false; + self.focus_request = Some(FocusTarget::Root); + cx.notify(); + } + + /// Read the volumes for the picker, or with `with_current` for the + /// page of disks, which shows the scanned one among the others. + fn load_volumes(&mut self, with_current: bool, cx: &mut Context<'_, Self>) { self.volume_epoch += 1; let epoch = self.volume_epoch; let root_path = self.root_path.clone(); self.volumes.clear(); self.volume_highlight = 0; self.volumes_loading = true; - self.volumes_open = true; - self.focus_request = Some(FocusTarget::Dialog); // Removable media and network volumes can take seconds to answer. // Keep Escape and the window responsive while probing them. let task = cx.background_executor().spawn(async move { @@ -669,15 +888,20 @@ impl Disktree { point: root.clone(), device: device_for(&root), space: space_info(&root).ok(), + label: disktree_core::space::volume_label(&root), }); } - volumes.retain(|volume| volume.point != root_path); + if !with_current { + volumes.retain(|volume| volume.point != root_path); + } + by_name(&mut volumes); volumes }); cx.spawn(async move |this, cx| { let volumes = task.await; let _ = this.update(cx, |this, cx| { - if this.volumes_open && this.volume_epoch == epoch { + let wanted = this.volumes_open || this.home_open; + if wanted && this.volume_epoch == epoch { this.volumes = volumes; this.volumes_loading = false; cx.notify(); @@ -708,10 +932,12 @@ impl Disktree { .map(|volume| volume.point.clone()) else { self.volumes_open = false; + self.home_open = false; cx.notify(); return; }; self.volumes_open = false; + self.home_open = false; self.volumes.clear(); self.set_root(point, cx); } @@ -751,17 +977,726 @@ impl Disktree { } } + /// Whether the scanned root is itself a volume: there is nothing above + /// it to widen to, so the only way on from its crumb is another volume. + pub fn root_is_a_volume(&self) -> bool { + self.root_path.parent().is_none() + || self.disk_root.as_deref() == Some(self.root_path.as_path()) + } + + // ── saved choices ─────────────────────────────────────────────────── + + /// The view choices as they stand, for the settings file. + pub fn settings(&self) -> Settings { + Settings { + theme: self.theme_choice, + depth: self.layout_options.max_depth, + include_hidden: self.options.include_hidden, + apparent_size: self.options.apparent_size, + mode: self.mode_index(), + panel_rems: self.panel_rems, + show_selection: self.show_selection, + deep_levels: self.deep_levels, + decimal_units: disktree_core::size::decimal_units(), + } + } + + /// The deepest the view may be asked to draw. + pub const fn depth_limit(&self) -> u32 { + if self.deep_levels { + DEEP_LEVELS + } else { + USUAL_LEVELS + } + } + + /// Allow [`DEEP_LEVELS`], or go back to [`USUAL_LEVELS`] and to a + /// depth within them. + pub fn set_deep_levels(&mut self, on: bool, cx: &mut Context<'_, Self>) { + self.deep_levels = on; + let limit = self.depth_limit(); + if self.layout_options.max_depth > limit { + self.layout_options.max_depth = limit; + self.cache = None; + } + self.save_settings(); + cx.notify(); + } + + /// Write sizes in GB, thousands, or in GiB, 1024s. A drive sold as + /// 500 GB reads 500 in the first and 465 in the second. + pub fn set_decimal_units(&self, decimal: bool, cx: &mut Context<'_, Self>) { + disktree_core::size::set_decimal_units(decimal); + self.save_settings(); + cx.notify(); + } + + /// The settings page, over whatever is on screen. + pub fn open_settings(&mut self, cx: &mut Context<'_, Self>) { + if !self.can_start_over() { + return; + } + self.settings_open = true; + self.filter_menu = false; + self.notice = None; + cx.notify(); + } + + pub fn close_settings(&mut self, cx: &mut Context<'_, Self>) { + self.settings_open = false; + self.focus_request = Some(FocusTarget::Root); + cx.notify(); + } + + /// Put a shortcut to this program on the Start menu or the desktop. + /// Off the UI thread: it waits on another program to write the link. + pub fn create_shortcut( + place: crate::shortcut::Place, + cx: &Context<'_, Self>, + ) { + let task = cx + .background_executor() + .spawn(async move { crate::shortcut::create(place) }); + cx.spawn(async move |this, cx| { + let notice = match task.await { + Ok(link) => { + (format!("added {}", link.display()), Status::Success) + } + Err(error) => ( + format!( + "could not add a shortcut to {}: {error}", + place.name() + ), + Status::Error, + ), + }; + let _ = this.update(cx, |this, cx| { + this.notice = Some(notice); + cx.notify(); + }); + }) + .detach(); + } + + // ── filtering by kind and size ────────────────────────────────────── + + /// Everything the filter asks, as the one needle the search reads: the + /// name typed after `/`, then the kinds and sizes chosen in the Filter + /// menu. They are held apart so the field shows only what was typed. + pub fn needle(&self) -> String { + use disktree_core::filter::{ + KIND_PREFIX, LEAST_PREFIX, MOST_PREFIX, kind_key, + }; + let mut words: Vec = Vec::new(); + let name = self.find.trim(); + if !name.is_empty() { + words.push(name.to_owned()); + } + for kind in &self.filter_kinds { + words.push(format!("{KIND_PREFIX}{}", kind_key(*kind))); + } + if let Some(least) = self.filter_least { + words.push(format!("{LEAST_PREFIX}{least}")); + } + if let Some(most) = self.filter_most { + words.push(format!("{MOST_PREFIX}{most}")); + } + words.join(" ") + } + + /// How many things the Filter menu asks for: each ticked kind, and + /// each size that is set. + pub fn filter_count(&self) -> usize { + self.filter_kinds.len() + + usize::from(self.filter_least.is_some()) + + usize::from(self.filter_most.is_some()) + } + + /// The menu's choices read back as a sentence, so what is in force is + /// said in words and not only shown by ticks. + pub fn filter_sentence(&self) -> String { + use disktree_core::size::human_bytes; + // Nothing is hidden when nothing matched: see `apply_filter`. + let none = self.matches.as_ref().is_some_and(|found| found.count == 0); + if self.filter_chosen() && none && !self.finding { + return "Nothing here matches, so everything is shown".into(); + } + let kinds = self + .filter_kinds + .iter() + .map(|kind| kind.label()) + .collect::>() + .join(" or "); + let sizes = match (self.filter_least, self.filter_most) { + (Some(least), Some(most)) => { + format!("from {} to {}", human_bytes(least), human_bytes(most)) + } + (Some(least), None) => format!("{} or more", human_bytes(least)), + (None, Some(most)) => format!("{} or less", human_bytes(most)), + (None, None) => String::new(), + }; + match (kinds.is_empty(), sizes.is_empty()) { + (true, true) => "Showing everything".into(), + (false, true) => format!("Showing {kinds}"), + (true, false) => format!("Showing files of {sizes}"), + (false, false) => format!("Showing {kinds}, {sizes}"), + } + } + + /// Whether the Filter menu asks for anything, whatever the name does. + pub const fn filter_chosen(&self) -> bool { + !self.filter_kinds.is_empty() + || self.filter_least.is_some() + || self.filter_most.is_some() + } + + /// Open the Filter menu, its size fields showing the sizes in force, + /// or close it. + pub fn toggle_filter_menu( + &mut self, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) { + if self.filter_menu { + self.close_filter_menu(cx); + return; + } + let (least, most) = if let Some(inputs) = self.size_inputs.clone() { + inputs + } else { + // An empty field says what empty means, rather than nothing. + let field = |window: &mut Window, cx: &mut Context<'_, Self>| { + cx.new(|cx| InputState::new(window, cx).placeholder("No limit")) + }; + let least = field(window, cx); + let most = field(window, cx); + for input in [&least, &most] { + cx.subscribe_in(input, window, Self::on_size_event).detach(); + } + self.size_inputs = Some((least.clone(), most.clone())); + (least, most) + }; + let units = self.size_unit; + self.unit_selects = Some([0, 1].map(|side| { + let select = cx.new(|cx| { + gpui_omarchy::ChoiceState::new( + size_units() + .into_iter() + .map(|unit| gpui_omarchy::ChoiceItem::new(unit, unit)) + .collect(), + window, + cx, + ) + .label(if side == 0 { + "Unit of the min size" + } else { + "Unit of the max size" + }) + .default_selected(units[side]) + }); + cx.observe(&select, move |this, select, cx| { + let picked = select.read(cx).selected().and_then(|item| { + size_units() + .into_iter() + .position(|unit| unit == item.value.as_ref()) + }); + if let Some(unit) = picked + && unit != this.size_unit[side] + { + this.set_size_unit(side, unit, cx); + } + }) + .detach(); + select + })); + for (input, bytes, unit) in [ + (&least, self.filter_least, units[0]), + (&most, self.filter_most, units[1]), + ] { + // What was typed stays as typed while it still means the + // size in force: written back from the bytes it would be + // rounded, and the next Apply would move the limit. + if size_typed(&input.read(cx).value(), unit) == Ok(bytes) { + continue; + } + let shown = + bytes.map_or_else(String::new, |bytes| size_shown(bytes, unit)); + input.update(cx, |state, cx| state.set_value(shown, window, cx)); + } + // The keyboard starts inside the menu, so Tab and Shift+Tab walk + // its controls; from the treemap they would not reach it. + least.update(cx, |state, cx| state.focus(window, cx)); + self.size_error = None; + self.filter_menu = true; + self.crumb_menu = None; + self.power_menu = None; + cx.notify(); + } + + /// Put the Filter menu away and return the keyboard to the treemap. + pub fn close_filter_menu(&mut self, cx: &mut Context<'_, Self>) { + self.filter_menu = false; + self.focus_request = Some(FocusTarget::Root); + cx.notify(); + } + + /// Tick or untick one kind of data. Any ticked kind is shown, so the + /// menu stays open for the next. + pub fn toggle_filter_kind( + &mut self, + kind: disktree_core::classify::Category, + cx: &mut Context<'_, Self>, + ) { + if let Some(at) = self.filter_kinds.iter().position(|on| *on == kind) { + self.filter_kinds.remove(at); + } else { + self.filter_kinds.push(kind); + } + self.rerun_filter(cx); + } + + /// Read one size field, the least (`0`) or the most (`1`), in another + /// unit: the number stays as it was typed and means something else, + /// as changing a unit does. + pub fn set_size_unit( + &mut self, + side: usize, + unit: usize, + cx: &mut Context<'_, Self>, + ) { + let side = side.min(1); + let unit = unit.min(size_units().len() - 1); + self.size_unit[side] = unit; + // The dropdown shows it too, when this did not come from there. + if let Some(selects) = &self.unit_selects { + let select = selects[side].clone(); + let shown = select + .read(cx) + .selected() + .is_some_and(|item| item.value.as_ref() == size_units()[unit]); + if !shown { + select.update(cx, |state, cx| { + state.set_selected(Some(unit), cx); + }); + } + } + self.apply_sizes(cx); + } + + /// Empty one size field, the least (`0`) or the most (`1`), and lift + /// that limit at once: the cross in a field is an action, not an + /// edit waiting for Apply. + pub fn clear_size( + &mut self, + side: usize, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) { + let Some((least, most)) = self.size_inputs.clone() else { + return; + }; + let input = if side == 0 { least } else { most }; + input.update(cx, |state, cx| { + state.set_value("", window, cx); + state.focus(window, cx); + }); + self.apply_sizes(cx); + } + + /// Take the least and most sizes from the menu's fields. An empty + /// field is no limit on that side. + pub fn apply_sizes(&mut self, cx: &mut Context<'_, Self>) { + let Some((least, most)) = self.size_inputs.clone() else { + return; + }; + let typed = |input: &Entity, unit: usize| { + size_typed(&input.read(cx).value(), unit) + }; + let units = self.size_unit; + // Each failure names its field and the way out of it, and is + // shown beside that field: see `views::filter_control`. + let not_a_number = |side: &str| { + format!("{side} is not a number. Type one such as 1.5.") + }; + match (typed(&least, units[0]), typed(&most, units[1])) { + (Err(()), _) => { + self.size_error = Some((0, not_a_number("Min"))); + } + (_, Err(())) => { + self.size_error = Some((1, not_a_number("Max"))); + } + (Ok(Some(least)), Ok(Some(most))) if least > most => { + self.size_error = Some(( + 1, + format!( + "Max is below Min. Raise Max above {}.", + disktree_core::size::human_bytes(least) + ), + )); + } + (Ok(least), Ok(most)) => { + self.filter_least = least; + self.filter_most = most; + self.size_error = None; + self.rerun_filter(cx); + } + } + cx.notify(); + } + + /// Untick every kind and lift both sizes; a name being searched for + /// stays, since it was not asked for here. + pub fn clear_chosen_filter( + &mut self, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) { + self.filter_kinds.clear(); + self.filter_least = None; + self.filter_most = None; + if let Some((least, most)) = self.size_inputs.clone() { + least.update(cx, |state, cx| state.set_value("", window, cx)); + most.update(cx, |state, cx| state.set_value("", window, cx)); + } + self.size_error = None; + self.rerun_filter(cx); + } + + /// Search again with the filter as it now stands, and show only what + /// matches, as Enter in the name field does. + fn rerun_filter(&mut self, cx: &mut Context<'_, Self>) { + if self.needle().is_empty() { + self.clear_filter(); + } else { + self.refresh_matches(cx); + self.apply_filter(cx); + } + cx.notify(); + } + + /// Apply, from the button or Enter: the sizes are taken, and when one + /// is wrong the keyboard is put in its field, where the fix is typed. + pub fn press_apply( + &mut self, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) { + self.apply_sizes(cx); + if let Some((side, _)) = &self.size_error + && let Some((least, most)) = self.size_inputs.clone() + { + let input = if *side == 0 { least } else { most }; + input.update(cx, |state, cx| state.focus(window, cx)); + } + } + + fn on_size_event( + &mut self, + _: &Entity, + event: &InputEvent, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) { + if matches!(event, InputEvent::PressEnter { .. }) && self.filter_menu { + self.press_apply(window, cx); + } + } + + /// Take the saved choices the command line has no flag for. The depth + /// and the scan options arrive through the arguments instead, where a + /// flag can overrule them. + pub fn apply_settings(&mut self, saved: &Settings) { + disktree_core::size::set_decimal_units(saved.decimal_units); + self.theme_choice = saved.theme; + if saved.mode == 2 { + self.color_mode = ColorMode::Age; + } + self.panel_rems = saved.panel_rems; + self.show_selection = saved.show_selection; + self.deep_levels = saved.deep_levels; + } + + /// Write the view choices down. A failure goes to standard error and + /// no further: the choice still holds for this run, and a notice on + /// every click would be worse than the loss. + pub fn save_settings(&self) { + let Some(path) = self.settings_path.as_deref() else { + return; + }; + if let Err(error) = crate::settings::save(path, &self.settings()) { + eprintln!("Cannot save settings: {error}"); + } + } + + /// `i`: include or skip hidden entries, which changes what is measured. + pub fn toggle_hidden(&mut self, cx: &mut Context<'_, Self>) { + self.options.include_hidden = !self.options.include_hidden; + self.save_settings(); + self.start_scan(cx); + } + + /// `d`: disk usage or apparent size, which changes what is measured. + pub fn toggle_apparent_size(&mut self, cx: &mut Context<'_, Self>) { + self.options.apparent_size = !self.options.apparent_size; + self.save_settings(); + self.start_scan(cx); + } + + /// `T`: the system's theme, then light, then dark, and round again. + pub fn cycle_theme(&mut self, window: &Window, cx: &mut Context<'_, Self>) { + self.set_theme(self.theme_choice.next(), window, cx); + } + + /// Draw with `choice` from now on, and remember it. + pub fn set_theme( + &mut self, + choice: ThemeChoice, + window: &Window, + cx: &mut Context<'_, Self>, + ) { + self.theme_choice = choice; + crate::appearance::choose( + self.theme_choice, + window.appearance(), + self.home.as_deref(), + cx, + ); + self.notice = Some(( + format!("{} theme", self.theme_choice.name()), + Status::Neutral, + )); + self.save_settings(); + cx.notify(); + } + + /// Open the project's page in the browser. + pub fn open_repository(cx: &Context<'_, Self>) { + cx.open_url(REPOSITORY); + } + + // ── the path field ────────────────────────────────────────────────── + + /// Click the empty part of the trail, or `ctrl l`: the trail becomes a + /// text field holding the path on screen, selected. Copy it from there, + /// or type or paste another over it and press Enter to go there, as a + /// file manager's address bar does. + pub fn open_path_bar( + &mut self, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) { + if !self.can_start_over() { + return; + } + let input = if let Some(input) = self.path_input.clone() { + input + } else { + let input = cx.new(|cx| InputState::new(window, cx)); + cx.subscribe_in(&input, window, Self::on_path_event) + .detach(); + self.path_input = Some(input.clone()); + input + }; + let shown = self.current_path().display().to_string(); + input.update(cx, |state, cx| { + state.set_value(shown, window, cx); + state.select_all(window, cx); + state.focus(window, cx); + }); + self.path_open = true; + self.crumb_menu = None; + self.power_menu = None; + cx.notify(); + } + + /// Put the trail back and return the keyboard to the treemap. + pub fn close_path_bar(&mut self, cx: &mut Context<'_, Self>) { + self.path_open = false; + self.focus_request = Some(FocusTarget::Root); + cx.notify(); + } + + fn on_path_event( + &mut self, + input: &Entity, + event: &InputEvent, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) { + match event { + InputEvent::PressEnter { .. } if self.path_open => { + let typed = input.read(cx).value().to_string(); + // A path that cannot be used leaves the field open, with + // the reason beside it, so it can be corrected in place. + if self.go_to_path(&typed, cx) { + self.close_path_bar(cx); + self.apply_focus(window, cx); + } + } + // The keyboard went elsewhere, to a click on the mosaic say: + // the field has nothing left to do. + InputEvent::Blur if self.path_open => { + self.path_open = false; + cx.notify(); + } + _ => {} + } + } + + /// Go to a path that was typed or pasted. Inside the scanned tree that + /// is a step within it; above the root it widens the scan, reusing what + /// is measured; anywhere else it is scanned from scratch. A file names + /// the directory it is in. Returns whether there was somewhere to go. + pub fn go_to_path( + &mut self, + typed: &str, + cx: &mut Context<'_, Self>, + ) -> bool { + let refuse = |this: &mut Self, why: String| { + this.notice = Some((why, Status::Warning)); + false + }; + // "Copy as path" in File Explorer wraps the path in quotes. + let typed = typed.trim().trim_matches('"').trim(); + if let Some(remote) = disktree_core::remote::Remote::parse(typed) { + self.set_remote(remote, cx); + return true; + } + let Some(path) = typed_path(typed, self.home.as_deref()) else { + cx.notify(); + return refuse( + self, + format!("{typed} is not a full path: start from the root"), + ); + }; + // Canonical, like a root from the command line, so the tree's own + // paths and this one can be compared. + let Ok(real) = dunce::canonicalize(&path) else { + cx.notify(); + return refuse(self, format!("{} cannot be read", path.display())); + }; + let directory = if real.is_dir() { + real + } else { + match real.parent() { + Some(parent) => parent.to_path_buf(), + None => real, + } + }; + self.notice = None; + let within = self + .crumbs_for_path(&directory) + .filter(|crumbs| self.node_at(crumbs).is_some_and(Node::is_dir)); + if let Some(crumbs) = within { + self.go_to(crumbs, cx); + } else if self.root_path.starts_with(&directory) { + self.widen_to(directory, cx); + } else { + // Elsewhere, or inside the root but not in the tree: hidden + // while hidden entries are skipped, or made since the scan. + self.set_root(directory, cx); + } + true + } + + /// The keys that need the window: `T` for the theme and `ctrl l` for + /// the path field. Only where the treemap has the keyboard, so neither + /// fires under a dialog, a menu or the filter. + pub fn on_window_key( + &mut self, + event: &KeyDownEvent, + window: &mut Window, + cx: &mut Context<'_, Self>, + ) -> bool { + let quiet = self.can_start_over() + && !self.path_open + && !self.find_open + && !self.show_help + && self.crumb_menu.is_none() + && self.power_menu.is_none() + && !self.filter_menu; + if !quiet { + return false; + } + let modifiers = &event.keystroke.modifiers; + let chord = modifiers.control || modifiers.platform; + match event.keystroke.key.as_str() { + "t" if modifiers.shift && !chord && !modifiers.alt => { + self.cycle_theme(window, cx); + } + // The address bar's key in browsers and file managers. + "l" if chord && !modifiers.shift && !modifiers.alt => { + self.open_path_bar(window, cx); + } + _ => return false, + } + true + } + + /// A click on a key hint does what the key would. + pub fn press(&mut self, key: &str, cx: &mut Context<'_, Self>) { + if self.confirm_open + || self.volumes_open + || self.path_open + || self.home_open + || self.settings_open + { + return; + } + self.filter_menu = false; + if key == "?" { + self.show_help = !self.show_help; + cx.notify(); + return; + } + if self.show_help { + return; + } + match self.screen { + // The hint names both keys and a click can only be one: it + // draws one level more, and past the deepest starts over. + Screen::Explore if key == "[ ]" => { + let limit = self.depth_limit(); + let step = if self.layout_options.max_depth >= limit { + 1 - limit.cast_signed() + } else { + 1 + }; + self.adjust_depth(step, cx); + } + Screen::Explore => self.on_explore_key(key, false, false, cx), + Screen::Review => self.on_review_key(key, cx), + Screen::Running | Screen::Done => {} + } + } + /// Recompute "worth a look" from the tree on screen. fn refresh_insights(&mut self) { self.scanned_at = now_seconds(); self.insights = self.tree.as_deref().map_or_else(Vec::new, |tree| { - worth_a_look(tree, self.scanned_at, INSIGHT_LIMIT) + let limit = if self.insights_all { + INSIGHT_MORE + } else { + INSIGHT_LIMIT + }; + worth_a_look(tree, self.scanned_at, limit) }); } + /// "Show more" under Worth a look, and "Show fewer" to put it back. + pub fn toggle_insights(&mut self, cx: &mut Context<'_, Self>) { + self.insights_all = !self.insights_all; + self.refresh_insights(); + cx.notify(); + } + /// Ask git about `path` once, off the UI thread, if it is a checkout. pub fn ensure_git(&mut self, path: &Path, cx: &Context<'_, Self>) { - if self.git.contains_key(path) || self.git_pending.contains(path) { + // git would be asked about this machine's directory of that name. + if self.remote.is_some() + || self.git.contains_key(path) + || self.git_pending.contains(path) + { return; } let path = path.to_path_buf(); @@ -940,10 +1875,14 @@ impl Disktree { self.scan_started = Some(Instant::now()); self.scan_elapsed = None; self.scan_root.clone_from(&self.root_path); - self.scan = Some(ScanHandle::spawn( - self.root_path.clone(), - self.options.clone(), - )); + self.scan = Some(match &self.remote { + Some(remote) => { + ScanHandle::spawn_remote(remote.clone(), self.options.clone()) + } + None => { + ScanHandle::spawn(self.root_path.clone(), self.options.clone()) + } + }); Self::poll_scan(epoch, cx); cx.notify(); } @@ -993,9 +1932,12 @@ impl Disktree { if came_from.is_some() { self.clear_filter(); self.root_path.clone_from(&self.scan_root); - self.space = space_info(&self.root_path).ok(); - self.device = device_for(&self.root_path); - self.file_table = file_table_readable(&self.root_path); + // Another machine's root says nothing of these disks. + if self.remote.is_none() { + self.space = space_info(&self.root_path).ok(); + self.device = device_for(&self.root_path); + self.file_table = file_table_readable(&self.root_path); + } } let metric = self.options.metric; self.marks.refresh(&self.root_path, &node, metric); @@ -1057,6 +1999,11 @@ impl Disktree { cx.background_executor().timer(interval).await; let ok = this .update(cx, |this, cx| { + // Another machine's path says nothing about this + // machine's disks. + if this.remote.is_some() { + return; + } let path = this.root_path.clone(); let fresh = space_info(&path).ok(); if fresh != this.space { @@ -1095,6 +2042,17 @@ impl Disktree { Some(path_of(&self.root_path, tree, crumbs)) } + /// `path` as it is shown. Another machine's is written its own way, + /// with forward slashes and no `~`: it was joined here, where the + /// separator may be `\`, and this machine's home is not its home. + pub fn shown_path(&self, path: &Path) -> String { + if self.remote.is_some() { + path.to_string_lossy().replace('\\', "/") + } else { + crate::marks::display_path(path, self.home.as_deref()) + } + } + /// Path of the directory currently drawn. pub fn current_path(&self) -> PathBuf { self.path_at(&self.crumbs) @@ -1685,6 +2643,9 @@ impl Disktree { crumbs: &[usize], cx: &mut Context<'_, Self>, ) { + if self.read_only("marking", cx) { + return; + } let Some(target) = self.target_at(crumbs) else { return; }; @@ -2048,9 +3009,11 @@ impl Disktree { /// a treemap: seeing further in without changing what is on screen. pub fn adjust_depth(&mut self, step: i32, cx: &mut Context<'_, Self>) { let depth = (self.layout_options.max_depth.cast_signed() + step) - .clamp(1, 6) as u32; + .clamp(1, self.depth_limit().cast_signed()) + as u32; self.layout_options.max_depth = depth; self.cache = None; + self.save_settings(); cx.notify(); } @@ -2094,6 +3057,7 @@ impl Disktree { if self.options.metric != metric { self.toggle_metric(cx); } + self.save_settings(); cx.notify(); } @@ -2182,6 +3146,11 @@ impl Disktree { } pub fn begin_removal(&mut self, cx: &mut Context<'_, Self>) { + // Marking is refused there, so this cannot be reached with marks; + // it is refused again here because it is the step that deletes. + if self.read_only("removal", cx) { + return; + } let plan = self.plan(); if plan.is_empty() { self.notice = Some(("nothing is marked".into(), Status::Warning)); @@ -2293,7 +3262,7 @@ impl Disktree { pub fn refresh_matches(&mut self, cx: &Context<'_, Self>) { self.find_epoch += 1; let epoch = self.find_epoch; - let needle = self.find.clone(); + let needle = self.needle(); let Some(tree) = self.tree.clone().filter(|_| !needle.trim().is_empty()) else { @@ -2339,10 +3308,14 @@ impl Disktree { return; }; if matches.count == 0 { - self.notice = Some(( - format!("nothing here matches {}", matches.needle), - Status::Warning, - )); + // The menu's choices travel as words no one typed, so they + // are not read back; a name alone is. + let what = if self.filter_chosen() { + "nothing here matches the filter".to_owned() + } else { + format!("nothing here matches {}", matches.needle) + }; + self.notice = Some((what, Status::Warning)); cx.notify(); return; } @@ -2373,6 +3346,9 @@ impl Disktree { self.finding = false; self.apply_pending = false; self.find.clear(); + self.filter_kinds.clear(); + self.filter_least = None; + self.filter_most = None; self.find_open = false; self.matches = None; self.filter_applied = false; @@ -2397,6 +3373,8 @@ impl Disktree { self.screen == Screen::Explore && !self.confirm_open && !self.volumes_open + && !self.home_open + && !self.settings_open } /// Ask for a directory and scan it: an app opened from the Dock has no @@ -2499,6 +3477,9 @@ impl Disktree { /// Show the tile a key acts on in Finder (or the file manager), selected. pub fn reveal_target(&mut self, cx: &mut Context<'_, Self>) { + if self.read_only("the file manager", cx) { + return; + } let crumbs = self.action_target().unwrap_or_else(|| self.crumbs.clone()); let Some(path) = self.path_at(&crumbs) else { @@ -2537,6 +3518,55 @@ impl Disktree { return; } + // So does the path field: what is typed there is text, not + // commands. Escape arrives here once the field has no use for it. + if self.path_open { + if key == "escape" { + self.close_path_bar(cx); + } + return; + } + + // The Filter menu has fields to type sizes in, so keys are text + // there too. + if self.filter_menu { + // An open dropdown takes Escape for itself first. + let picking = self.unit_selects.as_ref().is_some_and(|selects| { + selects.iter().any(|select| select.read(cx).is_open()) + }); + if key == "escape" && !picking { + self.close_filter_menu(cx); + } + return; + } + + // The settings page has controls of its own; only Escape is ours. + if self.settings_open { + if key == "escape" { + self.close_settings(cx); + } + return; + } + + // The page of disks takes the picker's keys. + if self.home_open { + // Letters are text for the address field, and left and right + // move its caret; only up and down are the list's. + let addressed = self + .ssh_input + .as_ref() + .is_some_and(|input| !input.read(cx).value().trim().is_empty()); + match key { + "escape" => self.close_home(cx), + // With an address typed, Enter is the field's own. + "enter" if !addressed => self.choose_volume(cx), + "up" if !control => self.move_volume_highlight(-1, cx), + "down" if !control => self.move_volume_highlight(1, cx), + _ => {} + } + return; + } + // The volume picker owns its keys while open: arrows move, Enter // picks, Escape closes, and nothing behind it acts. if self.volumes_open { @@ -2582,6 +3612,13 @@ impl Disktree { // tree, and Escape always means "give the keyboard back". if self.screen == Screen::Explore && self.find_open { match key { + // The name alone: what the Filter menu holds was not + // typed here, and its own Clear leaves the name in turn. + "escape" if self.filter_chosen() => { + self.find.clear(); + self.find_open = false; + self.rerun_filter(cx); + } "escape" => self.clear_filter(), "enter" => self.apply_filter(cx), "backspace" => { @@ -2730,16 +3767,11 @@ impl Disktree { "r" if !control => self.start_scan(cx), "g" if !control => self.go_to_disk(cx), "v" if !control && !shift => self.open_volumes(cx), - "i" if !control => { - self.options.include_hidden = !self.options.include_hidden; - self.start_scan(cx); - } - "d" if !control => { - self.options.apparent_size = !self.options.apparent_size; - self.start_scan(cx); - } + "i" if !control => self.toggle_hidden(cx), + "d" if !control => self.toggle_apparent_size(cx), "p" if !control => { self.show_selection = !self.show_selection; + self.save_settings(); cx.notify(); } "o" if !control => self.reveal_target(cx), @@ -3138,6 +4170,70 @@ pub fn restart_args( args } +/// A size typed in the Filter menu, in bytes: `None` for an empty field, +/// which asks nothing, and an error for anything that is not a size. +fn size_typed(text: &str, unit: usize) -> Result, ()> { + let text = text.trim(); + if text.is_empty() { + return Ok(None); + } + let number: f64 = text.parse().map_err(|_| ())?; + let bytes = + number * disktree_core::size::unit_step().powi(unit_power(unit)); + // `inf` and `nan` parse as numbers; neither is a size. + if !(bytes.is_finite() && (0.0..1e18).contains(&bytes)) { + return Err(()); + } + Ok(Some(bytes as u64)) +} + +/// `bytes` as the number to show in a size field read in `unit`, without +/// the zeros a whole number does not need. +fn size_shown(bytes: u64, unit: usize) -> String { + let number = + bytes as f64 / disktree_core::size::unit_step().powi(unit_power(unit)); + let text = format!("{number:.2}"); + text.trim_end_matches('0').trim_end_matches('.').to_owned() +} + +/// How many steps above a byte a unit of [`size_units`] is. +fn unit_power(unit: usize) -> i32 { + i32::try_from(unit.min(size_units().len() - 1)).unwrap_or(0) + 1 +} + +/// Order the picker's volumes by name, as a file manager lists drives: a +/// volume is found where its letter or name says, however full it happens +/// to be. Without regard to case, so `/Volumes/archive` is not sent below +/// every capital. +pub fn by_name(volumes: &mut [disktree_core::space::Volume]) { + volumes.sort_by_cached_key(|volume| { + volume.point.to_string_lossy().to_lowercase() + }); +} + +/// What was typed in the path field, as a path to look for: `~` is the home +/// directory, and a bare drive letter is that drive's root. `None` for a +/// relative path, which has no directory here to be relative to. +fn typed_path(typed: &str, home: Option<&Path>) -> Option { + if let Some(rest) = typed.strip_prefix('~') + && (rest.is_empty() || rest.starts_with(['/', '\\'])) + { + return Some(home?.join(rest.trim_start_matches(['/', '\\']))); + } + // `D:` alone means "the current directory on D" to Windows, which a + // window does not have; the drive is what was meant. + let drive = cfg!(windows) + && typed.len() == 2 + && typed.ends_with(':') + && typed.starts_with(|letter: char| letter.is_ascii_alphabetic()); + let path = if drive { + PathBuf::from(format!("{typed}\\")) + } else { + PathBuf::from(typed) + }; + path.is_absolute().then_some(path) +} + /// Now, in Unix seconds. pub fn now_seconds() -> i64 { std::time::SystemTime::now() diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rs index 3d7f151b..e4eb3e2f 100644 --- a/crates/disktree-app/src/tests.rs +++ b/crates/disktree-app/src/tests.rs @@ -552,6 +552,7 @@ fn enter_in_the_focused_volume_picker_scans_the_selected_root( point: target.clone(), device: None, space: None, + label: None, }]; app.volume_highlight = 0; app.volumes_open = true; @@ -586,11 +587,13 @@ fn the_volume_picker_is_centred_and_still_dismisses_from_outside( free: 500, available: 400, }), + label: None, }, Volume { point: PathBuf::from("/two"), device: None, space: None, + label: None, }, ]; app.volumes_open = true; @@ -1844,3 +1847,857 @@ fn the_power_menu_offers_only_what_the_cpus_can_tell_apart( draw(cx); assert!(read(&view, cx, |app| app.power_menu.is_none())); } + +#[test] +fn the_volume_picker_lists_volumes_by_name() { + let volume = |point: &str| Volume { + point: PathBuf::from(point), + device: None, + space: None, + label: None, + }; + let mut volumes = vec![volume("E:\\"), volume("c:\\"), volume("D:\\")]; + crate::state::by_name(&mut volumes); + let order: Vec<_> = volumes + .iter() + .map(|volume| volume.point.to_string_lossy().into_owned()) + .collect(); + assert_eq!(order, ["c:\\", "D:\\", "E:\\"]); +} + +#[gpui_kit::test] +fn a_click_on_a_key_hint_does_what_the_key_does(cx: &mut TestAppContext) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + + let click = |cx: &mut Window, selector: &'static str| { + let hint = cx.debug_bounds(selector).expect("the hint is drawn"); + cx.simulate_click(hint.center(), gpui_kit::Modifiers::none()); + draw(cx); + }; + + // `]` draws one level more; past the deepest the hint starts over. + assert_eq!(read(&view, cx, |app| app.layout_options.max_depth), 3); + click(cx, "key-depth"); + assert_eq!(read(&view, cx, |app| app.layout_options.max_depth), 4); + update(&view, cx, |app, cx| app.adjust_depth(2, cx)); + draw(cx); + click(cx, "key-depth"); + assert_eq!(read(&view, cx, |app| app.layout_options.max_depth), 1); + + // `?` opens the key list, and the keyboard still closes it: the click + // must not have left the keys with the hint. + click(cx, "key-all keys"); + assert!(read(&view, cx, |app| app.show_help)); + press(cx, "escape"); + assert!(!read(&view, cx, |app| app.show_help)); + + // `v` opens the picker, which takes the keyboard for itself. + click(cx, "key-volumes"); + assert!(read(&view, cx, |app| app.volumes_open)); + press(cx, "escape"); + assert!(!read(&view, cx, |app| app.volumes_open)); + + // `space` marks the selection, as the key does. + assert!(read(&view, cx, |app| app.marks.is_empty())); + click(cx, "key-mark"); + assert_eq!(read(&view, cx, |app| app.marks.len()), 1); + + // And on the review screen the footer's hints are buttons too. + click(cx, "key-review"); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Review); + click(cx, "key-back"); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Explore); +} + +#[gpui_kit::test] +fn the_empty_part_of_the_trail_opens_a_path_field(cx: &mut TestAppContext) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + + let space = cx + .debug_bounds("path-space") + .expect("room beside the trail"); + cx.simulate_click(space.center(), gpui_kit::Modifiers::none()); + draw(cx); + assert!(read(&view, cx, |app| app.path_open)); + assert!( + cx.debug_bounds("path-field").is_some(), + "the field is drawn" + ); + // It starts on the path on screen, to copy or to type over. + let shown = view.read_with(cx, |app, cx| { + app.path_input + .as_ref() + .map(|input| input.read(cx).value().to_string()) + }); + assert_eq!(shown, Some(temp.path().display().to_string())); + + // What is typed there is text: `c` must not open the review screen, + // nor `?` the key list. + update(&view, cx, Disktree::toggle_mark_selected); + press(cx, "c"); + press(cx, "?"); + read(&view, cx, |app| { + assert_eq!(app.screen, Screen::Explore); + assert!(!app.show_help); + assert!(app.path_open); + }); + + // Escape puts the trail back and the keys with the treemap. + press(cx, "escape"); + assert!(!read(&view, cx, |app| app.path_open)); + assert!(cx.debug_bounds("path-space").is_some()); + press(cx, "?"); + assert!(read(&view, cx, |app| app.show_help)); +} + +#[gpui_kit::test] +fn a_typed_path_goes_there_or_says_why_not(cx: &mut TestAppContext) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + // Canonical, as a root from the command line is. + let root = dunce::canonicalize(temp.path()).expect("root"); + let (view, cx) = view_over(&root, cx); + draw(cx); + + // Inside the tree: a step within it, and no new scan. + let deeper = root.join("junk").join("deeper"); + let quoted = format!(" \"{}\" ", deeper.display()); + assert!(update(&view, cx, |app, cx| app.go_to_path("ed, cx))); + read(&view, cx, |app| { + assert_eq!(app.current_path(), deeper); + assert_eq!(app.root_path, root); + assert!(app.scan.is_none(), "nothing was scanned again"); + }); + + // A file names the directory it is in. + let file = root.join("keep").join("notes.txt"); + let typed = file.display().to_string(); + assert!(update(&view, cx, |app, cx| app.go_to_path(&typed, cx))); + assert_eq!(read(&view, cx, Disktree::current_path), root.join("keep")); + + // Nowhere, and a path with nothing to be relative to: said, not done. + for typed in [root.join("no-such").display().to_string(), "junk".into()] { + assert!(!update(&view, cx, |app, cx| app.go_to_path(&typed, cx))); + read(&view, cx, |app| { + assert!(app.notice.is_some(), "{typed} is explained"); + assert_eq!(app.current_path(), root.join("keep")); + }); + } + + // Outside the scanned root: that directory becomes the root. + let other = tempfile::TempDir::new().expect("tempdir"); + let elsewhere = dunce::canonicalize(other.path()).expect("elsewhere"); + let typed = elsewhere.display().to_string(); + assert!(update(&view, cx, |app, cx| app.go_to_path(&typed, cx))); + assert_eq!(read(&view, cx, |app| app.root_path.clone()), elsewhere); + finish_scan(&view, cx); +} + +#[gpui_kit::test] +fn the_theme_steps_from_the_system_to_light_to_dark(cx: &mut TestAppContext) { + use crate::appearance::ThemeChoice; + use gpui_kit::base::ThemeAppearance; + use gpui_omarchy::ActiveTheme as _; + + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + assert_eq!(read(&view, cx, |app| app.theme_choice), ThemeChoice::System); + + press(cx, "shift-t"); + assert_eq!(read(&view, cx, |app| app.theme_choice), ThemeChoice::Light); + cx.update(|_, cx| { + assert!(matches!(cx.omarchy().appearance, ThemeAppearance::Light)); + }); + + // Round again, and a frame draws in each. + press(cx, "shift-t"); + assert_eq!(read(&view, cx, |app| app.theme_choice), ThemeChoice::Dark); + cx.update(|_, cx| { + assert!(matches!(cx.omarchy().appearance, ThemeAppearance::Dark)); + }); + // `t` alone is still the Size | Files | Age switch. + press(cx, "t"); + read(&view, cx, |app| { + assert_eq!(app.theme_choice, ThemeChoice::Dark); + assert_eq!(app.mode_index(), 1); + }); +} + +#[gpui_kit::test] +fn view_choices_are_written_down_as_they_change(cx: &mut TestAppContext) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let config = tempfile::TempDir::new().expect("tempdir"); + let path = config.path().join("disktree").join("settings"); + let (view, cx) = view_over(temp.path(), cx); + update(&view, cx, |app, _| app.settings_path = Some(path.clone())); + draw(cx); + assert!(!path.exists(), "nothing changed yet"); + + press(cx, "]"); + press(cx, "shift-t"); + press(cx, "p"); + let saved = crate::settings::load(&path).expect("saved"); + assert_eq!(saved.depth, 4); + assert_eq!(saved.theme, crate::appearance::ThemeChoice::Light); + assert!(!saved.show_selection); + + // And a window opened with them starts as this one was left. + let again = update(&view, cx, |app, _| { + app.show_selection = true; + app.apply_settings(&saved); + app.settings() + }); + assert!(!again.show_selection); + assert_eq!(again.theme, saved.theme); +} + +#[gpui_kit::test] +fn the_crumb_of_a_whole_volume_offers_the_other_volumes( + cx: &mut TestAppContext, +) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + // A directory with a disk above it is not one. + assert!(!read(&view, cx, Disktree::root_is_a_volume)); + update(&view, cx, |app, _| { + app.disk_root = Some(app.root_path.clone()); + }); + assert!(read(&view, cx, Disktree::root_is_a_volume)); + draw(cx); + + // The disk's label in the panel is the same way on. + let label = cx.debug_bounds("disk-label").expect("the disk label"); + cx.simulate_click(label.center(), gpui_kit::Modifiers::none()); + draw(cx); + assert!(read(&view, cx, |app| app.volumes_open)); +} + +#[gpui_kit::test] +fn a_page_closes_from_outside_it_and_not_from_inside(cx: &mut TestAppContext) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + + press(cx, "?"); + assert!(read(&view, cx, |app| app.show_help)); + // A press on the card is the card's own. + let card = cx.debug_bounds("help-card").expect("the key list"); + cx.simulate_click(card.center(), gpui_kit::Modifiers::none()); + draw(cx); + assert!(read(&view, cx, |app| app.show_help)); + // One beside it closes the page, and the keys are the treemap's again. + let page = cx.debug_bounds("help").expect("the page"); + let outside = Point::new(page.origin.x + px(4.), page.origin.y + px(4.)); + cx.simulate_click(outside, gpui_kit::Modifiers::none()); + draw(cx); + assert!(!read(&view, cx, |app| app.show_help)); + press(cx, "?"); + assert!(read(&view, cx, |app| app.show_help)); + press(cx, "escape"); + assert!(!read(&view, cx, |app| app.show_help)); +} + +#[gpui_kit::test] +fn the_settings_page_unlocks_deeper_levels(cx: &mut TestAppContext) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + + let gear = cx.debug_bounds("settings").expect("the settings button"); + cx.simulate_click(gear.center(), gpui_kit::Modifiers::none()); + draw(cx); + assert!(read(&view, cx, |app| app.settings_open)); + assert!(cx.debug_bounds("settings-card").is_some()); + // Nothing behind the page takes a key while it is up. + press(cx, "]"); + assert_eq!(read(&view, cx, |app| app.layout_options.max_depth), 3); + press(cx, "escape"); + assert!(!read(&view, cx, |app| app.settings_open)); + + // Six levels is as deep as the view goes until more are allowed. + for _ in 0..9 { + press(cx, "]"); + } + assert_eq!(read(&view, cx, |app| app.layout_options.max_depth), 6); + update(&view, cx, |app, cx| app.set_deep_levels(true, cx)); + for _ in 0..9 { + press(cx, "]"); + } + assert_eq!(read(&view, cx, |app| app.layout_options.max_depth), 10); + // Taking the allowance back brings the depth back within it. + update(&view, cx, |app, cx| app.set_deep_levels(false, cx)); + draw(cx); + assert_eq!(read(&view, cx, |app| app.layout_options.max_depth), 6); +} + +#[gpui_kit::test] +fn the_page_of_disks_scans_the_one_clicked(cx: &mut TestAppContext) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let target = temp.path().join("junk"); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + + let home = cx.debug_bounds("home").expect("the home button"); + cx.simulate_click(home.center(), gpui_kit::Modifiers::none()); + assert!(read(&view, cx, |app| app.home_open)); + // Fixed disks, so this is not about the machine running the test. + update(&view, cx, |app, cx| { + app.volumes = vec![ + Volume { + point: PathBuf::from("/elsewhere"), + device: None, + space: Some(SpaceInfo { + total: 1_000, + free: 50, + available: 40, + }), + label: Some("Nearly full".into()), + }, + Volume { + point: target.clone(), + device: None, + space: None, + label: None, + }, + ]; + app.volumes_loading = false; + cx.notify(); + }); + draw(cx); + // The treemap's keys are the page's while it is up. + press(cx, "c"); + assert_eq!(read(&view, cx, |app| app.screen), Screen::Explore); + press(cx, "down"); + assert_eq!(read(&view, cx, |app| app.volume_highlight), 1); + + let drive = cx.debug_bounds("drive-1").expect("the second disk"); + cx.simulate_click(drive.center(), gpui_kit::Modifiers::none()); + draw(cx); + read(&view, cx, |app| { + assert!(!app.home_open); + assert_eq!(app.root_path, target); + }); + finish_scan(&view, cx); +} + +#[gpui_kit::test] +fn the_filter_menu_narrows_by_size_and_kind(cx: &mut TestAppContext) { + use disktree_core::classify::Category; + + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + let click = |cx: &mut Window, selector: &'static str| { + let at = cx.debug_bounds(selector).expect(selector); + cx.simulate_click(at.center(), gpui_kit::Modifiers::none()); + draw(cx); + }; + + click(cx, "filter-control"); + assert!(read(&view, cx, |app| app.filter_menu)); + assert!( + cx.debug_bounds("filter-menu").is_some(), + "the menu is drawn" + ); + + // Kinds are ticked, any number of them, and the menu stays for more. + click(cx, "filter-kind-media"); + click(cx, "filter-kind-cache"); + read(&view, cx, |app| { + assert_eq!(app.filter_kinds, [Category::Media, Category::Cache]); + assert!(app.filter_menu); + // The name field is not where these are kept. + assert!(app.find.is_empty()); + }); + click(cx, "filter-kind-media"); + click(cx, "filter-kind-cache"); + assert!(read(&view, cx, |app| app.filter_kinds.is_empty())); + + // A least and a most, typed, in the unit picked: 150 to 250 KiB is + // the one 200 KiB blob, not the 300 KiB one or the 100 KiB one. + let (least, most) = + read(&view, cx, |app| app.size_inputs.clone()).expect("the fields"); + cx.update(|window, cx| { + least.update(cx, |field, cx| field.set_value("150", window, cx)); + most.update(cx, |field, cx| field.set_value("250", window, cx)); + }); + update(&view, cx, |app, cx| app.set_size_unit(0, 0, cx)); + update(&view, cx, |app, cx| app.set_size_unit(1, 0, cx)); + cx.run_until_parked(); + draw(cx); + read(&view, cx, |app| { + assert_eq!(app.filter_least, Some(150 << 10)); + assert_eq!(app.filter_most, Some(250 << 10)); + // Read back as a sentence, and counted for the button. + assert_eq!( + app.filter_sentence(), + "Showing files of from 150 KiB to 250 KiB" + ); + assert_eq!(app.filter_count(), 2); + let matches = app.matches.as_ref().expect("a filter"); + assert_eq!((matches.count, matches.bytes), (1, 200_000)); + assert!(app.filter_applied); + }); + + // Not a number, or the wrong way round: said, and nothing changes. + cx.update(|window, cx| { + least.update(cx, |field, cx| field.set_value("lots", window, cx)); + }); + update(&view, cx, Disktree::apply_sizes); + draw(cx); + read(&view, cx, |app| { + // Said for the field it is in, with the way out of it. + let (side, why) = app.size_error.clone().expect("an error"); + assert_eq!(side, 0); + assert!(why.starts_with("Min is not a number"), "{why}"); + assert_eq!(app.filter_least, Some(150 << 10)); + }); + assert!( + cx.debug_bounds("filter-size-error").is_some(), + "the error is drawn beside its field" + ); + cx.update(|window, cx| { + least.update(cx, |field, cx| field.set_value("300", window, cx)); + }); + update(&view, cx, Disktree::apply_sizes); + read(&view, cx, |app| { + let (side, why) = app.size_error.clone().expect("an error"); + assert_eq!(side, 1); + assert!(why.starts_with("Max is below Min"), "{why}"); + }); + // Apply puts the keyboard in the field that is wrong: Max, here. + click(cx, "filter-apply"); + let in_max = cx.update(|window, cx| { + use gpui_kit::Focusable as _; + most.read(cx).focus_handle(cx).is_focused(window) + }); + assert!(in_max, "the Max field has the keyboard"); + // Put right, the error goes; nothing is left greyed out meanwhile. + cx.update(|window, cx| { + least.update(cx, |field, cx| field.set_value("150", window, cx)); + }); + click(cx, "filter-apply"); + read(&view, cx, |app| { + assert!(app.size_error.is_none()); + assert_eq!(app.filter_least, Some(150 << 10)); + }); + assert!(cx.debug_bounds("filter-size-error").is_none()); + + // Escape closes the menu and leaves the filter; Clear lifts it. + press(cx, "escape"); + read(&view, cx, |app| { + assert!(!app.filter_menu); + assert!(app.filter_chosen()); + }); + cx.update(|window, cx| { + view.update(cx, |app, cx| app.clear_chosen_filter(window, cx)); + }); + cx.run_until_parked(); + read(&view, cx, |app| { + assert!(!app.filter_chosen()); + assert!(app.matches.is_none()); + }); +} + +#[gpui_kit::test] +fn the_name_filter_has_a_button_of_its_own(cx: &mut TestAppContext) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + let name = cx.debug_bounds("filter-name").expect("the Name button"); + cx.simulate_click(name.center(), gpui_kit::Modifiers::none()); + draw(cx); + read(&view, cx, |app| { + assert!(app.find_open); + assert!(!app.filter_menu); + }); + // What is typed is the name, and only the name. + press(cx, "b l o b"); + read(&view, cx, |app| { + assert_eq!(app.find, "blob"); + assert!(!app.filter_chosen()); + }); +} + +#[gpui_kit::test] +fn the_settings_page_changes_the_theme_and_names_the_build( + cx: &mut TestAppContext, +) { + use crate::appearance::ThemeChoice; + use gpui_kit::base::ThemeAppearance; + use gpui_omarchy::ActiveTheme as _; + + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + let click = |cx: &mut Window, selector: &'static str| { + let at = cx.debug_bounds(selector).expect(selector); + cx.simulate_click(at.center(), gpui_kit::Modifiers::none()); + draw(cx); + }; + click(cx, "settings"); + assert!(cx.debug_bounds("about").is_some(), "version and build"); + + // Each button puts its theme in force, and the page stays open. + for (selector, choice, appearance) in [ + ("theme-light", ThemeChoice::Light, ThemeAppearance::Light), + ("theme-dark", ThemeChoice::Dark, ThemeAppearance::Dark), + ("theme-light", ThemeChoice::Light, ThemeAppearance::Light), + ] { + click(cx, selector); + read(&view, cx, |app| { + assert_eq!(app.theme_choice, choice); + assert!(app.settings_open); + }); + cx.update(|_, cx| assert_eq!(cx.omarchy().appearance, appearance)); + } + // And the key agrees with the buttons about which one is on. + press(cx, "escape"); + press(cx, "shift-t"); + assert_eq!(read(&view, cx, |app| app.theme_choice), ThemeChoice::Dark); +} + +#[gpui_kit::test] +fn worth_a_look_lists_more_when_asked(cx: &mut TestAppContext) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + assert!(!read(&view, cx, |app| app.insights_all)); + update(&view, cx, Disktree::toggle_insights); + draw(cx); + assert!(read(&view, cx, |app| app.insights_all)); + assert!(cx.debug_bounds("disktree-root").is_some()); + // The way back is under the lists, not at the foot of them: it is + // there to press however far the long list runs. + let lists = cx.debug_bounds("panel-lists").expect("the lists"); + let toggle = cx.debug_bounds("insights-more").expect("Show fewer"); + assert!( + toggle.origin.y >= lists.origin.y + lists.size.height, + "the button is outside what scrolls" + ); + cx.simulate_click( + toggle.origin + gpui_kit::point(gpui_kit::px(12.), gpui_kit::px(8.)), + gpui_kit::Modifiers::none(), + ); + draw(cx); + assert!(!read(&view, cx, |app| app.insights_all)); +} + +#[gpui_kit::test] +fn each_size_has_its_own_unit(cx: &mut TestAppContext) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + cx.update(|window, cx| { + view.update(cx, |app, cx| app.toggle_filter_menu(window, cx)); + }); + draw(cx); + let (least, most) = + read(&view, cx, |app| app.size_inputs.clone()).expect("the fields"); + cx.update(|window, cx| { + least.update(cx, |field, cx| field.set_value("150", window, cx)); + most.update(cx, |field, cx| field.set_value("1", window, cx)); + }); + // 150 KiB to 1 MiB: the min in one unit, the max in another. + update(&view, cx, |app, cx| app.set_size_unit(0, 0, cx)); + update(&view, cx, |app, cx| app.set_size_unit(1, 1, cx)); + cx.run_until_parked(); + draw(cx); + read(&view, cx, |app| { + assert_eq!(app.size_unit, [0, 1]); + assert_eq!(app.filter_least, Some(150 << 10)); + assert_eq!(app.filter_most, Some(1 << 20)); + assert_eq!(app.matches.as_ref().map(|found| found.count), Some(2)); + }); + assert!(cx.debug_bounds("filter-size-summary").is_some()); + assert!(cx.debug_bounds("filter-summary").is_some()); + read(&view, cx, |app| { + assert_eq!( + app.filter_sentence(), + "Showing files of from 150 KiB to 1.0 MiB" + ); + }); +} + +#[gpui_kit::test] +fn a_size_has_a_dropdown_for_its_unit_and_a_cross_to_empty_it( + cx: &mut TestAppContext, +) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + cx.update(|window, cx| { + view.update(cx, |app, cx| app.toggle_filter_menu(window, cx)); + }); + draw(cx); + // Min and Max share a line: the Max field is beside the Min one. + let least = cx.debug_bounds("filter-least").expect("Min"); + let most = cx.debug_bounds("filter-most").expect("Max"); + assert_eq!(least.origin.y, most.origin.y); + assert!(most.origin.x > least.origin.x); + // An empty field has nothing to clear. + assert!(cx.debug_bounds("filter-least-clear").is_none()); + + press(cx, "1 5 0 enter"); + draw(cx); + assert_eq!(read(&view, cx, |app| app.filter_least), Some(150 << 20)); + + // The unit is picked from a dropdown, and what is picked is read at + // once: the 150 typed now means KiB. + let selects = + read(&view, cx, |app| app.unit_selects.clone()).expect("dropdowns"); + let unit = cx.debug_bounds("filter-unit-0").expect("the Min unit"); + cx.simulate_click(unit.center(), gpui_kit::Modifiers::none()); + draw(cx); + assert!(cx.update(|_, cx| selects[0].read(cx).is_open())); + assert!(cx.debug_bounds("omarchy-choice-popup").is_some()); + // Escape there closes the dropdown, not the menu under it. + press(cx, "escape"); + draw(cx); + assert!(read(&view, cx, |app| app.filter_menu)); + cx.update(|_, cx| { + selects[0].update(cx, |select, cx| select.set_selected(Some(0), cx)); + }); + cx.run_until_parked(); + draw(cx); + read(&view, cx, |app| { + assert_eq!(app.size_unit, [0, 1]); + assert_eq!(app.filter_least, Some(150 << 10)); + }); + + // The largest unit on offer is the terabyte. + let (_, most) = + read(&view, cx, |app| app.size_inputs.clone()).expect("the fields"); + cx.update(|window, cx| { + most.update(cx, |field, cx| field.set_value("1.5", window, cx)); + selects[1].update(cx, |select, cx| select.set_selected(Some(3), cx)); + }); + cx.run_until_parked(); + draw(cx); + read(&view, cx, |app| { + assert_eq!(crate::state::size_units()[3], "TiB"); + assert_eq!(app.filter_most, Some(3 << 39)); + }); + + // The cross in the field empties it and lifts that limit. + let clear = cx.debug_bounds("filter-least-clear").expect("the cross"); + cx.simulate_click(clear.center(), gpui_kit::Modifiers::none()); + draw(cx); + read(&view, cx, |app| { + assert_eq!(app.filter_least, None); + assert!(app.filter_menu); + }); + assert!(cx.debug_bounds("filter-least-clear").is_none()); +} + +#[gpui_kit::test] +fn the_name_and_the_menu_are_cleared_apart_and_a_miss_is_said( + cx: &mut TestAppContext, +) { + use disktree_core::classify::Category; + + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + cx.update(|window, cx| { + view.update(cx, |app, cx| app.toggle_filter_menu(window, cx)); + }); + draw(cx); + // A size typed with more digits than it is shown with. + let (least, _) = + read(&view, cx, |app| app.size_inputs.clone()).expect("the fields"); + cx.update(|window, cx| { + least.update(cx, |field, cx| field.set_value("0.1234", window, cx)); + }); + update(&view, cx, Disktree::apply_sizes); + let typed = read(&view, cx, |app| app.filter_least); + press(cx, "escape"); + cx.update(|window, cx| { + view.update(cx, |app, cx| app.toggle_filter_menu(window, cx)); + }); + draw(cx); + // Reopened, it reads as it was typed, and Apply moves nothing. + assert_eq!( + cx.update(|_, cx| least.read(cx).value().to_string()), + "0.1234" + ); + update(&view, cx, Disktree::apply_sizes); + assert_eq!(read(&view, cx, |app| app.filter_least), typed); + press(cx, "escape"); + + // Escape in the name field drops the name and leaves the menu's. + press(cx, "/"); + press(cx, "b l o b"); + press(cx, "escape"); + cx.run_until_parked(); + read(&view, cx, |app| { + assert!(app.find.is_empty()); + assert!(!app.find_open); + assert_eq!(app.filter_least, typed); + }); + + // A kind nothing here is: said, since nothing is then hidden. + update(&view, cx, |app, cx| { + app.filter_least = None; + app.toggle_filter_kind(Category::Git, cx); + }); + cx.run_until_parked(); + read(&view, cx, |app| { + assert_eq!(app.matches.as_ref().map(|found| found.count), Some(0)); + assert_eq!( + app.filter_sentence(), + "Nothing here matches, so everything is shown" + ); + }); +} + +#[gpui_kit::test] +fn the_filter_menu_is_walked_and_worked_by_keyboard(cx: &mut TestAppContext) { + use disktree_core::classify::Category; + + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + cx.update(|window, cx| { + view.update(cx, |app, cx| app.toggle_filter_menu(window, cx)); + }); + draw(cx); + // Nothing to clear, so no Clear button rather than a greyed one. + assert!(cx.debug_bounds("filter-clear").is_none()); + assert_eq!( + read(&view, cx, Disktree::filter_sentence), + "Showing everything" + ); + + // The keyboard starts in the Min field: digits are text there, and + // Enter applies. + press(cx, "2 0 0 enter"); + draw(cx); + read(&view, cx, |app| { + assert_eq!(app.filter_least, Some(200 << 20)); + assert!(app.filter_menu); + }); + assert!(cx.debug_bounds("filter-clear").is_some()); + + // Shift+Tab walks back out of the field to the kinds above it, the + // last of them first, and Space ticks the one in focus. + press(cx, "shift-tab"); + draw(cx); + // A control answers the key coming up, as a native button does. + let space = gpui_kit::Keystroke::parse("space").expect("a key"); + cx.simulate_event(gpui_kit::KeyDownEvent { + keystroke: space.clone(), + is_held: false, + prefer_character_input: false, + }); + cx.simulate_event(gpui_kit::KeyUpEvent { keystroke: space }); + draw(cx); + read(&view, cx, |app| { + assert_eq!( + app.filter_kinds, + [*Category::LEGEND.last().expect("a kind")] + ); + assert_eq!(app.filter_count(), 2); + assert!(app.filter_menu, "the menu stays for more"); + }); + + // The way out is a button as well as a key. + let close = cx.debug_bounds("filter-done").expect("Close"); + cx.simulate_click(close.center(), gpui_kit::Modifiers::none()); + draw(cx); + assert!(!read(&view, cx, |app| app.filter_menu)); +} + +#[gpui_kit::test] +fn another_machine_is_looked_at_and_never_acted_on(cx: &mut TestAppContext) { + use disktree_core::remote::Remote; + + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + update(&view, cx, Disktree::toggle_mark_selected); + assert_eq!(read(&view, cx, |app| app.marks.len()), 1); + assert!(cx.debug_bounds("mark-button").is_some()); + assert!(cx.debug_bounds("key-mark").is_some()); + + // The page of disks has the address field; nonsense is said, not tried. + let home = cx.debug_bounds("home").expect("the home button"); + cx.simulate_click(home.center(), gpui_kit::Modifiers::none()); + draw(cx); + assert!( + cx.debug_bounds("ssh-address").is_some(), + "the address field" + ); + update(&view, cx, Disktree::connect_ssh); + read(&view, cx, |app| { + assert!(app.remote.is_none()); + assert!(app.notice.is_some()); + }); + + // Stand in for a scan of another machine: the tree on screen with a + // remote set, as it is once a listing lands. Nothing is connected to. + update(&view, cx, |app, cx| { + app.close_home(cx); + app.remote = Remote::parse("me@box:/srv/data"); + app.marks.clear(); + cx.notify(); + }); + draw(cx); + // Its paths read as its own, whatever this machine joins them with, + // and nothing offers to mark one or to restart as an administrator. + read(&view, cx, |app| { + let inside = app.root_path.join("srv").join("data"); + assert_eq!(app.shown_path(&inside), { + let root = app.root_path.to_string_lossy().replace('\\', "/"); + format!("{root}/srv/data") + }); + }); + assert!(cx.debug_bounds("mark-button").is_none()); + assert!(cx.debug_bounds("key-mark").is_none()); + assert!(cx.debug_bounds("key-review").is_none()); + assert!(cx.debug_bounds("key-open").is_some()); + // Marking says why not, and marks nothing; so does the file manager. + press(cx, "space"); + read(&view, cx, |app| { + assert!(app.marks.is_empty()); + let (text, _) = app.notice.as_ref().expect("a reason"); + assert!(text.contains("read-only"), "{text}"); + }); + update(&view, cx, |app, cx| { + app.notice = None; + app.reveal_target(cx); + assert!(app.notice.is_some()); + app.begin_removal(cx); + assert_eq!(app.screen, Screen::Explore); + }); + // A local root is a local scan again, with everything it allows. + let root = temp.path().to_path_buf(); + update(&view, cx, |app, cx| app.set_root(root, cx)); + assert!(read(&view, cx, |app| app.remote.is_none())); + finish_scan(&view, cx); + press(cx, "space"); + assert_eq!(read(&view, cx, |app| app.marks.len()), 1); +} diff --git a/crates/disktree-app/src/ui.rs b/crates/disktree-app/src/ui.rs index ea715d25..95dd6a6b 100644 --- a/crates/disktree-app/src/ui.rs +++ b/crates/disktree-app/src/ui.rs @@ -21,6 +21,8 @@ use gpui_kit::Rems; pub mod space { use super::Rems; + /// None at all: a control whose height is set, not padded out. + pub const NONE: Rems = Rems(0.0); /// Optical correction: an icon baseline, a compact separator. pub const XXS: Rems = Rems(0.125); /// Parts of one control: icon and label, title and its description. @@ -98,6 +100,17 @@ pub mod size { pub const TOOLTIP: Rems = Rems(16.75); /// The keyboard overlay. pub const HELP: Rems = Rems(32.5); + /// The Filter menu: Min and Max side by side, each a field and a unit. + pub const FILTER_MENU: Rems = Rems(28.0); + /// A size's unit, as a dropdown: `MiB` and the arrow that opens it. + pub const UNIT_SELECT: Rems = Rems(5.0); + /// The least height of something to press in that menu: 32 px at the + /// default rem, over the 24 px WCAG 2.2 asks of a pointer target. + pub const TARGET: Rems = Rems(2.0); + /// The page of disks: three cards across at the default rem. + pub const HOME: Rems = Rems(58.0); + /// One disk on that page: wide enough for a label and its letter. + pub const DRIVE_CARD: Rems = Rems(16.0); /// The key column of the keyboard overlay. pub const KEY_LANE: Rems = Rems(7.0); } diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index c23e91b3..a94c87f0 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -93,6 +93,9 @@ pub fn root( cx.notify(); return; } + if this.on_window_key(event, window, cx) { + return; + } this.on_key_down(event, cx); this.apply_focus(window, cx); })) @@ -111,6 +114,12 @@ pub fn root( if app.show_help { root = root.child(help_overlay(app, cx)); } + if app.home_open { + root = root.child(home_page(app, window, cx)); + } + if app.settings_open { + root = root.child(settings_page(app, cx)); + } if app.volumes_open { root = root.child(volumes_dialog(app, cx)); } @@ -142,16 +151,13 @@ fn volumes_dialog( } for (index, volume) in app.volumes.iter().enumerate() { let highlighted = index == app.volume_highlight; - let free = volume.space.map_or_else( - || "unknown free".to_string(), - |space| format!("{} free", human_bytes(space.available)), - ); + let name = volume_name(volume); + let room = volume_room(volume); let label = match &volume.device { - Some(device) => format!( - "{} \u{00b7} {device} \u{00b7} {free}", - volume.point.display() - ), - None => format!("{} \u{00b7} {free}", volume.point.display()), + Some(device) => { + format!("{name} \u{00b7} {device} \u{00b7} {room}") + } + None => format!("{name} \u{00b7} {room}"), }; rows = rows.child( div() @@ -250,6 +256,510 @@ fn centred_popup( ) } +/// A page over the dimmed window: the keys, the settings, the disks. A +/// press outside the card closes it, as Escape does; one on the card is the +/// card's own, and nothing reaches the screen behind either way. +fn modal( + id: &'static str, + theme: &Theme, + card: impl IntoElement, + close: fn(&mut Disktree, &mut Context<'_, Disktree>), + cx: &Context<'_, Disktree>, +) -> Stateful
{ + div() + .id(id) + .debug_selector(move || id.into()) + .absolute() + .inset_0() + .flex() + .items_center() + .justify_center() + .bg(theme.background.opacity(0.86)) + .on_any_mouse_down(cx.listener( + move |this, _: &MouseDownEvent, window, cx| { + cx.stop_propagation(); + close(this, cx); + window.focus(&this.focus, cx); + }, + )) + .child( + div() + .id(ElementId::Name(format!("{id}-card").into())) + .debug_selector(move || format!("{id}-card")) + .on_any_mouse_down( + |_: &MouseDownEvent, _: &mut Window, cx: &mut App| { + cx.stop_propagation(); + }, + ) + .child(card), + ) +} + +/// A page's heading with the way out of it at the far end, for a hand on +/// the mouse; Escape and a press outside do the same. +fn page_header( + id: &'static str, + glyph: gpui_omarchy::IconName, + title: &'static str, + close: fn(&mut Disktree, &mut Context<'_, Disktree>), + cx: &Context<'_, Disktree>, +) -> Div { + let theme = cx.omarchy(); + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .child( + gpui_omarchy::icon(glyph) + .size(icon::MD) + .text_color(theme.accent), + ) + .child( + div() + .text_size(text::TITLE) + .font_weight(FontWeight::BOLD) + .text_color(theme.bright) + .child(title), + ) + .child(div().flex_1()) + .child( + button(id, "Close", ButtonVariant::Secondary, cx) + .tab_stop(false) + .on_click(cx.listener(move |this, _, window, cx| { + close(this, cx); + window.focus(&this.focus, cx); + })), + ) +} + +/// A volume as a file manager names it: its label, then where it is +/// mounted, `Data (D:)`; or the mount point alone when it has no label. +fn volume_name(volume: &disktree_core::space::Volume) -> String { + let point = volume.point.display().to_string(); + match &volume.label { + Some(label) => { + let short = point.trim_end_matches(['\\', '/']); + let short = if short.is_empty() { &point } else { short }; + format!("{label} ({short})") + } + None => point, + } +} + +/// How much room a volume has, of how much: `23 GiB free of 317 GiB`. +fn volume_room(volume: &disktree_core::space::Volume) -> String { + volume.space.map_or_else( + || "size unknown".to_string(), + |space| { + format!( + "{} free of {}", + human_bytes(space.available), + human_bytes(space.total) + ) + }, + ) +} + +/// How full a volume has to be before its bar turns to the danger colour, +/// the way a file manager warns that a drive is nearly out of room. +const NEARLY_FULL: f32 = 0.9; + +/// Every disk, as the first page of a file manager shows them: name, a bar +/// of what is used, and the room left. A click scans that one. +fn home_page( + app: &Disktree, + window: &Window, + cx: &mut Context<'_, Disktree>, +) -> Stateful
{ + let theme = cx.omarchy().clone(); + let close: fn(&mut Disktree, &mut Context<'_, Disktree>) = + Disktree::close_home; + let mut drives = div() + .id("home-drives") + .flex() + .flex_row() + .flex_wrap() + .gap(space::LG); + if app.volumes_loading { + drives = drives.child( + div() + .text_color(theme.secondary) + .child("Looking for disks\u{2026}"), + ); + } else if app.volumes.is_empty() { + drives = drives.child( + div() + .text_color(theme.secondary) + .child("No disk could be read."), + ); + } + for (index, volume) in app.volumes.iter().enumerate() { + let highlighted = index == app.volume_highlight; + let scanned = app.root_path.starts_with(&volume.point); + let used = volume.space.map_or(0.0, |space| { + (space.used() as f32 / space.total.max(1) as f32).clamp(0.0, 1.0) + }); + let fill = if used >= NEARLY_FULL { + theme.danger + } else { + theme.accent + }; + drives = drives.child( + div() + .id(ElementId::Name(format!("drive-{index}").into())) + .debug_selector(move || format!("drive-{index}")) + .flex() + .flex_row() + .items_center() + .gap(space::MD) + .w(size::DRIVE_CARD) + .p(space::MD) + .border_1() + .border_color(if highlighted { + theme.accent + } else { + theme.control_border() + }) + .when(highlighted, |card| card.bg(theme.accent.opacity(0.12))) + .hover(|card| card.bg(theme.hover_fill())) + .cursor_pointer() + .on_click(cx.listener(move |this, _, window, cx| { + this.volume_highlight = index; + this.choose_volume(cx); + window.focus(&this.focus, cx); + })) + .child( + gpui_omarchy::icon(gpui_omarchy::IconName::HardDrive) + .size(icon::LG) + .text_color(theme.secondary), + ) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .gap(space::XS) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .child( + div() + .flex_1() + .min_w_0() + .text_size(text::BODY) + .text_color(theme.bright) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(volume_name(volume)), + ) + .when(scanned, |row| { + row.child(widgets::chip( + "scanned", + theme.accent, + cx, + )) + }), + ) + .child(widgets::bar(used, fill, cx)) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(volume_room(volume)), + ) + // Where a volume has no label, as on Linux, its + // device is what tells two apart. On a line of its + // own: beside the room it pushed the total out of + // the card. + .children(volume.device.clone().map(|device| { + div() + .text_size(text::CAPTION) + .text_color(theme.secondary.opacity(0.7)) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(device) + })), + ), + ); + } + let card = div() + .flex() + .flex_col() + .gap(space::LG) + .w(size::HOME) + .max_w(relative(0.94)) + .p(space::XL) + .border_1() + .border_color(theme.border) + .bg(theme.surface) + .child(page_header( + "home-close", + gpui_omarchy::IconName::HardDrive, + "Disks", + close, + cx, + )) + .child(drives) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child( + "Click a disk to scan it \u{00b7} up, down and enter work \ + too \u{00b7} esc stays here", + ), + ) + .children(app.ssh_input.clone().map(|input| { + div() + .flex() + .flex_col() + .gap(space::SM) + .pt(space::SM) + .border_t_1() + .border_color(theme.divider()) + .child(widgets::eyebrow("Another machine, over SSH", cx)) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .child( + div() + .id("ssh-address") + .debug_selector(|| "ssh-address".into()) + .flex_1() + .min_w_0() + .child(gpui_omarchy::input( + "ssh-input", + &input, + window, + cx, + )), + ) + .child( + button( + "ssh-connect", + "Connect", + ButtonVariant::Outline, + cx, + ) + .tab_stop(false) + .on_click(cx.listener( + |this, _, window, cx| { + this.connect_ssh(cx); + this.apply_focus(window, cx); + }, + )), + ), + ) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child( + "user@host:/path \u{00b7} uses your own ssh keys \ + and config, never a password \u{00b7} needs a \ + Linux machine \u{00b7} to look at only: nothing \ + there can be marked or removed", + ), + ) + .children(app.notice.as_ref().map(|(text, status)| { + div() + .text_size(text::CAPTION) + .text_color(widgets::alert_color(*status, cx)) + .child(text.clone()) + })) + })); + modal("home", &theme, card, close, cx) +} + +/// The choices that are made once and kept: the theme, how deep the view +/// may go, and on Windows a shortcut to the program. +fn settings_page( + app: &Disktree, + cx: &mut Context<'_, Disktree>, +) -> Stateful
{ + use crate::appearance::ThemeChoice; + use crate::shortcut::Place; + use crate::state::{DEEP_LEVELS, USUAL_LEVELS}; + + let theme = cx.omarchy().clone(); + let close: fn(&mut Disktree, &mut Context<'_, Disktree>) = + Disktree::close_settings; + let entity = cx.entity().downgrade(); + let row = |label: &'static str, cx: &App| { + div() + .flex() + .flex_col() + .gap(space::SM) + .child(widgets::eyebrow(label, cx)) + }; + + // Three buttons of our own rather than the toolkit's group, which + // keeps a selection of its own: the theme also changes from `T`, and + // the two could then disagree about which one is on. + let mut themes = div().flex().flex_row().gap(space::XS); + for choice in ThemeChoice::ALL { + themes = themes.child( + segment( + format!("theme-{}", choice.key()), + choice.name(), + choice == app.theme_choice, + &theme, + ) + .on_click(cx.listener(move |this, _, window, cx| { + this.set_theme(choice, window, cx); + })), + ); + } + let deep = checkbox( + "settings-deep", + format!("Allow up to {DEEP_LEVELS} levels at once"), + if app.deep_levels { + CheckboxState::Checked + } else { + CheckboxState::Unchecked + }, + cx, + ) + .tab_stop(false) + .on_change(move |_, _, _, cx| { + let _ = entity.update(cx, |this, cx| { + this.set_deep_levels(!this.deep_levels, cx); + }); + }); + let shortcut = |id: &'static str, + label: &'static str, + place: Place, + cx: &mut Context<'_, Disktree>| { + button(id, label, ButtonVariant::Outline, cx) + .tab_stop(false) + .on_click(cx.listener(move |_, _, _, cx| { + Disktree::create_shortcut(place, cx); + })) + }; + + let mut card = div() + .flex() + .flex_col() + .gap(space::LG) + .w(size::HELP) + .p(space::XL) + .border_1() + .border_color(theme.border) + .bg(theme.surface) + .child(page_header( + "settings-close", + gpui_omarchy::IconName::Settings, + "Settings", + close, + cx, + )) + .child(row("Theme", cx).child(themes)) + .child( + row("Depth", cx).child(deep).child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(format!( + "The depth control stops at {USUAL_LEVELS} levels \ + otherwise. Deeper draws many more tiles, most of \ + them too small to read, and a whole disk gets slow." + )), + ), + ); + if cfg!(windows) { + card = card.child( + row("Shortcuts", cx).child( + div() + .flex() + .flex_row() + .gap(space::SM) + .child(shortcut( + "shortcut-start", + "Add to Start menu", + Place::StartMenu, + cx, + )) + .child(shortcut( + "shortcut-desktop", + "Add to desktop", + Place::Desktop, + cx, + )), + ), + ); + } + if let Some((text, status)) = &app.notice { + card = card.child( + div() + .text_size(text::CAPTION) + .text_color(widgets::alert_color(*status, cx)) + .child(text.clone()), + ); + } + let decimal = disktree_core::size::decimal_units(); + let mut units = div().flex().flex_row().gap(space::XS); + for (id, label, on) in [ + ("units-gib", "GiB \u{00b7} 1024", false), + ("units-gb", "GB \u{00b7} 1000", true), + ] { + units = units.child( + segment(id.to_owned(), label, on == decimal, &theme).on_click( + cx.listener(move |this, _, _, cx| { + this.set_decimal_units(on, cx); + }), + ), + ); + } + card = card.child( + row("Sizes", cx).child(units).child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child( + "GiB counts in 1024s, as this app and Linux do. GB \ + counts in 1000s, as a drive's box does: a 500 GB drive \ + is 465 GiB.", + ), + ), + ); + card = card.child( + row("About", cx).child( + div() + .id("about") + .debug_selector(|| "about".into()) + .text_size(text::BODY) + .text_color(theme.foreground) + .child(format!( + "disktree {} \u{00b7} build {}", + env!("CARGO_PKG_VERSION"), + env!("DISKTREE_BUILD") + )), + ), + ); + if let Some(path) = &app.settings_path { + card = card.child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary.opacity(0.7)) + .child(format!("Kept in {}", path.display())), + ); + } + modal("settings", &theme, card, close, cx) +} + /// The one question disktree asks: a permanent deletion cannot be undone, so /// it is an alert dialog that names what goes and what comes back. The trash is /// reversible and needs no dialog. @@ -391,7 +901,7 @@ fn explore( .flex_1() .min_w_0() .min_h_0() - .child(trail_and_legend(app, &theme, cx)) + .child(trail_and_legend(app, &theme, window, cx)) .child( div() .flex() @@ -402,13 +912,17 @@ fn explore( .child(viewport), ), ) - .children(panel.then(|| side_panel(app, &theme, cx))), + .children(panel.then(|| side_panel(app, &theme, window, cx))), ) .child(key_bar(app, &theme, cx)) } /// The selection, when it is a checkout git can say something about. fn selection_checkout(app: &Disktree) -> Option { + // On another machine there is no checkout here to ask git about. + if app.remote.is_some() { + return None; + } let target = app.action_target()?; let node = app.node_at(&target)?; if !node.is_dir() { @@ -448,7 +962,7 @@ fn top_bar( window: &mut Window, cx: &mut Context<'_, Disktree>, ) -> Div { - div() + let bar = div() .flex() .flex_row() .items_center() @@ -458,10 +972,55 @@ fn top_bar( .border_b_1() .border_color(theme.divider()) .child(logo(theme)) + .child(with_tooltip( + bar_icon("home", gpui_omarchy::IconName::HardDrive, theme) + .on_click(cx.listener(|this, _, window, cx| { + this.open_home(window, cx); + window.focus(&this.focus, cx); + })), + "Every disk, to scan another", + )); + let bar = match app.path_input.clone().filter(|_| app.path_open) { + Some(input) => bar.child( + div() + .id("path-field") + .debug_selector(|| "path-field".into()) + .flex_1() + .min_w_0() + // Framed in the accent, so the row plainly became a field + // to type in: the input's own border is the bar's colour. + .border_1() + .border_color(theme.accent) + .child(gpui_omarchy::input("path-input", &input, window, cx)), + ), // Where you are is navigation, and it belongs to the whole window. - .child(trail(app, theme, cx)) - .child(div().flex_1()) - .child(view_settings(app, window, cx)) + None => bar.child(trail(app, theme, cx)).child(path_space(cx)), + }; + bar.child(view_settings(app, window, cx)) +} + +/// The empty part of the trail's row. A click there turns the trail into a +/// text field holding the path, as the same spot does in a file manager's +/// address bar: to copy it, or to type or paste another. +fn path_space(cx: &Context<'_, Disktree>) -> Stateful
{ + with_tooltip( + div() + .id("path-space") + .debug_selector(|| "path-space".into()) + .flex_1() + // The row centres its children, and an empty one has no + // height of its own to click on. + .self_stretch() + .cursor_text() + .on_click(cx.listener(|this, _, window, cx| { + this.open_path_bar(window, cx); + })), + if cfg!(target_os = "macos") { + "Type or paste a path \u{00b7} \u{2318}L" + } else { + "Type or paste a path \u{00b7} ctrl l" + }, + ) } /// The trail, from `/`. Above the scanned root, a crumb widens the scan; @@ -489,7 +1048,7 @@ fn trail(app: &Disktree, theme: &Theme, cx: &Context<'_, Disktree>) -> Div { for (index, (label, step)) in steps.into_iter().enumerate() { if hidden.contains(&index) { if index == hidden.start { - row = row.child(separator_glyph(theme)).child( + row = row.child(separator_glyph(app, theme)).child( div() .px(space::XS) .text_color(theme.secondary.opacity(0.6)) @@ -500,7 +1059,7 @@ fn trail(app: &Disktree, theme: &Theme, cx: &Context<'_, Disktree>) -> Div { } // The root is its own separator: "/" then "home", not "/ / home". if index > 1 { - row = row.child(separator_glyph(theme)); + row = row.child(separator_glyph(app, theme)); } let id = ElementId::Name(SharedString::from(format!("crumb-{index}"))); let crumb = match step { @@ -533,12 +1092,17 @@ fn trail(app: &Disktree, theme: &Theme, cx: &Context<'_, Disktree>) -> Div { const TRAIL_STEPS: usize = 7; /// The platform's path separator, so the trail reads like the paths shown -/// elsewhere: `/` here, `\` on Windows. -fn separator_glyph(theme: &Theme) -> Div { +/// elsewhere: `/` here, `\` on Windows. Another machine's paths are +/// listed by `find`, and are always `/`. +fn separator_glyph(app: &Disktree, theme: &Theme) -> Div { div() .text_color(theme.secondary.opacity(0.5)) .text_size(text::BODY) - .child(std::path::MAIN_SEPARATOR_STR) + .child(if app.remote.is_some() { + "/" + } else { + std::path::MAIN_SEPARATOR_STR + }) } /// A crumb in the tree. Its label goes there (the current one opens the @@ -553,12 +1117,28 @@ fn tree_crumb( cx: &Context<'_, Disktree>, ) -> gpui_kit::AnyElement { let Some((&index, parent)) = path.split_last() else { - // The scanned root: no siblings in the tree to offer. - return widgets::crumb(id, label, current, cx) - .on_click( - cx.listener(move |this, _, _, cx| this.go_to(Vec::new(), cx)), - ) - .into_any_element(); + // The scanned root: no siblings in the tree to offer. Being there + // already, the crumb of a whole volume offers the other volumes + // instead, as a current crumb in the tree offers its siblings. + let volumes = current && app.root_is_a_volume(); + let crumb = widgets::crumb(id, label, current, cx) + .when(volumes, |crumb| { + crumb.hover(|style| style.bg(theme.hover_fill())) + }) + .on_click(cx.listener(move |this, _, window, cx| { + if volumes { + this.open_volumes(cx); + this.apply_focus(window, cx); + } else { + this.go_to(Vec::new(), cx); + } + })); + return if volumes { + with_tooltip(crumb, "Scan another volume \u{00b7} v") + .into_any_element() + } else { + crumb.into_any_element() + }; }; let parent = parent.to_vec(); let open = app @@ -636,7 +1216,7 @@ fn sibling_menu( let largest = rows.first().map_or(1, |row| row.value.max(1)); let parent_name = app.node_at(parent).map_or_else(String::new, |node| { if parent.is_empty() { - crate::marks::display_path(&app.root_path, app.home.as_deref()) + app.shown_path(&app.root_path) } else { node.name.to_string() } @@ -834,10 +1414,7 @@ fn view_settings( ) .tab_stop(false) .on_change(move |_, _, window, cx| { - let _ = entity.update(cx, |this, cx| { - this.options.include_hidden = !this.options.include_hidden; - this.start_scan(cx); - }); + let _ = entity.update(cx, Disktree::toggle_hidden); window.focus(&focus, cx); }) }; @@ -850,10 +1427,7 @@ fn view_settings( ) .tab_stop(false) .on_change(move |_, _, window, cx| { - let _ = entity.update(cx, |this, cx| { - this.options.apparent_size = !this.options.apparent_size; - this.start_scan(cx); - }); + let _ = entity.update(cx, Disktree::toggle_apparent_size); window.focus(&focus, cx); }) }; @@ -944,7 +1518,11 @@ fn view_settings( cx: &mut Context<'_, Disktree>| { button(id, label, ButtonVariant::Secondary, cx) .tab_stop(false) - .disabled(if step < 0 { depth <= 1 } else { depth >= 6 }) + .disabled(if step < 0 { + depth <= 1 + } else { + depth >= app.depth_limit() + }) .on_click(cx.listener(move |this, _, window, cx| { this.adjust_depth(step, cx); window.focus(&this.focus, cx); @@ -982,6 +1560,46 @@ fn view_settings( .child(apparent) .child(depth_control) .child(power_efficiency(app, cx)) + .child(with_tooltip( + bar_icon("settings", gpui_omarchy::IconName::Settings, &theme) + .on_click(cx.listener(|this, _, window, cx| { + this.open_settings(cx); + window.focus(&this.focus, cx); + })), + "Settings: theme, depth, shortcuts", + )) + .child(repository_button(&theme, cx)) +} + +/// A glyph on the bar that does one thing when clicked. +fn bar_icon( + id: &'static str, + name: gpui_omarchy::IconName, + theme: &Theme, +) -> Stateful
{ + div() + .id(id) + .debug_selector(move || id.into()) + .p(space::XS) + .text_color(theme.secondary) + .hover(|style| style.bg(theme.hover_fill()).text_color(theme.bright)) + .child(gpui_omarchy::icon(name).size(icon::MD)) +} + +/// The way to the source, the releases and the issue tracker. +fn repository_button( + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Stateful
{ + with_tooltip( + bar_icon("repository", gpui_omarchy::IconName::Github, theme).on_click( + cx.listener(|this, _, window, cx| { + Disktree::open_repository(cx); + window.focus(&this.focus, cx); + }), + ), + "disktree on GitHub", + ) } /// What the tooltip says the choice will do, where the gauge alone cannot. @@ -1185,25 +1803,488 @@ fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { // ── trail and legend ──────────────────────────────────────────────────── -/// Where you are, as a clickable trail, and what the colours mean, on one -/// row over the mosaic. -fn trail_and_legend( - app: &Disktree, - theme: &Theme, - cx: &Context<'_, Disktree>, -) -> Div { - let mut row = div() +/// Where you are, as a clickable trail, and what the colours mean, on one +/// row over the mosaic. +fn trail_and_legend( + app: &Disktree, + theme: &Theme, + window: &mut Window, + cx: &mut Context<'_, Disktree>, +) -> Div { + let mut row = div() + .flex() + .flex_row() + .items_center() + .gap(space::LG) + .px(space::LG) + .py(space::SM) + .child(scan_totals(app, theme)) + .child(filter_control(app, theme, window, cx)); + if app.find_open || !app.find.is_empty() { + row = row.child(find_field(app, theme)); + } + row.child(div().flex_1()).child(legend(app, theme, cx)) +} + +/// One choice of a few set side by side: the theme, a size's unit. +fn segment( + id: String, + label: &'static str, + on: bool, + theme: &Theme, +) -> Stateful
{ + div() + .id(ElementId::Name(id.clone().into())) + .debug_selector(move || id) + .px(space::MD) + .py(space::XS) + .border_1() + .border_color(if on { + theme.accent + } else { + theme.control_border() + }) + .text_size(text::BODY) + .text_color(if on { theme.bright } else { theme.secondary }) + .when(on, |this| this.bg(theme.accent.opacity(0.18))) + .hover(|this| this.bg(theme.hover_fill())) + .cursor_pointer() + .child(label) +} + +/// How many things the Filter menu asks for, in words: read in its +/// heading, and on its button while the menu is shut. +fn filter_status(app: &Disktree) -> String { + match app.filter_count() { + 0 => "No filter on".into(), + 1 => "1 filter on".into(), + many => format!("{many} filters on"), + } +} + +/// A section of the Filter menu: what it is, then what it does, in words +/// at reading size rather than as a small capital label. +fn menu_heading(title: &'static str, hint: &'static str, theme: &Theme) -> Div { + div() + .flex() + .flex_col() + .gap(space::XXS) + .child( + div() + .text_size(text::TITLE) + .font_weight(FontWeight::BOLD) + .text_color(theme.bright) + .child(title), + ) + .child( + div() + .text_size(text::BODY) + .text_color(theme.secondary) + .child(hint), + ) +} + +/// Two ways to narrow the mosaic, each its own button. **Filter** is what +/// can be picked: kinds of data, any number of them, and a least and a +/// most size for files. **Name** is what has to be typed, and opens the +/// field `/` opens. They combine, and neither shows the other's words. +/// +/// The menu is laid out to the four POUR principles. Perceivable: nothing +/// is smaller than body text, and a state is never colour alone — a tick, +/// a weight, an icon or a word goes with it. Operable: every control is a +/// tab stop at least [`size::TARGET`] tall, and Tab walks them. To be +/// understood: each field is labelled above, an empty one says "No limit", +/// the filter is read back as a sentence, and an error sits by its field +/// and says the way out. Robust: the controls are the toolkit's own, so +/// each carries a role, a name and a state. +fn filter_control( + app: &Disktree, + theme: &Theme, + window: &mut Window, + cx: &mut Context<'_, Disktree>, +) -> Div { + use gpui_omarchy::{IconName, Status}; + + let highlight = palette::highlight(theme); + let chosen = app.filter_chosen(); + let toggle = + button("filter-button", "Filter", ButtonVariant::Secondary, cx) + .tab_stop(false) + .when(chosen, |toggle| { + // The count is there to read with the menu shut. + toggle.border_color(highlight).child( + div() + .debug_selector(|| "filter-summary".into()) + .px(space::XS) + .bg(highlight.opacity(0.2)) + .text_color(theme.bright) + .font_weight(FontWeight::BOLD) + .child(format!("{} on", app.filter_count())), + ) + }) + .on_click(cx.listener(|this, _, window, cx| { + this.toggle_filter_menu(window, cx); + this.apply_focus(window, cx); + })); + let name = button("filter-name", "Name", ButtonVariant::Secondary, cx) + .tab_stop(false) + .when(!app.find.is_empty(), |name| name.border_color(highlight)) + .on_click(cx.listener(|this, _, window, cx| { + this.filter_menu = false; + this.find_open = true; + cx.notify(); + window.focus(&this.focus, cx); + })); + let holder = div() + .id("filter-control") + .debug_selector(|| "filter-control".into()) + .relative() + .flex_shrink_0() + .child(toggle); + let buttons = |holder: Stateful
| { + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .flex_shrink_0() + .child(holder) + .child( + div() + .id("filter-name-holder") + .debug_selector(|| "filter-name".into()) + .child(name), + ) + }; + let Some((least, most)) = + app.size_inputs.clone().filter(|_| app.filter_menu) + else { + return buttons(holder); + }; + + let header = div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .child( + div() + .flex_1() + .flex() + .flex_col() + .gap(space::XXS) + .child( + div() + .text_size(text::TITLE) + .font_weight(FontWeight::BOLD) + .text_color(theme.bright) + .child("Filter"), + ) + .child( + div() + .debug_selector(|| "filter-status".into()) + .text_size(text::BODY) + .text_color(theme.secondary) + .child(filter_status(app)), + ), + ) + .child( + gpui_omarchy::icon_button( + "filter-done", + IconName::Close, + "Close the Filter menu", + ButtonVariant::Outline, + cx, + ) + .debug_selector(|| "filter-done".into()) + .size(size::TARGET) + .on_click(cx.listener(|this, _, window, cx| { + this.close_filter_menu(cx); + this.apply_focus(window, cx); + })), + ); + + let entity = cx.entity().downgrade(); + let mut kinds = div().flex().flex_col().child( + menu_heading("Kind", "Show files of any ticked kind", theme) + .pb(space::XS), + ); + for category in Category::LEGEND { + let on = app.filter_kinds.contains(&category); + let id = format!( + "filter-kind-{}", + disktree_core::filter::kind_key(category) + ); + let entity = entity.clone(); + kinds = kinds.child( + div() + .debug_selector({ + let id = id.clone(); + move || id + }) + .child( + // The toolkit's tick box: a checkbox by role, named + // for its kind, focusable, and ticked with Space. The + // whole row is the target, not the box alone. + checkbox( + ElementId::Name(id.into()), + "", + if on { + CheckboxState::Checked + } else { + CheckboxState::Unchecked + }, + cx, + ) + .accessibility_label(category.label()) + .w_full() + .min_h(size::TARGET) + .text_size(text::TITLE) + // Ticked is said by the tick and by weight; the + // swatch only echoes the legend. + .when(on, |row| { + row.font_weight(FontWeight::BOLD) + .text_color(theme.bright) + }) + .child(widgets::swatch(palette::category_accent( + theme, category, + ))) + .child(category.label()) + .on_change(move |_, _, _, cx| { + let _ = entity.update(cx, |this, cx| { + this.toggle_filter_kind(category, cx); + }); + }), + ), + ); + } + + let warning = widgets::alert_color(Status::Warning, cx); + // Min and Max on one line, read left to right as the range is said: + // "from 500 MiB to 4 GiB". Each is named above its field, and has its + // unit in a dropdown beside it and a cross in it that empties it. + let mut sides = div().flex().flex_row().items_start().gap(space::MD); + for (side, (label, hint, id, input)) in [ + ("Min size", "at least", "filter-least", &least), + ("Max size", "at most", "filter-most", &most), + ] + .into_iter() + .enumerate() + { + let wrong = app.size_error.as_ref().is_some_and(|(at, _)| *at == side); + let mut editor = gpui_omarchy::input( + ElementId::Name(format!("{id}-input").into()), + input, + window, + cx, + ) + // A set height, so the cross turning up does not move the row. + .h(size::TARGET) + .py(space::NONE); + if !input.read(cx).value().is_empty() { + editor = editor.suffix( + gpui_omarchy::icon_button( + ElementId::Name(format!("{id}-clear").into()), + IconName::Close, + format!("Clear the {}", label.to_lowercase()), + ButtonVariant::Secondary, + cx, + ) + .debug_selector(move || format!("{id}-clear")) + .p(space::XS) + .on_click(cx.listener( + move |this, _, window, cx| { + this.clear_size(side, window, cx); + }, + )), + ); + } + let field = div() + .id(id) + .debug_selector(move || id.into()) + .flex_1() + .min_w_0() + // Always a border, so one that turns up for an error moves + // nothing. + .border_1() + .border_color(if wrong { + warning + } else { + theme.foreground.opacity(0.) + }) + .child(editor); + let unit = app.unit_selects.as_ref().map(|selects| { + div() + .debug_selector(move || format!("filter-unit-{side}")) + .w(size::UNIT_SELECT) + .flex_shrink_0() + .child(gpui_omarchy::select( + ElementId::Name( + format!("filter-unit-{side}-select").into(), + ), + &selects[side], + window, + cx, + )) + }); + sides = sides.child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(space::XS) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .child( + div() + .text_size(text::TITLE) + .text_color(theme.bright) + .child(label), + ) + .child( + div() + .text_size(text::BODY) + .text_color(theme.secondary) + .child(hint), + ), + ) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::XS) + .child(field) + .children(unit), + ), + ); + } + // Under both, since the row is shared: the sentence names the field. + // An icon and words, not a red edge alone. + let sizes = div() + .flex() + .flex_col() + .gap(space::XS) + .child(sides) + .children(app.size_error.as_ref().map(|(_, why)| { + div() + .debug_selector(|| "filter-size-error".into()) + .flex() + .flex_row() + .items_center() + .gap(space::XS) + .text_size(text::BODY) + .text_color(warning) + .child( + gpui_omarchy::icon(IconName::TriangleAlert) + .size(icon::SM) + .text_color(warning), + ) + .child(why.clone()) + })); + + let summary = div() + .debug_selector(|| "filter-size-summary".into()) + .px(space::SM) + .py(space::XS) + .bg(theme.hover_fill()) + .text_size(text::BODY) + .text_color(theme.foreground) + .child(if app.size_error.is_some() { + "Not applied yet: put the size right first".to_owned() + } else { + app.filter_sentence() + }); + let actions = div() .flex() .flex_row() .items_center() - .gap(space::LG) - .px(space::LG) - .py(space::SM) - .child(scan_totals(app, theme)); - if app.find_open || !app.find.is_empty() { - row = row.child(find_field(app, theme)); - } - row.child(div().flex_1()).child(legend(app, theme, cx)) + .gap(space::SM) + // Only when there is something to clear, rather than greyed out. + .children(chosen.then(|| { + button("filter-clear", "Clear all", ButtonVariant::Outline, cx) + .debug_selector(|| "filter-clear".into()) + .min_h(size::TARGET) + .text_size(text::TITLE) + .on_click(cx.listener(|this, _, window, cx| { + this.clear_chosen_filter(window, cx); + })) + })) + .child(div().flex_1()) + .child( + div() + .text_size(text::BODY) + .text_color(theme.secondary) + .child("Esc closes"), + ) + .child( + // Never disabled: a bad size is answered beside its field, + // and the keyboard is put there. + button("filter-apply", "Apply", ButtonVariant::Primary, cx) + .debug_selector(|| "filter-apply".into()) + .min_h(size::TARGET) + .text_size(text::TITLE) + .font_weight(FontWeight::BOLD) + .child( + div() + .text_size(text::BODY) + .font_weight(FontWeight::NORMAL) + .child("Enter"), + ) + .on_click(cx.listener(|this, _, window, cx| { + this.press_apply(window, cx); + })), + ); + + // A focus scope, so Tab and Shift+Tab walk the menu's controls. + let menu = gpui_omarchy::focus_scope("filter-menu") + .debug_selector(|| "filter-menu".into()) + .occlude() + .child( + card_surface(cx) + .w(size::FILTER_MENU) + .p(space::MD) + .gap(space::MD) + // Solid, where a tooltip is not: the mosaic's labels + // showing through would sit behind words to be read. + .bg(theme.background) + .child(header) + .child(kinds) + .child(separator(cx)) + .child(menu_heading( + "File size", + "Sizes apply to files, not folders", + theme, + )) + .child(sizes) + .child(summary) + .child(actions) + .children(app.notice.as_ref().map(|(text, status)| { + div() + .text_size(text::BODY) + .text_color(widgets::alert_color(*status, cx)) + .child(text.clone()) + })), + ); + // Hung below the button and deferred, so it paints over the mosaic. + buttons( + holder.child( + div().absolute().top_full().left_0().child( + deferred( + anchored() + .snap_to_window_with_margin(px(8.)) + .offset(gpui_kit::point(px(0.), px(4.))) + .child(menu), + ) + .with_priority(2), + ), + ), + ) } /// What the whole scan found, as one quiet line; unreadable paths are @@ -1296,6 +2377,7 @@ fn legend(app: &Disktree, theme: &Theme, cx: &App) -> Div { fn side_panel( app: &Disktree, theme: &Theme, + window: &Window, cx: &Context<'_, Disktree>, ) -> Div { let rule = || div().h(px(1.)).bg(theme.divider()); @@ -1337,17 +2419,38 @@ fn side_panel( // so the two numbers that matter never leave the screen. .child( div() - .id("panel-lists") + .relative() .flex() .flex_col() - .gap(space::LG) .flex_1() .min_h_0() - .overflow_y_scroll() - .child(worth_section(app, theme, cx)) - .child(rule()) - .child(marked_section(app, theme, cx)), + .child( + div() + .id("panel-lists") + .debug_selector(|| "panel-lists".into()) + .flex() + .flex_col() + .gap(space::LG) + .flex_1() + .min_h_0() + // Room for the bar, which is drawn over this edge. + .pr(space::MD) + .overflow_y_scroll() + .track_scroll(&app.panel_scroll) + .child(worth_section(app, theme, cx)) + .child(rule()) + .child(marked_section(app, theme, cx)), + ) + .child(gpui_omarchy::scrollbar( + "panel-scroll", + gpui_kit::base::ScrollbarAxis::Vertical, + &app.panel_scroll, + window, + cx, + )), ) + // Pinned under the lists, so it is there however long they are. + .children(insights_toggle(app, theme, cx)) .children(notice_line(app, theme, cx)) .children(privacy_line(app, theme, cx)) .children(administrator_line(app, theme, cx)) @@ -1419,9 +2522,10 @@ fn selection_section( .whitespace_nowrap() .overflow_hidden() .text_ellipsis() - .child(path.as_deref().map_or_else(String::new, |path| { - crate::marks::display_path(path, app.home.as_deref()) - })), + .child( + path.as_deref() + .map_or_else(String::new, |path| app.shown_path(path)), + ), ); let (number, unit) = match app.options.metric { @@ -1557,6 +2661,7 @@ fn selection_section( _ => "Mark for removal".to_string(), }; let mark = button("mark", label, ButtonVariant::Primary, cx) + .debug_selector(|| "mark-button".into()) .tab_stop(false) .flex_1() .justify_center() @@ -1570,18 +2675,25 @@ fn selection_section( window.focus(&this.focus, cx); })); let filled = !marked && covered_by.is_none(); - actions = actions.child(if filled { - let on = palette::on_highlight(theme); - mark.bg(highlight) - .border_color(highlight) - .text_color(on) - .font_weight(FontWeight::SEMIBOLD) - .hover(move |style| { - style.bg(highlight.opacity(0.85)).border_color(highlight) - }) - } else { - mark - }); + // Nothing is marked on another machine, so marking is not offered + // there; pressed, it could only say no. + let offered = app.remote.is_none(); + actions = actions.children(offered.then(|| { + if filled { + let on = palette::on_highlight(theme); + mark.bg(highlight) + .border_color(highlight) + .text_color(on) + .font_weight(FontWeight::SEMIBOLD) + .hover(move |style| { + style + .bg(highlight.opacity(0.85)) + .border_color(highlight) + }) + } else { + mark + } + })); } section @@ -1625,8 +2737,11 @@ fn worth_section( .text_color(theme.secondary) .child(if app.tree().is_some() { "Nothing obviously disposable" - } else { + } else if app.scan.is_some() { "Waiting for the scan" + } else { + // Cancelled, or failed: there is none to wait for. + "Nothing was scanned" }), ); } @@ -1705,6 +2820,60 @@ fn worth_section( section } +/// "Show more" under Worth a look, and "Show fewer" to put the short list +/// back. Offered once the short list is full, since there may then be +/// more, and while the long one is shown. +/// +/// It sits under the lists, not at the end of them: the long list is +/// thirty rows, and a button at its foot is a scroll away from whoever +/// wants the short one back. +fn insights_toggle( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Option
{ + let offered = + app.insights_all || app.insights.len() >= crate::state::INSIGHT_LIMIT; + offered.then(|| { + div() + .debug_selector(|| "insights-more".into()) + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .flex_shrink_0() + .child( + button( + "insights-more", + if app.insights_all { + "Show fewer" + } else { + "Show more" + }, + ButtonVariant::Outline, + cx, + ) + .tab_stop(false) + .on_click(cx.listener( + |this, _, window, cx| { + this.toggle_insights(cx); + window.focus(&this.focus, cx); + }, + )), + ) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(if app.insights_all { + format!("{} worth a look", app.insights.len()) + } else { + "of what is worth a look".to_owned() + }), + ) + }) +} + /// A finding's title, as the last two parts of its path, and why it is on /// the list. fn insight_text(app: &Disktree, candidate: &Candidate) -> (String, String) { @@ -1768,7 +2937,11 @@ fn marked_section( div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child("Space marks the tile you point at"), + .child(if app.remote.is_some() { + "Nothing is marked on another machine" + } else { + "Space marks the tile you point at" + }), ); } for (index, item) in app.marks.items().iter().take(MARKED_ROWS).enumerate() @@ -1886,7 +3059,11 @@ fn privacy_line( theme: &Theme, cx: &Context<'_, Disktree>, ) -> Option
{ - if app.progress.errors == 0 || app.full_disk_access != Some(false) { + // What another machine kept back is not this one's access to grant. + if app.remote.is_some() + || app.progress.errors == 0 + || app.full_disk_access != Some(false) + { return None; } let color = theme.warning; @@ -1939,7 +3116,13 @@ fn administrator_line( theme: &Theme, cx: &Context<'_, Disktree>, ) -> Option
{ - if app.administrator != Some(false) || app.restarting || app.run.is_some() { + // Nor would an administrator here read what another machine kept + // back, or its disk from a file table. + if app.remote.is_some() + || app.administrator != Some(false) + || app.restarting + || app.run.is_some() + { return None; } let errors = app.progress.errors; @@ -2014,13 +3197,28 @@ fn disk_section( .flex_row() .items_center() .gap(space::SM) - .child(widgets::eyebrow("Disk", cx)) - .child( + .child(with_tooltip( div() - .text_size(text::CAPTION) - .text_color(theme.secondary.opacity(0.6)) - .child(device), - ) + .id("disk-label") + .debug_selector(|| "disk-label".into()) + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .hover(|style| style.bg(theme.hover_fill())) + .on_click(cx.listener(|this, _, window, cx| { + this.open_volumes(cx); + this.apply_focus(window, cx); + })) + .child(widgets::eyebrow("Disk", cx)) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary.opacity(0.6)) + .child(device), + ), + "Scan another volume \u{00b7} v", + )) .child(div().flex_1()) .child( button("volumes", "Volumes", ButtonVariant::Secondary, cx) @@ -2208,20 +3406,23 @@ fn review_button( /// The keys, quietly: outlines and light labels, there when needed. The key /// to every other key and the scan's own numbers hold the trailing edge. -fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div { - // Most useful first, so a narrow window clips the least useful. - let hints: [(&str, &str); 11] = [ - ("space", "mark"), - ("enter", "open"), - ("\u{232b}", "up"), - ("c", "review"), - ("hjkl", "move"), - ("/", "filter"), - ("[ ]", "depth"), - ("t", "mode"), - ("0", "reset"), - ("v", "volumes"), - ("r", "rescan"), +fn key_bar(app: &Disktree, theme: &Theme, cx: &Context<'_, Disktree>) -> Div { + // Most useful first, so a narrow window clips the least useful. Each + // is a button for the key it names, for a hand already on the mouse; + // the last column is that key as the bindings spell it. Moving between + // tiles is four keys and no one click, so it stays a label. + let hints: [(&str, &str, Option<&str>); 11] = [ + ("space", "mark", Some("space")), + ("enter", "open", Some("enter")), + ("\u{232b}", "up", Some("backspace")), + ("c", "review", Some("c")), + ("hjkl", "move", None), + ("/", "filter", Some("/")), + ("[ ]", "depth", Some("[ ]")), + ("t", "mode", Some("t")), + ("0", "reset", Some("0")), + ("v", "volumes", Some("v")), + ("r", "rescan", Some("r")), ]; let mut lane = div() .flex() @@ -2231,8 +3432,19 @@ fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div { .flex_1() .min_w_0() .overflow_hidden(); - for (keys, label) in hints { - lane = lane.child(widgets::hint(keys, label, cx).flex_shrink_0()); + // Marking and its review are not offered for another machine, so + // their keys are not advertised there. + let local = app.remote.is_none(); + for (keys, label, key) in hints + .into_iter() + .filter(|(_, label, _)| local || !matches!(*label, "mark" | "review")) + { + lane = lane.child(match key { + Some(key) => key_hint(keys, label, key, cx).into_any_element(), + None => widgets::hint(keys, label, cx) + .flex_shrink_0() + .into_any_element(), + }); } let mut row = div() @@ -2274,14 +3486,35 @@ fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div { widgets::human_count(app.progress.files) ) }; - row.child(widgets::hint("?", "all keys", cx).flex_shrink_0()) - .child( - div() - .flex_shrink_0() - .text_size(text::CAPTION) - .text_color(theme.secondary.opacity(0.7)) - .child(scan), - ) + row.child(key_hint("?", "all keys", "?", cx)).child( + div() + .flex_shrink_0() + .text_size(text::CAPTION) + .text_color(theme.secondary.opacity(0.7)) + .child(scan), + ) +} + +/// A key hint that is also a button: a click does what `key` does, and the +/// keyboard goes back to where that leaves it. +fn key_hint( + keys: &'static str, + label: &'static str, + key: &'static str, + cx: &Context<'_, Disktree>, +) -> Stateful
{ + let id = format!("key-{label}"); + widgets::hint_button(ElementId::Name(id.clone().into()), keys, label, cx) + .debug_selector(move || id) + .on_click(cx.listener(move |this, _, window, cx| { + this.press(key, cx); + // A dialog the key opened takes the keyboard; anything else + // hands it back to the treemap, which a click took it from. + if this.focus_request.is_none() { + window.focus(&this.focus, cx); + } + this.apply_focus(window, cx); + })) } /// What the viewport shows while the first scan is running. @@ -2291,7 +3524,11 @@ fn scanning_panel( cx: &Context<'_, Disktree>, ) -> Div { let progress = &app.progress; - let cancelled = app.scan.is_none() && progress.cancelled; + // No scan running and no tree: it was cancelled, or it failed, as a + // connection to another machine does when the host is not found. + // Either way nothing is being read, so nothing here should spin. + let stopped = app.scan.is_none(); + let cancelled = stopped && progress.cancelled; let mut panel = div() .flex() .flex_col() @@ -2301,7 +3538,7 @@ fn scanning_panel( .justify_center() .gap(space::LG) .bg(theme.inset) - .when(!cancelled, |panel| { + .when(!stopped, |panel| { panel.child( gpui_omarchy::icon(gpui_omarchy::IconName::Loader) .size(icon::LG) @@ -2315,6 +3552,8 @@ fn scanning_panel( .text_color(theme.bright) .child(if cancelled { format!("Stopped reading {}", widgets::display_root(app)) + } else if stopped { + format!("Could not read {}", widgets::display_root(app)) } else { format!("Reading {}", widgets::display_root(app)) }), @@ -2342,7 +3581,7 @@ fn scanning_panel( cx, )), ) - .when(!cancelled, |panel| { + .when(!stopped, |panel| { panel.child( div() .w(size::SCANNING_METER) @@ -2359,8 +3598,10 @@ fn scanning_panel( div() .text_size(text::BODY) .text_color(theme.secondary) - .child(if cancelled { + .child(if stopped { "Nothing is shown from a scan that did not finish." + } else if app.remote.is_some() { + "Another machine's files can be looked at as soon as it lands, and nothing else: a remote scan is read-only." } else { "Marking, zooming and the free-space meter all work as soon as it lands." }), @@ -2934,7 +4175,11 @@ fn commit_controls( ) } -fn review_footer(app: &Disktree, theme: &Theme, cx: &App) -> Div { +fn review_footer( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Div { let commit = match app.removal_mode { RemovalMode::Trash => "move to trash", RemovalMode::Permanent => "delete\u{2026}", @@ -2948,13 +4193,13 @@ fn review_footer(app: &Disktree, theme: &Theme, cx: &App) -> Div { .py(space::SM) .border_t_1() .border_color(theme.divider()) - .child(widgets::hint("enter", commit, cx)) - .child(widgets::hint("m", "trash", cx)) - .child(widgets::hint("p", "permanent", cx)) - .child(widgets::hint("!", "unmark all", cx)) - .child(widgets::hint("s", "save list", cx)) - .child(widgets::hint("a", "copy as prompt", cx)) - .child(widgets::hint("esc", "back", cx)) + .child(key_hint("enter", commit, "enter", cx)) + .child(key_hint("m", "trash", "m", cx)) + .child(key_hint("p", "permanent", "p", cx)) + .child(key_hint("!", "unmark all", "!", cx)) + .child(key_hint("s", "save list", "s", cx)) + .child(key_hint("a", "copy as prompt", "a", cx)) + .child(key_hint("esc", "back", "escape", cx)) .child(div().flex_1()) .child( div() @@ -3349,10 +4594,12 @@ fn history_card(app: &Disktree, back: bool, cx: &gpui_kit::App) -> Div { pub fn hover_tooltip(app: &Disktree, cx: &gpui_kit::App) -> Option
{ let crumbs = app.hovered.as_deref()?; let is_dir = app.node_at(crumbs)?.is_dir(); - let keys = if is_dir { - "space mark · enter open" - } else { - "space mark" + // Marking is not offered for another machine, so it is not named. + let keys = match (app.remote.is_some(), is_dir) { + (false, true) => "space mark · enter open", + (false, false) => "space mark", + (true, true) => "enter open", + (true, false) => "read-only", }; node_card(app, crumbs, keys, cx) } @@ -3405,9 +4652,10 @@ fn node_card( div() .text_size(text::CAPTION) .text_color(theme.secondary) - .child(path.as_deref().map_or_else(String::new, |path| { - crate::marks::display_path(path, app.home.as_deref()) - })), + .child( + path.as_deref() + .map_or_else(String::new, |path| app.shown_path(path)), + ), ) .child( div() @@ -3494,9 +4742,18 @@ const MODIFIER_OPEN: &str = if cfg!(target_os = "macos") { } else { "ctrl-o" }; +const MODIFIER_PATH: &str = if cfg!(target_os = "macos") { + "\u{2318}L" +} else { + "ctrl-l" +}; -fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { - let theme = cx.omarchy(); +fn help_overlay(app: &Disktree, cx: &Context<'_, Disktree>) -> Stateful
{ + let theme = cx.omarchy().clone(); + let close: fn(&mut Disktree, &mut Context<'_, Disktree>) = |this, cx| { + this.show_help = false; + cx.notify(); + }; // Sentence case, and the tile a key acts on is always the one under the // pointer if the pointer moved last, else the keyboard selection. let rows = [ @@ -3526,12 +4783,20 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { ("t", "Size, files or age: what areas and colours say"), ("r", "Scan again from the same root"), ("esc", "Stop a scan in progress"), - ("v", "Scan another volume"), + ("v", "Scan another volume; so does the disk's own name"), (MODIFIER_OPEN, "Choose another directory to scan"), + ( + MODIFIER_PATH, + "Type or paste a path; a click beside the trail does too", + ), ("g", "The whole disk; click any directory above to widen"), ("d", "Disk usage or apparent size"), ("i", "Include or skip hidden entries"), ("p", "Show or hide the selection line"), + ( + "T", + "System, light or dark theme; the settings page has it too", + ), ( "o", if cfg!(target_os = "macos") { @@ -3580,54 +4845,32 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { ); } - div() - .absolute() - .inset_0() + let card = div() .flex() - .items_center() - .justify_center() - .bg(theme.background.opacity(0.86)) + .flex_col() + .gap(space::MD) + .w(size::HELP) + .p(space::XL) + .border_1() + .border_color(theme.border) + .bg(theme.surface) + .child(page_header( + "help-close", + gpui_omarchy::IconName::Keyboard, + "Keyboard and mouse", + close, + cx, + )) + .child(keys) .child( div() - .flex() - .flex_col() - .gap(space::MD) - .w(size::HELP) - .p(space::XL) - .border_1() - .border_color(theme.border) - .bg(theme.surface) - .child( - div() - .flex() - .flex_row() - .items_center() - .gap(space::SM) - .child( - gpui_omarchy::icon( - gpui_omarchy::IconName::Keyboard, - ) - .size(icon::MD) - .text_color(theme.accent), - ) - .child( - div() - .text_size(text::TITLE) - .font_weight(FontWeight::BOLD) - .text_color(theme.bright) - .child("Keyboard and mouse"), - ), - ) - .child(keys) - .child( - div() - .text_size(text::CAPTION) - .text_color(theme.secondary) - .child(format!( - "? or esc closes \u{00b7} {} \u{00b7} {}", - app.root_path.display(), - app.options.metric.label() - )), - ), - ) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(format!( + "?, esc or a click outside closes \u{00b7} {} \u{00b7} {}", + app.root_path.display(), + app.options.metric.label() + )), + ); + modal("help", &theme, card, close, cx) } diff --git a/crates/disktree-app/src/widgets.rs b/crates/disktree-app/src/widgets.rs index 905c04ff..e9a03aeb 100644 --- a/crates/disktree-app/src/widgets.rs +++ b/crates/disktree-app/src/widgets.rs @@ -9,7 +9,8 @@ use disktree_core::tree::{Metric, Node}; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::{ App, Div, ElementId, FontWeight, Hsla, InteractiveElement as _, - ParentElement, SharedString, Styled, div, relative, + ParentElement, SharedString, StatefulInteractiveElement as _, Styled, div, + relative, }; use gpui_omarchy::{ActiveTheme, Status}; @@ -19,7 +20,12 @@ use crate::state::Disktree; /// The scanned root, shortened to `~` where it is the home directory. pub fn display_root(app: &Disktree) -> String { - crate::marks::display_path(&app.root_path, app.home.as_deref()) + // Another machine's root is named with the machine: `/tmp` alone + // would read as this one's. + app.remote.as_ref().map_or_else( + || crate::marks::display_path(&app.root_path, app.home.as_deref()), + ToString::to_string, + ) } /// File counts, which is what a directory count is too. @@ -248,6 +254,30 @@ pub fn hint( ) } +/// A hint that can be clicked: the same pair, with the hover and the +/// pointer of something that does what its key does. +pub fn hint_button( + id: impl Into, + keys: impl Into, + label: impl Into, + cx: &App, +) -> gpui_kit::Stateful
{ + let theme = cx.omarchy(); + hint(keys, label, cx) + .id(id) + .flex_shrink_0() + // Framed and padded evenly, so the key and its word sit in the + // middle of something that reads as pressable. + .justify_center() + .px(space::SM) + .py(space::XXS) + .border_1() + .border_color(theme.control_border()) + .cursor_pointer() + .hover(|style| style.bg(theme.hover_fill())) + .active(|style| style.bg(theme.pressed_fill())) +} + /// A section heading inside a panel. pub fn section(label: impl Into, cx: &App) -> Div { let theme = cx.omarchy(); diff --git a/crates/disktree-core/src/filter.rs b/crates/disktree-core/src/filter.rs index 24c1a7a9..cbc38613 100644 --- a/crates/disktree-core/src/filter.rs +++ b/crates/disktree-core/src/filter.rs @@ -1,15 +1,134 @@ -//! Typeahead filtering: which parts of a tree match a name. +//! Typeahead filtering: which parts of a tree match a name, a kind or a +//! size. //! //! A node whose name contains the needle (ignoring ASCII case) matches, and //! is kept whole: everything under a matching directory goes with it. Its //! ancestors are kept only partly, and sized by what matched beneath them, //! so a filtered treemap shows exactly the matches, at their true relative //! sizes, in the places they live. +//! +//! Some words in the needle are not part of the name: `kind:cache` asks +//! for a [`Category`], and may be given more than once for any of several; +//! `>1g` asks for files of at least that size and `<4g` of at most. See +//! [`Query`]. use rustc_hash::FxHashMap; +use crate::classify::Category; use crate::tree::{Metric, Node}; +/// What a filter asks of an entry; every part that is set must hold. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Query { + /// Text the name must contain, lowercased. Empty asks nothing. + pub name: String, + /// The kinds of data it may be: any one of them. Empty asks nothing. + pub kinds: Vec, + /// The least a file may hold. A size is asked of files only: a + /// directory is as large as everything in it, so every directory above + /// a large file would match and the small files beside it come along. + pub min_bytes: Option, + /// The most a file may hold. + pub max_bytes: Option, +} + +/// The word that asks for a kind: `kind:cache`. +pub const KIND_PREFIX: &str = "kind:"; + +/// The word that asks for a least size: `>500m`. +pub const LEAST_PREFIX: char = '>'; + +/// The word that asks for a most size: `<4g`. +pub const MOST_PREFIX: char = '<'; + +impl Query { + /// Read a needle. A word that looks like a kind or a size but names + /// none is left in the name, so a file really called `kind:x` can + /// still be found. + pub fn parse(needle: &str) -> Self { + let mut query = Self::default(); + let mut words: Vec = Vec::new(); + for word in needle.split_whitespace() { + let word = word.to_ascii_lowercase(); + let kind = word.strip_prefix(KIND_PREFIX).and_then(kind_named); + let least = word.strip_prefix(LEAST_PREFIX).and_then(parse_size); + let most = word.strip_prefix(MOST_PREFIX).and_then(parse_size); + if let Some(kind) = kind { + if !query.kinds.contains(&kind) { + query.kinds.push(kind); + } + } else if least.is_some() { + query.min_bytes = least; + } else if most.is_some() { + query.max_bytes = most; + } else { + words.push(word); + } + } + query.name = words.join(" "); + query + } + + pub const fn is_empty(&self) -> bool { + self.name.is_empty() + && self.kinds.is_empty() + && self.min_bytes.is_none() + && self.max_bytes.is_none() + } + + fn matches(&self, node: &Node) -> bool { + let sized = self.min_bytes.is_some() || self.max_bytes.is_some(); + (self.name.is_empty() || contains_ignoring_case(&node.name, &self.name)) + && (self.kinds.is_empty() || self.kinds.contains(&node.category)) + && (!sized + || (!node.is_dir() + && self.min_bytes.is_none_or(|least| node.bytes >= least) + && self.max_bytes.is_none_or(|most| node.bytes <= most))) + } +} + +/// The word a kind is asked for by, after [`KIND_PREFIX`]. +pub const fn kind_key(category: Category) -> &'static str { + match category { + Category::Code => "code", + Category::AgentScratch => "agent", + Category::Toolchain => "toolchain", + Category::Synced => "synced", + Category::Git => "git", + Category::Media => "media", + Category::Documents => "documents", + Category::Cache => "cache", + Category::Other => "other", + } +} + +fn kind_named(key: &str) -> Option { + Category::LEGEND + .into_iter() + .chain([Category::Other]) + .find(|category| kind_key(*category) == key) +} + +/// `500m`, `1.5g`, `2gib`, `4096`: binary units, as sizes are shown. +fn parse_size(text: &str) -> Option { + let digits = text + .find(|char: char| !(char.is_ascii_digit() || char == '.')) + .unwrap_or(text.len()); + let (number, unit) = text.split_at(digits); + let number: f64 = number.parse().ok()?; + let shift = match unit.trim_end_matches("ib").trim_end_matches('b') { + "" => 0, + "k" => 10, + "m" => 20, + "g" => 30, + "t" => 40, + _ => return None, + }; + let bytes = number * f64::from(1_u32 << 10).powi(shift / 10); + // Not a size: negative cannot be typed, but `inf` and overflow can. + (bytes.is_finite() && bytes < 1e18).then_some(bytes as u64) +} + /// How a node takes part in a filtered view. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Keep { @@ -24,6 +143,8 @@ pub enum Keep { pub struct Matches { /// The needle, lowercased. pub needle: String, + /// What the needle asks for. + pub query: Query, /// Absolute crumbs of the subtree that was searched. pub base: Vec, /// Keyed by absolute crumbs. Only matches and their ancestors appear; @@ -76,11 +197,13 @@ impl Matches { /// `None` for an empty needle: nothing is filtered. pub fn filter(node: &Node, base: &[usize], needle: &str) -> Option { let needle = needle.trim().to_ascii_lowercase(); - if needle.is_empty() { + let query = Query::parse(&needle); + if query.is_empty() { return None; } let mut matches = Matches { needle, + query, base: base.to_vec(), ..Matches::default() }; @@ -101,7 +224,7 @@ fn visit( let mut total = (0, 0); for (index, child) in node.children.iter().enumerate() { crumbs.push(index); - if contains_ignoring_case(&child.name, &matches.needle) { + if matches.query.matches(child) { matches.keep.insert(crumbs.clone(), Keep::Whole); matches.count += 1; total.0 += child.bytes; @@ -154,6 +277,71 @@ mod tests { node } + #[test] + fn a_needle_can_ask_for_a_kind_and_a_size_beside_a_name() { + let query = Query::parse(" Blob kind:cache >1.5g kind:media <4g "); + assert_eq!(query.name, "blob"); + assert_eq!(query.kinds, [Category::Cache, Category::Media]); + assert_eq!(query.min_bytes, Some(3 << 29)); + assert_eq!(query.max_bytes, Some(4 << 30)); + assert_eq!(Query::parse(">500m").min_bytes, Some(500 << 20)); + assert_eq!(Query::parse(">2gib").min_bytes, Some(2 << 30)); + // Words that only look the part stay in the name. + let odd = Query::parse("kind:plaid >big"); + assert_eq!(odd.name, "kind:plaid >big"); + assert!(odd.kinds.is_empty() && odd.min_bytes.is_none()); + for category in Category::LEGEND { + let word = format!("{KIND_PREFIX}{}", kind_key(category)); + assert_eq!(Query::parse(&word).kinds, [category]); + } + } + + #[test] + fn a_size_is_asked_of_files_and_a_kind_of_whatever_is_topmost() { + let mut cache = dir("store", vec![file("a", 40), file("b", 2)]); + cache.category = Category::Cache; + for child in &mut cache.children { + child.category = Category::Cache; + } + let mut root = + dir("root", vec![cache, file("big", 50), file("small", 3)]); + aggregate(&mut root, Metric::Bytes); + + // Only the files that large, wherever they are; the directory + // holding one is kept for it, not whole. + let large = filter(&root, &[], ">30").expect("a size"); + assert_eq!(large.count, 2); + assert_eq!(large.bytes, 90); + let store = root + .children + .iter() + .position(|child| child.name.as_ref() == "store") + .expect("store"); + assert_eq!( + large.keep(&[store]), + Some(Keep::Partial { + bytes: 40, + files: 1 + }) + ); + + // A kind takes the directory of that kind whole, once. + let kind = filter(&root, &[], "kind:cache").expect("a kind"); + assert_eq!(kind.count, 1); + assert_eq!(kind.bytes, 42); + assert_eq!(kind.keep(&[store]), Some(Keep::Whole)); + // A most as well as a least: only what lies between. + let band = filter(&root, &[], ">30 <45").expect("a band"); + assert_eq!((band.count, band.bytes), (1, 40)); + // Any of several kinds. + let either = + filter(&root, &[], "kind:media kind:cache").expect("kinds"); + assert_eq!((either.count, either.bytes), (1, 42)); + // Both together: the large file of that kind alone. + let both = filter(&root, &[], "kind:cache >30").expect("both"); + assert_eq!((both.count, both.bytes), (1, 40)); + } + fn tree() -> Node { let mut root = dir( "root", diff --git a/crates/disktree-core/src/lib.rs b/crates/disktree-core/src/lib.rs index a620d802..2b6cbbf5 100644 --- a/crates/disktree-core/src/lib.rs +++ b/crates/disktree-core/src/lib.rs @@ -14,6 +14,7 @@ pub mod insights; mod macos; #[cfg(windows)] mod mft; +pub mod remote; pub mod removal; pub mod scan; pub mod scan_threads; diff --git a/crates/disktree-core/src/remote.rs b/crates/disktree-core/src/remote.rs new file mode 100644 index 00000000..9dd56d11 --- /dev/null +++ b/crates/disktree-core/src/remote.rs @@ -0,0 +1,527 @@ +//! Scanning another machine over SSH. +//! +//! The other machine does the walk: `find` lists everything under a path +//! with its type, blocks, length and last write, and the tree is built here +//! from that listing. Nothing is installed there, and nothing here reaches +//! past the user's own `ssh`: its keys, its agent, its `known_hosts` and its +//! config are what decide whether the connection is made. +//! +//! A tree built this way can be looked at and nothing else. Its paths are +//! the other machine's, so nothing that acts on a local path — removal +//! above all — may be offered for it; see the application's state. +//! +//! The listing needs GNU `find` for `-printf`, which is every Linux and not +//! macOS or the BSDs. + +use std::io::{self, BufRead, BufReader, Read as _}; +use std::path::Path; +use std::process::{Command, Stdio}; + +use crate::scan::{ScanOptions, ScanProgress}; +use crate::tree::{Node, NodeKind}; + +/// Somewhere to scan on another machine. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Remote { + /// Who and where, as `ssh` takes it: `user@host`, or a `Host` from the + /// user's SSH config. + pub target: String, + /// The port, when the address named one. + pub port: Option, + /// The directory there, absolute. + pub path: String, +} + +impl Remote { + /// Read `user@host:/path`, as `scp` writes it, or + /// `ssh://user@host[:port]/path`. `None` for anything else, a local + /// path above all: `C:/x` has a one-letter "host", which no address + /// written this way may have. + pub fn parse(text: &str) -> Option { + let text = text.trim(); + let (target, port, path) = + if let Some(rest) = text.strip_prefix("ssh://") { + let (authority, path) = rest.split_once('/')?; + let (target, port) = match authority.rsplit_once(':') { + Some((target, port)) => (target, Some(port.parse().ok()?)), + None => (authority, None), + }; + (target, port, format!("/{path}")) + } else { + let (target, path) = text.split_once(':')?; + if target.chars().count() < 2 { + return None; + } + (target, None, path.to_owned()) + }; + // A target that starts with a dash would be read by `ssh` as an + // option, and one of those runs a command of its choosing. + let plain = !target.is_empty() + && !target.starts_with('-') + && target.chars().all(|char| { + char.is_ascii_alphanumeric() || "@._-".contains(char) + }); + // `http://x/y` splits the same way, into a path of two slashes. + let rooted = path.starts_with('/') && !path.starts_with("//"); + (plain && rooted && !path.contains('\0')).then(|| Self { + target: target.to_owned(), + port, + path: tidy(&path), + }) + } + + /// The same place with another directory. + #[must_use] + pub fn at(&self, path: &str) -> Self { + Self { + path: tidy(path), + ..self.clone() + } + } +} + +impl std::fmt::Display for Remote { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}:{}", self.target, self.path) + } +} + +/// `path` with forward slashes and no trailing one, `/` itself aside. A +/// path that came back from a Windows `PathBuf` has both kinds. +fn tidy(path: &str) -> String { + let path = path.replace('\\', "/"); + let trimmed = path.trim_end_matches('/'); + if trimmed.is_empty() { + "/".to_owned() + } else { + trimmed.to_owned() + } +} + +/// `target` with its host spelled as the user's SSH config spells it. +/// +/// `ssh` matches a `Host` line by case, so `mybox` does not find the +/// entry for `MyBox` and is looked up as a name on the network instead, +/// which fails with nothing to say why. A name is not told apart by case +/// anywhere else it is typed, so the entry's own spelling is used when +/// the typed one names no entry exactly. Patterns are left to `ssh`. +fn as_configured(target: &str, config: &str) -> String { + let (user, host) = match target.rsplit_once('@') { + Some((user, host)) => (Some(user), host), + None => (None, target), + }; + let names: Vec<&str> = config + .lines() + .filter_map(|line| { + let line = line.trim(); + let (word, rest) = line + .split_once(|char: char| char.is_whitespace() || char == '=')?; + word.eq_ignore_ascii_case("host").then_some(rest) + }) + .flat_map(|names| names.split([' ', '\t', '='])) + .filter(|name| !name.is_empty() && !name.contains(['*', '?', '!'])) + .collect(); + let spelled = if names.contains(&host) { + host + } else { + names + .into_iter() + .find(|name| name.eq_ignore_ascii_case(host)) + .unwrap_or(host) + }; + match user { + Some(user) => format!("{user}@{spelled}"), + None => spelled.to_owned(), + } +} + +/// `text` as one word of a POSIX shell: the path is the one thing in the +/// remote command that is not ours, and it must stay a path. +fn quoted(text: &str) -> String { + format!("'{}'", text.replace('\'', "'\\''")) +} + +/// The command the other machine runs. One record per entry, NUL-ended +/// since a name may hold a newline: type, 512-byte blocks, length, last +/// write, and the path below the start. +fn listing_command(path: &str, options: &ScanOptions) -> String { + // The slash after the path has `find` enter a start that is a link + // to a directory, as `/bin` and many a `/var/www` are; without it + // the link alone is listed and there is no tree. + format!( + "LC_ALL=C find {}/ {}-printf '%y\\t%b\\t%s\\t%T@\\t%P\\0'", + quoted(path), + if options.one_filesystem { "-xdev " } else { "" }, + ) +} + +/// List `remote` over SSH and build its tree, sizes not yet totalled. +/// Blocks until the listing ends or `progress` is cancelled. +pub(crate) fn scan( + remote: &Remote, + options: &ScanOptions, + progress: &ScanProgress, +) -> io::Result { + let mut command = Command::new("ssh"); + command + // No prompt can be answered from a window: a key, an agent or the + // config has to be enough, and a host not yet known is refused + // rather than trusted on first sight. + .args(["-o", "BatchMode=yes", "-o", "ConnectTimeout=10"]); + if let Some(port) = remote.port { + command.args(["-p", &port.to_string()]); + } + let config = std::env::home_dir() + .and_then(|home| { + std::fs::read_to_string(home.join(".ssh").join("config")).ok() + }) + .unwrap_or_default(); + command + .arg("--") + .arg(as_configured(&remote.target, &config)) + .arg(listing_command(&remote.path, options)) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt as _; + // `CREATE_NO_WINDOW`: no console flashes up beside the window. + command.creation_flags(0x0800_0000); + } + let mut child = command.spawn().map_err(|error| { + io::Error::new(error.kind(), format!("cannot start ssh: {error}")) + })?; + let stdout = child.stdout.take().ok_or_else(|| io::Error::other("ssh"))?; + let mut stderr = + child.stderr.take().ok_or_else(|| io::Error::other("ssh"))?; + // Read beside the listing: `find` complains about every directory it + // may not enter, and a full pipe would stop it. + let complaints = std::thread::spawn(move || { + let mut said = String::new(); + let _ = stderr.read_to_string(&mut said); + said + }); + let name = remote.path.rsplit('/').next().unwrap_or_default(); + let name = if name.is_empty() { "/" } else { name }; + let tree = read_listing(BufReader::new(stdout), name, options, progress); + if progress.is_cancelled() { + let _ = child.kill(); + } + let status = child.wait()?; + let said = complaints.join().unwrap_or_default(); + for line in said.lines().filter(|line| line.starts_with("find:")) { + progress + .record_error(Path::new(&remote.target), &io::Error::other(line)); + } + let tree = tree?; + if let Some(error) = cut_short(status.code(), &said) { + return Err(error); + } + match tree { + Some(tree) => Ok(tree), + // Nothing listed at all: `ssh` or `find` said why. + None => Err(io::Error::other( + said.lines() + .find(|line| !line.trim().is_empty()) + .map_or_else( + || format!("ssh ended with {status} and listed nothing"), + str::to_owned, + ), + )), + } +} + +/// Why a listing that ended is not the whole of it, when it is not. `ssh` +/// ends with 255 for a failure of its own — a connection refused, or one +/// that dropped half way — and with the remote command's status +/// otherwise; `find` ends with 1 for a directory it may not enter, which +/// is an ordinary scan. Half a tree must not pass for a whole one: its +/// totals would be believed. +fn cut_short(status: Option, said: &str) -> Option { + (status == Some(255)).then(|| { + io::Error::other( + said.lines() + .map(str::trim) + .find(|line| !line.is_empty() && !line.starts_with("find:")) + .map_or_else( + || "the ssh connection ended before the listing did".into(), + str::to_owned, + ), + ) + }) +} + +/// Build the tree from a listing. `find` names a directory before what is +/// in it, so the directories still open are a stack: a record at a depth +/// closes every one at that depth or below, each into its parent. +/// `None` when the listing has no record for the start itself. +fn read_listing( + mut listing: impl BufRead, + root_name: &str, + options: &ScanOptions, + progress: &ScanProgress, +) -> io::Result> { + let mut open: Vec = Vec::new(); + // Depth below which entries are skipped, inside a hidden directory. + let mut skipping: Option = None; + let mut record = Vec::new(); + loop { + record.clear(); + if listing.read_until(0, &mut record)? == 0 { + break; + } + if progress.is_cancelled() { + return Err(io::Error::new( + io::ErrorKind::Interrupted, + "cancelled", + )); + } + if record.last() == Some(&0) { + record.pop(); + } + let Some(entry) = Entry::parse(&record) else { + continue; + }; + let depth = if entry.path.is_empty() { + 0 + } else { + entry.path.split('/').count() + }; + if skipping.is_some_and(|hidden| depth > hidden) { + continue; + } + skipping = None; + let name = entry.path.rsplit('/').next().unwrap_or_default(); + if depth > 0 && !options.include_hidden && name.starts_with('.') { + skipping = Some(depth); + continue; + } + // A record can only be placed in a directory that is open; one + // that arrives early is out of order and has nowhere to go. + if depth > open.len() { + continue; + } + close(&mut open, depth); + let bytes = if options.apparent_size { + entry.length + } else { + entry.blocks.saturating_mul(512) + }; + if entry.kind == NodeKind::Directory { + let mut node = + Node::directory(if depth == 0 { root_name } else { name }); + node.modified = entry.modified; + open.push(node); + progress.add(0, 1, 0); + } else if let Some(parent) = open.last_mut() { + // Sockets, fifos and devices are addressable, not space. + let bytes = if entry.kind == NodeKind::Other { + 0 + } else { + bytes + }; + let mut node = Node::entry(name, entry.kind, bytes); + node.modified = entry.modified; + parent.children.push(node); + progress.add(u64::from(entry.kind == NodeKind::File), 0, bytes); + } + } + close(&mut open, 1); + Ok(open.pop()) +} + +/// Close every open directory at `depth` or below into its parent. +fn close(open: &mut Vec, depth: usize) { + while open.len() > depth.max(1) { + if let Some(done) = open.pop() + && let Some(parent) = open.last_mut() + { + parent.children.push(done); + } + } +} + +/// One record of the listing. +struct Entry { + kind: NodeKind, + blocks: u64, + length: u64, + modified: i64, + /// Below the start; empty for the start itself. + path: String, +} + +impl Entry { + fn parse(record: &[u8]) -> Option { + let mut fields = record.splitn(5, |byte| *byte == b'\t'); + let kind = match fields.next()? { + b"d" => NodeKind::Directory, + b"f" => NodeKind::File, + b"l" => NodeKind::Symlink, + _ => NodeKind::Other, + }; + let number = |field: Option<&[u8]>| { + std::str::from_utf8(field?).ok()?.parse::().ok() + }; + let blocks = number(fields.next())?; + let length = number(fields.next())?; + // Seconds with a fraction; the whole seconds are what is kept. + let modified = std::str::from_utf8(fields.next()?) + .ok()? + .split('.') + .next()? + .parse() + .ok()?; + let path = String::from_utf8_lossy(fields.next()?).into_owned(); + Some(Self { + kind, + blocks, + length, + modified, + path, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tree::{Metric, aggregate}; + + #[test] + fn a_host_is_found_in_the_config_whatever_its_case() { + let config = "# mine\nHost box-HS other\n HostName 10.0.0.9\n\ + Host *.lan !gate\n User me\nhost=Lower\n"; + assert_eq!(as_configured("Box-hs", config), "box-HS"); + assert_eq!(as_configured("me@BOX-HS", config), "me@box-HS"); + assert_eq!(as_configured("OTHER", config), "other"); + assert_eq!(as_configured("lower", config), "Lower"); + // Spelled as an entry is, or naming none: as typed. + assert_eq!(as_configured("box-HS", config), "box-HS"); + assert_eq!(as_configured("elsewhere", config), "elsewhere"); + // A pattern is ssh's to match, and `HostName` is not `Host`. + assert_eq!(as_configured("X.LAN", config), "X.LAN"); + assert_eq!(as_configured("10.0.0.9", config), "10.0.0.9"); + assert_eq!(as_configured("me@box", ""), "me@box"); + } + + #[test] + fn a_listing_ssh_did_not_finish_is_not_a_tree() { + // `find` could not enter a directory: an ordinary scan. + assert!( + cut_short(Some(1), "find: '/root': Permission denied").is_none() + ); + assert!(cut_short(Some(0), "").is_none()); + // `ssh` itself failed, before the listing or part way through it. + let dropped = cut_short( + Some(255), + "find: '/root': Permission denied\nConnection to host closed.\n", + ) + .expect("an error"); + assert_eq!(dropped.to_string(), "Connection to host closed."); + assert!(cut_short(Some(255), "").is_some()); + } + + fn listing(records: &[&str]) -> Vec { + records + .iter() + .flat_map(|record| record.bytes().chain([0])) + .collect() + } + + fn read(records: &[&str], options: &ScanOptions) -> Option { + let progress = ScanProgress::default(); + let mut tree = read_listing( + listing(records).as_slice(), + "data", + options, + &progress, + ) + .expect("a listing")?; + aggregate(&mut tree, Metric::Bytes); + Some(tree) + } + + const RECORDS: [&str; 8] = [ + "d\t8\t4096\t1700000000.5\t", + "d\t8\t4096\t1700000001.0\tlogs", + "f\t16\t5000\t1700000002.0\tlogs/app.log", + "d\t8\t4096\t1700000003.0\tlogs/old", + "f\t8\t100\t1700000004.0\tlogs/old/a\nb.log", + "d\t8\t4096\t1700000005.0\t.cache", + "f\t2048\t1000000\t1700000006.0\t.cache/blob", + "l\t0\t11\t1700000007.0\tlink", + ]; + + #[test] + fn an_address_is_read_as_scp_or_as_a_url_and_a_local_path_is_not() { + let remote = Remote::parse(" me@box.lan:/var/log/ ").expect("scp"); + assert_eq!(remote.target, "me@box.lan"); + assert_eq!(remote.path, "/var/log"); + assert_eq!(remote.port, None); + assert_eq!(remote.to_string(), "me@box.lan:/var/log"); + let remote = Remote::parse("ssh://me@box:2222/srv").expect("url"); + assert_eq!((remote.port, remote.path.as_str()), (Some(2222), "/srv")); + assert_eq!(Remote::parse("box:/").expect("root").path, "/"); + assert_eq!(remote.at("\\srv\\www\\").path, "/srv/www"); + for local in [ + "C:/Users", + "C:\\Users", + "/home/me", + "box:relative", + "-oProxyCommand=x:/tmp", + "me@box;rm:/tmp", + "ssh://box", + "http://box/path", + ] { + assert_eq!(Remote::parse(local), None, "{local}"); + } + } + + #[test] + fn the_path_stays_one_word_whatever_is_in_it() { + let command = + listing_command("/srv/it's; rm -rf ~", &ScanOptions::default()); + assert!( + command.contains("find '/srv/it'\\''s; rm -rf ~'/ -xdev -printf"), + "{command}" + ); + } + + #[test] + fn a_listing_becomes_the_tree_it_lists() { + let tree = read(&RECORDS, &ScanOptions::default()).expect("a tree"); + assert_eq!(tree.name.as_ref(), "data"); + // Blocks, not lengths: 16 + 8 + 2048 of them. + assert_eq!(tree.bytes, (16 + 8 + 2048) * 512); + assert_eq!(tree.files, 3); + let logs = tree.child_named("logs").expect("logs"); + assert_eq!(logs.bytes, 24 * 512); + // A name with a newline in it is one entry, in the right place. + let old = logs.child_named("old").expect("old"); + assert!(old.child_named("a\nb.log").is_some()); + assert_eq!(logs.modified, 1_700_000_004); + assert!(tree.child_named("link").is_some()); + } + + #[test] + fn lengths_and_hidden_entries_follow_the_scan_options() { + let options = ScanOptions { + apparent_size: true, + include_hidden: false, + ..ScanOptions::default() + }; + let tree = read(&RECORDS, &options).expect("a tree"); + // Without `.cache` and what is in it; the link's length counts. + assert!(tree.child_named(".cache").is_none()); + assert_eq!(tree.bytes, 5000 + 100 + 11); + } + + #[test] + fn nothing_listed_is_no_tree() { + assert!(read(&[], &ScanOptions::default()).is_none()); + // A record that is not one is passed over. + assert!(read(&["find: nonsense"], &ScanOptions::default()).is_none()); + } +} diff --git a/crates/disktree-core/src/scan.rs b/crates/disktree-core/src/scan.rs index 693253a7..cca2bcd0 100644 --- a/crates/disktree-core/src/scan.rs +++ b/crates/disktree-core/src/scan.rs @@ -142,7 +142,7 @@ impl ScanProgress { self.bytes.store(bytes, Ordering::Relaxed); } - fn record_error(&self, path: &Path, error: &io::Error) { + pub(crate) fn record_error(&self, path: &Path, error: &io::Error) { self.errors.fetch_add(1, Ordering::Relaxed); // A scan without Full Disk Access can refuse thousands of paths; // only the ones that will be kept are worth formatting. @@ -247,6 +247,31 @@ impl ScanHandle { Self { progress, result } } + /// Start listing another machine over SSH on a worker thread. The + /// handle is the same as a walk's, so whoever waits on one waits on + /// either; see [`crate::remote`] for what the tree may be used for. + pub fn spawn_remote( + remote: crate::remote::Remote, + options: ScanOptions, + ) -> Self { + let progress = Arc::new(ScanProgress::default()); + let (sender, result) = mpsc::channel(); + let shared = Arc::clone(&progress); + let worker = thread::Builder::new().name("disktree-ssh".into()).spawn( + move || { + let outcome = crate::remote::scan(&remote, &options, &shared) + .map(|node| finish_tree(node, &options, &WALK_POOL)); + shared.finish(); + let _ = sender.send(outcome); + }, + ); + if let Err(error) = worker { + progress.record_error(Path::new("scan worker"), &error); + progress.finish(); + } + Self { progress, result } + } + /// Take the finished tree, if the walk is done. pub fn poll(&self) -> Option> { match self.result.try_recv() { diff --git a/crates/disktree-core/src/size.rs b/crates/disktree-core/src/size.rs index 69cbe624..41002f22 100644 --- a/crates/disktree-core/src/size.rs +++ b/crates/disktree-core/src/size.rs @@ -3,33 +3,65 @@ //! Binary units, like `du -h` and dust. One decimal below 10, none above 100: //! enough resolution to compare neighbours without a wall of digits. +use std::sync::atomic::{AtomicBool, Ordering}; + const BYTE_UNITS: [&str; 6] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]; +/// The same sizes counted in thousands, as a drive's box and Windows' +/// own File Explorer in other systems' clothes count them. +const DECIMAL_UNITS: [&str; 6] = ["B", "kB", "MB", "GB", "TB", "PB"]; + +/// Whether sizes are written in thousands rather than 1024s. One switch for +/// the whole process: a size reads the same wherever it is shown, and +/// threading the choice through every caller would let two of them differ. +static DECIMAL: AtomicBool = AtomicBool::new(false); + +/// Write sizes in GB (thousands) from now on, or in GiB (1024s) again. +pub fn set_decimal_units(decimal: bool) { + DECIMAL.store(decimal, Ordering::Relaxed); +} + +/// Whether sizes are being written in GB rather than GiB. +pub fn decimal_units() -> bool { + DECIMAL.load(Ordering::Relaxed) +} + +/// What one step between units is: 1000 or 1024. +pub fn unit_step() -> f64 { + if decimal_units() { 1000.0 } else { 1024.0 } +} + /// `1.4 GiB`, `523 MiB`, `12 B`. pub fn human_bytes(bytes: u64) -> String { - scale(bytes).format(1) + scale(bytes, decimal_units()).format(1) } /// `1.4G`, `523M`, `12B`: for tile labels, where columns are scarce. pub fn human_bytes_short(bytes: u64) -> String { - scale(bytes).format(0) + scale(bytes, decimal_units()).format(0) } -fn scale(bytes: u64) -> Scaled { +fn scale(bytes: u64, decimal: bool) -> Scaled { + let step = if decimal { 1000.0 } else { 1024.0 }; let mut value = bytes as f64; let mut unit = 0; // Step up from 1023.5, not 1024: no decimal is shown at that size, so // anything above it would print as `1024 KiB` instead of `1.0 MiB`. - while value >= 1023.5 && unit + 1 < BYTE_UNITS.len() { - value /= 1024.0; + while value >= step - 0.5 && unit + 1 < BYTE_UNITS.len() { + value /= step; unit += 1; } - Scaled { value, unit } + Scaled { + value, + unit, + decimal, + } } struct Scaled { value: f64, unit: usize, + decimal: bool, } impl Scaled { @@ -42,10 +74,15 @@ impl Scaled { } else { format!("{:.0}", self.value) }; + let units = if self.decimal { + DECIMAL_UNITS + } else { + BYTE_UNITS + }; if gap == 0 { - format!("{text}{}", BYTE_UNITS[self.unit]) + format!("{text}{}", units[self.unit]) } else { - format!("{text} {}", BYTE_UNITS[self.unit]) + format!("{text} {}", units[self.unit]) } } } @@ -95,6 +132,17 @@ pub fn share_bar(part: u64, total: u64, width: usize) -> String { mod tests { use super::*; + #[test] + fn sizes_can_be_counted_in_thousands() { + let decimal = |bytes| scale(bytes, true).format(1); + assert_eq!(decimal(999), "999 B"); + assert_eq!(decimal(1000), "1.0 kB"); + assert_eq!(decimal(1_500_000), "1.5 MB"); + assert_eq!(decimal(317_000_000_000), "317 GB"); + // The same bytes in 1024s, which is the default. + assert_eq!(scale(317_000_000_000, false).format(1), "295 GiB"); + } + #[test] fn bytes_use_binary_units_with_one_decimal_below_ten() { assert_eq!(human_bytes(0), "0 B"); diff --git a/crates/disktree-core/src/space.rs b/crates/disktree-core/src/space.rs index 8a2bc4ee..a2a04214 100644 --- a/crates/disktree-core/src/space.rs +++ b/crates/disktree-core/src/space.rs @@ -689,6 +689,20 @@ pub const fn foreign_mounts_for(_root: &Path) -> Option> { Some(Vec::new()) } +/// The name of the volume `path` is on, where the system keeps one. +#[cfg(windows)] +pub fn volume_label(path: &Path) -> Option { + crate::windows::volume_root(path) + .and_then(|root| crate::windows::volume_label(&root)) +} + +/// The name of the volume `path` is on, where the system keeps one: only +/// Windows is asked, the mount point being the name elsewhere. +#[cfg(not(windows))] +pub const fn volume_label(_path: &Path) -> Option { + None +} + /// A mounted volume the picker can switch the scan to: where it is mounted /// and how much room it has. Listed by [`volumes`]. #[derive(Clone, Debug, PartialEq, Eq)] @@ -701,6 +715,9 @@ pub struct Volume { pub device: Option, /// Free space on the volume now; `None` when it cannot be read. pub space: Option, + /// The name its owner gave it, such as `Data` for `D:\`; `None` when + /// it has none or the system does not say. + pub label: Option, } /// Every volume worth offering as a scan root, fullest first. @@ -742,6 +759,7 @@ pub fn volumes_in(mounts: &[Mount]) -> Vec { let mut volumes: Vec = seen .iter() .map(|mount| Volume { + label: None, point: mount.point.clone(), device: Some(mount.source.clone()), space: space_info(&mount.point).ok(), @@ -824,6 +842,7 @@ pub fn volumes() -> Vec { let mut volumes: Vec = points .iter() .map(|point| Volume { + label: None, point: point.clone(), device: device_for(point), space: space_info(point).ok(), @@ -844,6 +863,7 @@ pub fn volumes() -> Vec { .into_iter() .filter_map(|point| { space_info(&point).ok().map(|space| Volume { + label: crate::windows::volume_label(&point), point, device: None, space: Some(space), @@ -999,6 +1019,7 @@ portal /run/user/1000/doc fuse.portal rw 0 0 #[test] fn volumes_with_least_space_come_first_and_unknowns_last() { let volume = |name: &str, available: Option| Volume { + label: None, point: PathBuf::from(name), device: None, space: available.map(|available| SpaceInfo { diff --git a/crates/disktree-core/src/windows.rs b/crates/disktree-core/src/windows.rs index 53b8564c..9a4f0d5c 100644 --- a/crates/disktree-core/src/windows.rs +++ b/crates/disktree-core/src/windows.rs @@ -639,6 +639,31 @@ pub fn file_table_readable(root: &Path) -> bool { ok != 0 && String::from_utf16_lossy(&name[..end]) == "NTFS" } +/// The label of the volume mounted at `root`, as File Explorer shows it +/// before the drive letter. `None` for an unlabelled or unreadable volume. +pub fn volume_label(root: &Path) -> Option { + let volume = wide(root, true).ok()?; + let mut label = [0_u16; MAX_PATH as usize + 1]; + let length = u32::try_from(label.len()).unwrap_or(u32::MAX); + // SAFETY: `volume` is NUL-terminated and outlives the call, `label` is + // writable for the length passed, and the other outputs may be null. + let ok = unsafe { + GetVolumeInformationW( + volume.as_ptr(), + label.as_mut_ptr(), + length, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + 0, + ) + }; + let end = label.iter().position(|&unit| unit == 0).unwrap_or(0); + let label = String::from_utf16_lossy(&label[..end]); + (ok != 0 && !label.is_empty()).then_some(label) +} + /// Start `program` with `args` as an administrator, through the UAC /// prompt. Returns once the prompt is answered; declining it is an error /// (`ERROR_CANCELLED`).