A treemap for finding and removing what fills your disk, for Omarchy. Rust + GPUI.
Rust
feat(app): offer restart as administrator on Windows
Shishir Pai5f374c3b471b
diff --git a/crates/disktree-app/src/main.rs b/crates/disktree-app/src/main.rsindex 7ce0180..b5e1ca8 100644--- a/crates/disktree-app/src/main.rs+++ b/crates/disktree-app/src/main.rs@@ -73,7 +73,7 @@ fn main() -> Result<()> {}fn run() -> Result<()> {- let args = parse_args()?;+ let args = parse_args(std::env::args_os().skip(1))?;let root = args.root.clone();let depth = args.depth;let title_root = root.clone();@@ -150,15 +150,25 @@ fn run() -> Result<()> {Ok(())}-fn parse_args() -> Result<Args> {+/// Read the command line, program name already skipped.+fn parse_args(+ mut args: impl Iterator<Item = std::ffi::OsString>,+) -> Result<Args> {let mut root: Option<PathBuf> = None;let mut options = ScanOptions::default();let mut depth = 3_u32;let mut disk = false;- let mut args = std::env::args().skip(1);+ // `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+ // it was, so the caller passes `args_os`.+ let text = |value: Option<std::ffi::OsString>, need: &str| {+ value+ .and_then(|value| value.into_string().ok())+ .with_context(|| need.to_owned())+ };while let Some(arg) = args.next() {- match arg.as_str() {+ match arg.to_str().unwrap_or_default() {"-h" | "--help" => {println!("{USAGE}");std::process::exit(0);@@ -172,7 +182,7 @@ fn parse_args() -> Result<Args> {"-X" | "--cross-filesystems" => options.one_filesystem = false,"-D" | "--disk" => disk = true,"-d" | "--depth" => {- let value = args.next().context("--depth needs a number")?;+ let value = text(args.next(), "--depth needs a number")?;depth = value.parse().context("--depth needs a number")?;anyhow::ensure!((1..=6).contains(&depth),@@ -180,7 +190,7 @@ fn parse_args() -> Result<Args> {);}"--metric" => {- let value = args.next().context("--metric needs a value")?;+ let value = text(args.next(), "--metric needs a value")?;options.metric = match value.as_str() {"files" => disktree_core::tree::Metric::Files,"bytes" | "size" => disktree_core::tree::Metric::Bytes,@@ -195,9 +205,9 @@ fn parse_args() -> Result<Args> {other if other.starts_with('-') => {anyhow::bail!("unknown option {other}\n\n{USAGE}");}- path => {+ _ => {anyhow::ensure!(root.is_none(), "only one path can be scanned");- root = Some(PathBuf::from(path));+ root = Some(PathBuf::from(arg));}}}diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rsindex 27e1846..804946b 100644--- a/crates/disktree-app/src/state.rs+++ b/crates/disktree-app/src/state.rs@@ -10,6 +10,7 @@ use std::rc::Rc;use std::sync::Arc;use std::time::{Duration, Instant};+use disktree_core::access::file_table_readable;use disktree_core::filter::{Keep, Matches, filter};use disktree_core::insights::{Candidate, worth_a_look};use disktree_core::removal::{@@ -416,6 +417,15 @@ pub struct Disktree {/// Whether macOS lets this process read everything: asked once, since a/// grant only takes effect after a relaunch. `None` off macOS.pub full_disk_access: Option<bool>,+ /// Whether disktree runs as an administrator, which lets a whole drive+ /// be read from its file table instead of walked. `None` off Windows.+ pub administrator: Option<bool>,+ /// Whether the root is a whole NTFS drive, which an administrator reads+ /// from its file table. Follows the root; `false` off Windows.+ pub file_table: bool,+ /// A restart as administrator was asked for and not yet declined, so a+ /// second click does not raise a second prompt.+ pub restarting: bool,/// 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>,@@ -505,6 +515,9 @@ impl Disktree {git_pending: FxHashSet::default(),device: None,full_disk_access: None,+ administrator: disktree_core::access::administrator(),+ file_table: false,+ restarting: false,disk_root: None,panel_rems: PANEL_REMS,scan_started: None,@@ -520,6 +533,7 @@ impl Disktree {// The disk of what is on screen, as `set_root` keeps it: `disktree// /Volumes/Ext` then `g` measures that drive, like opening it with ⌘O.tree.disk_root = volume_root_for(&tree.root_path);+ tree.file_table = file_table_readable(&tree.root_path);disktree_core::removal::prime_mount_points();tree.start_scan(cx);Self::start_space_ticker(cx);@@ -557,6 +571,7 @@ impl Disktree {// can change: an external drive has its own.self.disk_root =volume_root_for(&root).or_else(|| self.disk_root.take());+ self.file_table = file_table_readable(&root);self.root_path = root;self.screen = Screen::Explore;self.start_scan(cx);@@ -671,7 +686,7 @@ impl Disktree {if !self.crumbs.is_empty() {self.remember();}- self.tree = None;+ discard(self.tree.take());self.crumbs.clear();self.selected = None;self.hovered = None;@@ -738,10 +753,11 @@ impl Disktree {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);}let metric = self.options.metric;self.marks.refresh(&self.root_path, &node, metric);- self.tree = Some(Arc::new(node));+ discard(self.tree.replace(Arc::new(node)));self.cache = None;self.refresh_insights();self.scan_elapsed =@@ -1801,7 +1817,7 @@ impl Disktree {if let Some(tree) = &self.tree {let mut tree = (**tree).clone();disktree_core::tree::aggregate(&mut tree, self.options.metric);- self.tree = Some(Arc::new(tree));+ discard(self.tree.replace(Arc::new(tree)));let metric = self.options.metric;self.marks.refresh(&self.root_path,@@ -1922,6 +1938,16 @@ impl Disktree {cx.notify();return;}+ // This window quits once the prompt is answered yes, and quitting+ // would stop a permanent delete halfway.+ if self.restarting {+ self.notice = Some((+ "not while restarting as administrator".into(),+ Status::Warning,+ ));+ cx.notify();+ return;+ }self.space_baseline = self.space.or(self.space_baseline);self.run_epoch += 1;let epoch = self.run_epoch;@@ -2726,6 +2752,80 @@ fn crumb_label(path: &Path) -> String {)}+impl Disktree {+ /// Start again as an administrator on the root this window is headed+ /// for, with the same options, and close this window once the prompt is+ /// accepted.+ /// Declined, nothing changes. Not while a removal runs: quitting would+ /// stop a permanent delete halfway.+ pub fn restart_as_administrator(&mut self, cx: &mut Context<'_, Self>) {+ if self.restarting || self.run.is_some() {+ return;+ }+ self.restarting = true;+ cx.notify();+ // While a widening scan runs, the wider root is where this window+ // ends up, and the drive the offer is about: reopening the folder+ // still on screen would walk it again. `scan_root` equals+ // `root_path` for any other scan, and is stale once none runs.+ let root = if self.scan.is_some() {+ &self.scan_root+ } else {+ &self.root_path+ };+ let args =+ restart_args(&self.options, self.layout_options.max_depth, root);+ // Off the UI thread: the prompt runs its own message loop, which+ // would re-enter this window while it is still being handled.+ let restart = cx.background_executor().spawn(async move {+ disktree_core::access::restart_as_administrator(&args)+ });+ cx.spawn(async move |this, cx| {+ let outcome = restart.await;+ let _ = this.update(cx, |this, cx| match outcome {+ Ok(()) => cx.quit(),+ Err(error) => {+ this.restarting = false;+ this.notice = Some((+ format!("still not an administrator: {error}"),+ Status::Warning,+ ));+ cx.notify();+ }+ });+ })+ .detach();+ }+}++/// The command line that reopens `root` with `options` and `depth`, in the+/// flags `parse_args` reads.+pub fn restart_args(+ options: &ScanOptions,+ depth: u32,+ root: &Path,+) -> Vec<std::ffi::OsString> {+ let mut args: Vec<std::ffi::OsString> = Vec::new();+ for (on, flag) in [+ (options.apparent_size, "--apparent-size"),+ (options.follow_links, "--follow-links"),+ (!options.include_hidden, "--no-hidden"),+ (!options.one_filesystem, "--cross-filesystems"),+ (options.metric == Metric::Files, "--metric"),+ ] {+ if on {+ args.push(flag.into());+ }+ }+ if options.metric == Metric::Files {+ args.push("files".into());+ }+ args.push("--depth".into());+ args.push(depth.to_string().into());+ args.push(root.as_os_str().to_owned());+ args+}+/// Now, in Unix seconds.pub fn now_seconds() -> i64 {std::time::SystemTime::now()@@ -2735,6 +2835,16 @@ pub fn now_seconds() -> i64 {})}+/// Let go of a tree off the UI thread: freeing a disk's millions of nodes+/// takes a good part of a second, and nothing waits on it.+fn discard(tree: Option<Arc<Node>>) {+ if let Some(tree) = tree {+ // When no thread can be made, the closure is dropped here instead,+ // and the tree is freed in place rather than taking the window down.+ let _ = std::thread::Builder::new().spawn(move || drop(tree));+ }+}+/// Smallest tile, in rem, that gets a label: below this a name cannot be read.const LABEL_MIN_W_REMS: f32 = 3.375;const LABEL_MIN_H_REMS: f32 = 0.9375;diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rsindex af151ec..bcd050c 100644--- a/crates/disktree-app/src/tests.rs+++ b/crates/disktree-app/src/tests.rs@@ -1012,6 +1012,8 @@ fn widening_reuses_the_tree_it_has_and_reads_only_the_rest(let (view, cx) = view_over(&inner, cx);update(&view, cx, |app, _| {app.disk_root = Some(temp.path().to_path_buf());+ // Stale on purpose: the wider root, a folder, must reset it.+ app.file_table = true;});let before = read(&view, cx, |app| app.tree().map(|tree| tree.files));@@ -1039,6 +1041,10 @@ fn widening_reuses_the_tree_it_has_and_reads_only_the_rest(assert!(read(&view, cx, |app| app.tree().is_some()));finish_scan(&view, cx);assert_eq!(read(&view, cx, |app| app.root_path.clone()), temp.path());+ assert!(+ !read(&view, cx, |app| app.file_table),+ "the offer follows the root it widened to"+ );let (reused, rest, selected) = read(&view, cx, |app| {let tree = app.tree().expect("the wider tree");let junk = tree.child_named("junk").map(|node| node.files);@@ -1322,3 +1328,45 @@ fn back_and_forward_retrace_where_you_have_been(cx: &mut TestAppContext) {Vec::<usize>::new());}++/// The restart as administrator reopens the same root and options: every+/// flag it writes is one the command line reads back.+#[test]+fn restart_arguments_parse_back_to_the_same_scan() {+ use disktree_core::tree::Metric;+ let temp = tempfile::TempDir::new().expect("tempdir");+ let root = temp.path().join("a folder");+ std::fs::create_dir(&root).expect("mkdir");+ let root = dunce::canonicalize(&root).expect("canonical root");+ let changed = ScanOptions {+ apparent_size: true,+ follow_links: true,+ include_hidden: false,+ one_filesystem: false,+ metric: Metric::Files,+ ..ScanOptions::default()+ };+ for (options, depth) in [(changed, 5), (ScanOptions::default(), 1)] {+ let args = crate::state::restart_args(&options, depth, &root);+ let parsed = crate::parse_args(args.into_iter()).expect("parses");+ assert_eq!(parsed.root, root);+ assert_eq!(parsed.depth, depth);+ let got = &parsed.options;+ assert_eq!(+ (+ got.apparent_size,+ got.follow_links,+ got.include_hidden,+ got.one_filesystem,+ got.metric,+ ),+ (+ options.apparent_size,+ options.follow_links,+ options.include_hidden,+ options.one_filesystem,+ options.metric,+ )+ );+ }+}diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rsindex 8f75253..36ad7d8 100644--- a/crates/disktree-app/src/views.rs+++ b/crates/disktree-app/src/views.rs@@ -1003,6 +1003,7 @@ fn side_panel().children(notice_line(app, theme, cx)).children(privacy_line(app, theme, cx))+ .children(administrator_line(app, theme, cx)).child(disk_section(app, theme, cx))}@@ -1581,6 +1582,77 @@ fn privacy_line()}+/// The faster, fuller scan an administrator gets on Windows, and the way to+/// it. Only where it would help: on a whole NTFS drive walked without `-l`,+/// which is then read from its file table instead, or once the walk was+/// refused something. Hidden once asked, and while a removal runs, which a+/// restart would cut short.+fn administrator_line(+ app: &Disktree,+ theme: &Theme,+ cx: &Context<'_, Disktree>,+) -> Option<Div> {+ if app.administrator != Some(false) || app.restarting || app.run.is_some() {+ return None;+ }+ let errors = app.progress.errors;+ let message = if errors > 0 {+ let noun = if errors == 1 { "item" } else { "items" };+ // With `-l` the elevated copy walks too: only the reading is gained.+ let faster = if app.options.follow_links {+ ""+ } else {+ ", and a whole drive several times faster"+ };+ format!(+ "Windows kept {} {noun} unreadable. Run as administrator to read \+ them{faster}.",+ widgets::human_count(errors)+ )+ } else if app.file_table && !app.options.follow_links {+ "Run as administrator to read the whole drive from its file table: \+ several times faster than this walk."+ .to_owned()+ } else {+ return None;+ };+ // Marks live only in this process; the new one starts without them.+ let message = if app.marks.is_empty() {+ message+ } else {+ format!("{message} Restarting drops the marks.")+ };+ let color = theme.warning;+ Some(+ div()+ .flex()+ .flex_col()+ .gap(space::SM)+ .px(space::SM)+ .py(space::SM)+ .border_1()+ .border_color(color.opacity(0.5))+ .text_size(text::CAPTION)+ .child(div().text_color(color).child(message))+ .child(+ button(+ "administrator",+ "Restart as Administrator",+ ButtonVariant::Outline,+ cx,+ )+ .tab_stop(false)+ .justify_center()+ .on_click(cx.listener(+ |this, _, window, cx| {+ window.focus(&this.focus, cx);+ this.restart_as_administrator(cx);+ },+ )),+ ),+ )+}+/// Free space on the volume now, and after the marks go.fn disk_section(app: &Disktree,