A treemap for finding and removing what fills your disk, for Omarchy. Rust + GPUI.
Rust
space, app: a volume picker listing every mounted volume and its free space
Abdulwahb Isam93cb8c64b722
diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rsindex 27e1846..d78f3c0 100644--- a/crates/disktree-app/src/state.rs+++ b/crates/disktree-app/src/state.rs@@ -419,6 +419,12 @@ pub struct Disktree {/// The top of the disk the scanned root lives on: what "Whole disk"/// scans. Follows the root when a folder is opened.pub disk_root: Option<PathBuf>,+ /// The volume picker: open, what it listed, and which row the keys are+ /// on. `None` when closed; empty when no volume besides the current one+ /// could be read.+ pub volumes_open: bool,+ pub volumes: Vec<disktree_core::space::Volume>,+ pub volume_highlight: usize,/// The side panel's width, in rem; dragged from its left edge.pub panel_rems: f32,pub scan_started: Option<Instant>,@@ -506,6 +512,9 @@ impl Disktree {device: None,full_disk_access: None,disk_root: None,+ volumes_open: false,+ volumes: Vec::new(),+ volume_highlight: 0,panel_rems: PANEL_REMS,scan_started: None,scan_root: PathBuf::new(),@@ -599,6 +608,68 @@ impl Disktree {cx.notify();}+ /// `V`: list every volume and let the scan move to one. The in-flight walk+ /// 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>) {+ let mut volumes = disktree_core::space::volumes();+ // The current disk is always offered, even when the table misses it:+ // it is the one row that is never wrong.+ if let Some(root) = volume_root_for(&self.root_path)+ && !volumes.iter().any(|volume| volume.point == root)+ {+ volumes.push(disktree_core::space::Volume {+ point: root.clone(),+ device: device_for(&root),+ space: space_info(&root).ok(),+ });+ }+ volumes.retain(|volume| volume.point != self.root_path);+ self.volume_highlight = 0;+ self.volumes = volumes;+ self.volumes_open = true;+ cx.notify();+ }++ /// Scan the highlighted volume from scratch; closes the picker when there+ /// is nothing to pick.+ pub fn choose_volume(&mut self, cx: &mut Context<'_, Self>) {+ let Some(point) = self+ .volumes+ .get(self.volume_highlight)+ .map(|volume| volume.point.clone())+ else {+ self.volumes_open = false;+ cx.notify();+ return;+ };+ self.volumes_open = false;+ self.volumes.clear();+ self.set_root(point, cx);+ }++ /// Move the highlight in the open picker, wrapping at the ends.+ pub fn move_volume_highlight(+ &mut self,+ step: i32,+ cx: &mut Context<'_, Self>,+ ) {+ if self.volumes.is_empty() {+ return;+ }+ let len = self.volumes.len();+ let at = self.volume_highlight;+ // Picker steps are ±1, but wrap either way without casting the length+ // down to a narrower type.+ let next = match step.signum() {+ 1 => (at + 1) % len,+ -1 => at.checked_sub(1).unwrap_or(len - 1),+ _ => at,+ };+ self.volume_highlight = next;+ cx.notify();+ }+/// `g`: the whole disk. Widens when the disk is above the scanned root,/// and goes to its top when it already is the root.pub fn go_to_disk(&mut self, cx: &mut Context<'_, Self>) {@@ -2259,6 +2330,26 @@ impl Disktree {return;}+ // The volume picker owns its keys while open: arrows move, Enter+ // picks, Escape closes, and nothing behind it acts.+ if self.volumes_open {+ match key {+ "escape" => {+ self.volumes_open = false;+ cx.notify();+ }+ "enter" => self.choose_volume(cx),+ "up" | "k" if !control => {+ self.move_volume_highlight(-1, cx);+ }+ "down" | "j" if !control => {+ self.move_volume_highlight(1, cx);+ }+ _ => {}+ }+ return;+ }+// ⌘ chords belong to the menu bar (⌘Q, ⌘W, ⌘R) or to the system.// Read as plain letters they would act twice or by surprise: ⌘D// would re-scan with apparent sizes, ⌘H would hide *and* toggle.@@ -2430,6 +2521,7 @@ 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);diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rsindex af151ec..1b7f4db 100644--- a/crates/disktree-app/src/tests.rs+++ b/crates/disktree-app/src/tests.rs@@ -466,6 +466,27 @@ fn the_help_overlay_opens_and_closes(cx: &mut TestAppContext) {assert!(!read(&view, cx, |app| app.show_help));}+#[gpui_kit::test]+fn the_volume_picker_opens_moves_and_closes(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ draw(cx);++ // The picker lists volumes and draws them without panicking; Escape+ // leaves the scan where it was.+ press(cx, "v");+ assert!(read(&view, cx, |app| app.volumes_open));+ draw(cx);+ assert!(cx.debug_bounds("disktree-root").is_some());+ let before = read(&view, cx, |app| app.root_path.clone());+ press(cx, "down");+ press(cx, "up");+ press(cx, "escape");+ assert!(!read(&view, cx, |app| app.volumes_open));+ assert_eq!(read(&view, cx, |app| app.root_path.clone()), before);+}+#[gpui_kit::test]fn showing_a_tile_that_is_gone_says_so_instead(cx: &mut TestAppContext) {cx.update(gpui_omarchy::init);diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rsindex 8f75253..22febac 100644--- a/crates/disktree-app/src/views.rs+++ b/crates/disktree-app/src/views.rs@@ -111,12 +111,84 @@ pub fn root(if app.show_help {root = root.child(help_overlay(app, cx));}+ if app.volumes_open {+ root = root.child(volumes_dialog(app, cx));+ }if app.confirm_open {root = root.child(delete_dialog(app, cx));}root}+/// Picking another volume scans it from scratch: the picker lists every+/// volume with its free space, and the choice is the new root.+fn volumes_dialog(+ app: &Disktree,+ cx: &mut Context<'_, Disktree>,+) -> impl IntoElement {+ let theme = cx.omarchy().clone();+ let cancel = cx.entity().downgrade();+ let mut rows = div().flex().flex_col().gap(space::XS);+ if app.volumes.is_empty() {+ rows = rows+ .child(dialog_description("No other volume could be read.", cx));+ }+ 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 label = match &volume.device {+ Some(device) => format!(+ "{} \u{00b7} {device} \u{00b7} {free}",+ volume.point.display()+ ),+ None => format!("{} \u{00b7} {free}", volume.point.display()),+ };+ rows = rows.child(+ div()+ .id(ElementId::Name(format!("volume-{index}").into()))+ .px(space::MD)+ .py(space::SM)+ .text_size(text::BODY)+ .text_color(if highlighted {+ theme.bright+ } else {+ theme.foreground+ })+ // Only the row the keys are on is tinted: a second highlight+ // would read as a second selection.+ .when(highlighted, |row| row.bg(theme.accent.opacity(0.18)))+ .hover(|row| row.bg(theme.accent.opacity(0.1)))+ .child(label)+ .on_click(cx.listener(move |this, _, window, cx| {+ this.volume_highlight = index;+ this.choose_volume(cx);+ window.focus(&this.focus, cx);+ })),+ );+ }+ let popup = dialog_popup(cx)+ .child(dialog_title("Scan a volume", cx))+ .child(dialog_description(+ "Up and down moves, Enter scans it, Escape stays here.",+ cx,+ ))+ .child(rows);+ alert_dialog(&app.confirm_focus, cx)+ .open(true)+ .on_cancel(move |_, window, cx| {+ let _ = cancel.update(cx, |this, cx| {+ this.volumes_open = false;+ cx.notify();+ this.apply_focus(window, cx);+ });+ false+ })+ .popup(popup)+}+/// 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.@@ -1588,19 +1660,30 @@ fn disk_section(cx: &Context<'_, Disktree>,) -> Div {let device = app.device.clone().unwrap_or_default();- let mut section = div().flex().flex_col().gap(space::SM).child(- div()- .flex()- .flex_row()- .gap(space::SM)- .child(widgets::eyebrow("Disk", cx))- .child(- div()- .text_size(text::CAPTION)- .text_color(theme.secondary.opacity(0.6))- .child(device),- ),- );+ // The disk header doubles as the way to another volume: it opens the+ // picker, like `V` does. A plain label would hide that the scan can move.+ let header = div()+ .flex()+ .flex_row()+ .items_center()+ .gap(space::SM)+ .child(widgets::eyebrow("Disk", cx))+ .child(+ div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary.opacity(0.6))+ .child(device),+ )+ .child(div().flex_1())+ .child(+ button("volumes", "Volumes", ButtonVariant::Secondary, cx)+ .tab_stop(false)+ .on_click(cx.listener(|this, _, window, cx| {+ this.open_volumes(cx);+ window.focus(&this.focus, cx);+ })),+ );+ let mut section = div().flex().flex_col().gap(space::SM).child(header);let Some(space_info) = app.space else {return section.child(div()@@ -1751,7 +1834,7 @@ fn review_button(/// to every other key and the scan's own numbers hold the trailing edge.fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div {// Most useful first, so a narrow window clips the least useful.- let hints: [(&str, &str); 10] = [+ let hints: [(&str, &str); 11] = [("space", "mark"),("enter", "open"),("\u{232b}", "up"),@@ -1761,6 +1844,7 @@ fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div {("[ ]", "depth"),("t", "mode"),("0", "reset"),+ ("v", "volumes"),("r", "rescan"),];let mut lane = div()@@ -2995,7 +3079,7 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div {let theme = cx.omarchy();// Sentence case, and the tile a key acts on is always the one under the// pointer if the pointer moved last, else the keyboard selection.- let rows: [(&str, &str); 27] = [+ let rows: [(&str, &str); 28] = [("space / x", "Mark or unmark the tile you point at"),(MODIFIER_CLICK, "Mark without moving the selection"),("enter", "Open that directory, at any depth"),@@ -3021,6 +3105,7 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div {("c", "Review the marked list"),("t", "Size, files or age: what areas and colours say"),("r", "Scan again from the same root"),+ ("v", "Scan another volume"),(MODIFIER_OPEN, "Choose another directory to scan"),("g", "The whole disk; click any directory above to widen"),("d", "Disk usage or apparent size"),diff --git a/crates/disktree-core/src/space.rs b/crates/disktree-core/src/space.rsindex f7b5bb4..91dade7 100644--- a/crates/disktree-core/src/space.rs+++ b/crates/disktree-core/src/space.rs@@ -329,6 +329,175 @@ pub const fn foreign_mounts_for(_root: &Path) -> Option<Vec<PathBuf>> {Some(Vec::new())}+/// 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)]+pub struct Volume {+ /// Where the volume is mounted: `C:\` on Windows, `/` or `/home` on+ /// Linux, `/` on macOS.+ pub point: PathBuf,+ /// What is mounted there, when the table names it: a device such as+ /// `/dev/nvme0n1p2`, or a name like `tmpfs`.+ pub device: Option<String>,+ /// Free space on the volume now; `None` when it cannot be read.+ pub space: Option<SpaceInfo>,+}++impl Volume {+ /// Free bytes for ranking; an unreadable volume sorts last.+ const fn available(&self) -> u64 {+ match &self.space {+ Some(space) => space.available,+ None => 0,+ }+ }+}++/// Every volume worth offering as a scan root, fullest first.+///+/// Pseudo filesystems (`/proc`, `/sys`, tmpfs, …), snapshot subvolumes and+/// automount points are left out: switching the scan to one of those would+/// measure the wrong thing, the same reason [`foreign_mounts`] keeps a scan+/// from entering them. Duplicates from one device mounted twice (a btrfs+/// subvolume at `/` and `/home`) collapse to the shortest mount point, which+/// is the top of that disk.+#[cfg(not(any(target_os = "macos", windows)))]+pub fn volumes() -> Vec<Volume> {+ let Ok(table) = std::fs::read_to_string("/proc/self/mounts") else {+ return Vec::new();+ };+ volumes_in(&parse_mounts(&table))+}++/// [`volumes`] over a given mount table, for testing.+pub fn volumes_in(mounts: &[Mount]) -> Vec<Volume> {+ let mut seen: Vec<&Mount> = Vec::new();+ for mount in mounts {+ if !is_volume_candidate(mount) {+ continue;+ }+ // One device mounted twice (a btrfs disk at `/`, `/home`,+ // `/var/log`) is one volume: keep the shortest mount point, which is+ // the top of that disk.+ if let Some(known) = seen.iter_mut().find(|known| {+ known.source == mount.source && known.fstype == mount.fstype+ }) {+ if mount.point.as_os_str().len() < known.point.as_os_str().len() {+ *known = mount;+ }+ continue;+ }+ seen.push(mount);+ }+ let mut volumes: Vec<Volume> = seen+ .iter()+ .map(|mount| Volume {+ point: mount.point.clone(),+ device: Some(mount.source.clone()),+ space: space_info(&mount.point).ok(),+ })+ .collect();+ // The scarcest room is the most interesting to a cleanup tool, so the+ // fullest volume that still reads is first; unreadable ones sort last.+ sort_by_free_space(&mut volumes);+ volumes+}++/// Fullest first; an unreadable volume sorts last.+fn sort_by_free_space(volumes: &mut [Volume]) {+ volumes.sort_by_key(|volume| std::cmp::Reverse(volume.available()));+}++/// Whether the mount is a real disk worth scanning: a device-backed+/// filesystem that is not a snapshot, an automount point, or one of the+/// pseudo filesystems the scan itself refuses to enter.+fn is_volume_candidate(mount: &Mount) -> bool {+ if is_snapshot(mount) {+ return false;+ }+ if mount+ .options+ .split(',')+ .any(|option| option == "automounted" || option.starts_with("autofs"))+ {+ return false;+ }+ !matches!(+ mount.fstype.as_str(),+ "autofs"+ | "cgroup"+ | "cgroup2"+ | "configfs"+ | "debugfs"+ | "devpts"+ | "devtmpfs"+ | "fuse.portal"+ | "fusectl"+ | "hugetlbfs"+ | "mqueue"+ | "nsfs"+ | "overlay"+ | "proc"+ | "pstore"+ | "securityfs"+ | "sysfs"+ | "tmpfs"+ | "tracefs"+ )+}++/// Every volume worth offering as a scan root, fullest first.+///+/// The Data volume's second mount is the same disk under another name, so it+/// is left out; the firmlinks joined into `/` mean `/` already shows it.+#[cfg(target_os = "macos")]+pub fn volumes() -> Vec<Volume> {+ use std::process::Command;++ let output = Command::new("mount")+ .output()+ .ok()+ .and_then(|output| String::from_utf8(output.stdout).ok());+ let Some(output) = output else {+ return Vec::new();+ };+ let mut points = parse_macos_mounts(&output);+ points.retain(|point| {+ point.as_os_str() != MACOS_DATA_VOLUME && !point.as_os_str().is_empty()+ });+ let mut volumes: Vec<Volume> = points+ .iter()+ .map(|point| Volume {+ point: point.clone(),+ device: device_for(point),+ space: space_info(point).ok(),+ })+ .collect();+ sort_by_free_space(&mut volumes);+ volumes+}++/// Every place a volume is mounted that can be scanned.+///+/// Drive roots such as `D:\` and folders a volume is mounted on. Unready+/// drives (an empty card reader reports a path but no space) are left out,+/// since there is nothing to measure there.+#[cfg(windows)]+pub fn volumes() -> Vec<Volume> {+ let mut volumes: Vec<Volume> = crate::windows::mount_points()+ .into_iter()+ .filter_map(|point| {+ space_info(&point).ok().map(|space| Volume {+ point,+ device: None,+ space: Some(space),+ })+ })+ .collect();+ sort_by_free_space(&mut volumes);+ volumes+}+#[cfg(test)]mod tests {use super::*;@@ -366,6 +535,33 @@ portal /run/user/1000/doc fuse.portal rw 0 0assert_eq!(foreign, expected, "/home and /var/log are the same disk");}+ #[test]+ fn volume_candidates_are_real_disks_not_pseudo_filesystems() {+ let mounts = parse_mounts(OMARCHY);+ let points: Vec<PathBuf> = volumes_in(&mounts)+ .iter()+ .map(|volume| volume.point.clone())+ .collect();+ // One btrfs disk (at `/`, collapsing `/home` and `/var/log`), plus+ // the boot disk; tmpfs, autofs, portals and snapshots are not scans.+ assert!(points.contains(&PathBuf::from("/")), "{points:?}");+ assert!(points.contains(&PathBuf::from("/boot")), "{points:?}");+ assert_eq!(points.len(), 2, "{points:?}");+ }++ #[test]+ fn separate_home_disk_is_its_own_volume() {+ let separate = parse_mounts(+ "/dev/sda1 / ext4 rw 0 0\n/dev/sdb1 /home ext4 rw 0 0\n",+ );+ let points: Vec<PathBuf> = volumes_in(&separate)+ .iter()+ .map(|volume| volume.point.clone())+ .collect();+ assert!(points.contains(&PathBuf::from("/")), "{points:?}");+ assert!(points.contains(&PathBuf::from("/home")), "{points:?}");+ }+#[test]fn the_whole_disk_is_the_top_of_the_home_volume() {let mounts = parse_mounts(OMARCHY);