diff --git a/crates/disktree-app/src/main.rs b/crates/disktree-app/src/main.rs index 47b00f1..4245889 100644 --- a/crates/disktree-app/src/main.rs +++ b/crates/disktree-app/src/main.rs @@ -16,7 +16,6 @@ mod appearance; mod git; mod marks; mod palette; -mod power; mod state; #[cfg(test)] mod tests; @@ -48,7 +47,6 @@ struct Args { choose_root: bool, options: ScanOptions, depth: u32, - power: Option, } const USAGE: &str = "\ @@ -83,9 +81,7 @@ options: also measure other disks, network shares and pseudo filesystems mounted below PATH (local only; off by default) -d, --depth N how many levels to draw at once (1-6, default 4) - --power-efficiency PRESET - miser, balanced (default), aggressive, drain-my-battery - --scan-threads N fixed scan workers, capped by available CPU count + --scan-threads N fixed scan workers (default: automatic heuristic) --metric files rank by file count instead of bytes -h, --help show this help "; @@ -103,16 +99,7 @@ fn run() -> Result<()> { if extract_scanner()? { return Ok(()); } - let saved = power::settings_path() - .map_or_else( - || Ok(power::PowerEfficiency::default()), - |path| power::load(&path), - ) - .unwrap_or_else(|error| { - 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 args = parse_args(std::env::args_os().skip(1))?; if args.check { let host = args @@ -226,7 +213,7 @@ fn run() -> Result<()> { appearance::follow(window); } cx.new(|cx| { - let mut app = if args.choose_root { + if args.choose_root { Disktree::choose( options, depth, @@ -242,9 +229,7 @@ fn run() -> Result<()> { args.remote_disk, cx, ) - }; - app.power_choice = args.power; - app + } }) }, ) @@ -293,21 +278,9 @@ fn extract_scanner() -> Result { } /// Read the command line, program name already skipped. -#[cfg(test)] fn parse_args(args: impl Iterator) -> Result { - parse_args_with_power(args, power::PowerEfficiency::default()) -} - -fn parse_args_with_power( - args: impl Iterator, - preset: power::PowerEfficiency, -) -> Result { let mut root: Option = None; - let mut options = ScanOptions { - threads: Some(preset.threads(power::cpu_threads())), - ..ScanOptions::default() - }; - let mut power = Some(preset); + let mut options = ScanOptions::default(); let mut depth = 4_u32; let mut disk = false; // `std::env::args` panics on a name that is not Unicode, and a path is @@ -353,16 +326,7 @@ fn parse_args_with_power( "--depth must be 1 to 6" ); } - "--power-efficiency" => { - let value = - text(args.next(), "--power-efficiency needs a preset")?; - let preset = power::PowerEfficiency::parse(&value) - .context("unknown Power Efficiency preset")?; - options.threads = Some(preset.threads(power::cpu_threads())); - power = Some(preset); - } "--scan-threads" => { - power = None; let value = text(args.next(), "--scan-threads needs a number")?; let threads: usize = value .parse() @@ -413,7 +377,6 @@ fn parse_args_with_power( remote_disk: disk, check, choose_root, - power, options, depth, }); @@ -454,7 +417,6 @@ fn parse_args_with_power( choose_root, options, depth: depth.clamp(1, 6), - power, }) } @@ -503,13 +465,12 @@ mod argument_tests { } #[test] - fn worker_budget_defaults_and_override_are_explicit() { + fn worker_budget_defaults_to_heuristic_and_allows_override() { let args = parse_args(arguments(&[])).expect("defaults"); - assert_eq!(args.options.threads, Some(4.min(power::cpu_threads()))); + assert_eq!(args.options.threads, None); let args = parse_args(arguments(&["--scan-threads", "4"])).expect("custom"); assert_eq!(args.options.threads, Some(4)); - assert!(args.power.is_none()); } #[test] @@ -544,7 +505,6 @@ mod argument_tests { assert!(args.check); assert_eq!(args.options.threads, Some(4)); assert_eq!(args.root, PathBuf::from("/only-on-the-remote-machine")); - assert!(args.power.is_none()); for root in ["relative", r"C:\Users", r"\srv"] { assert!( parse_args( @@ -565,35 +525,7 @@ mod argument_tests { .expect("remote volume"); assert!(args.remote_disk); assert!(args.root.as_os_str().is_empty()); - assert!(args.power.is_some()); - } - - #[test] - fn saved_power_is_loaded_before_cli_overrides() { - use power::PowerEfficiency as Power; - let dir = tempfile::tempdir().expect("tempdir"); - let path = dir.path().join("power-efficiency"); - power::save(&path, Power::Miser).expect("save"); - let saved = power::load(&path).expect("load"); - let args = parse_args_with_power(arguments(&[]), saved).expect("saved"); - assert_eq!(args.power, Some(Power::Miser)); - assert_eq!(args.options.threads, Some(2.min(power::cpu_threads()))); - let args = parse_args_with_power( - arguments(&["--power-efficiency", "drain-my-battery"]), - saved, - ) - .expect("override"); - assert_eq!(args.power, Some(Power::DrainMyBattery)); - assert_eq!(args.options.threads, Some(power::cpu_threads())); - let args = - parse_args_with_power(arguments(&["--scan-threads", "8"]), saved) - .expect("override"); - assert!(args.power.is_none()); - assert_eq!(args.options.threads, Some(8)); - assert_eq!(power::load(&path).expect("unchanged"), saved); - assert!( - parse_args(arguments(&["--power-efficiency", "invalid"])).is_err() - ); + assert_eq!(args.options.threads, None); } // APFS rejects these filename bytes; Linux filesystems permit them. diff --git a/crates/disktree-app/src/power.rs b/crates/disktree-app/src/power.rs deleted file mode 100644 index e3cc7f0..0000000 --- a/crates/disktree-app/src/power.rs +++ /dev/null @@ -1,193 +0,0 @@ -//! Saved fixed worker presets. Read before the first scan starts. - -use std::io::{self, Write as _}; -use std::path::{Path, PathBuf}; - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum PowerEfficiency { - Miser, - #[default] - Balanced, - Aggressive, - DrainMyBattery, -} - -impl PowerEfficiency { - pub const ALL: [Self; 4] = [ - Self::Miser, - Self::Balanced, - Self::Aggressive, - Self::DrainMyBattery, - ]; - - pub const fn key(self) -> &'static str { - match self { - Self::Miser => "miser", - Self::Balanced => "balanced", - Self::Aggressive => "aggressive", - Self::DrainMyBattery => "drain-my-battery", - } - } - - pub const fn name(self) -> &'static str { - match self { - Self::Miser => "Miser", - Self::Balanced => "Balanced", - Self::Aggressive => "Aggressive", - Self::DrainMyBattery => "Drain My Battery", - } - } - - pub fn parse(value: &str) -> Option { - Self::ALL.into_iter().find(|preset| preset.key() == value) - } - - pub fn threads(self, cpus: usize) -> usize { - let cpus = cpus.max(1); - match self { - Self::Miser => 2.min(cpus), - Self::Balanced => 4.min(cpus), - Self::Aggressive => 8.min(cpus), - Self::DrainMyBattery => cpus, - } - } - - pub fn label(self, cpus: usize) -> String { - format!("{} ({})", self.name(), workers(self.threads(cpus))) - } - - /// A preset that would run no more workers than the one below it, on a - /// machine with this many CPUs, is a duplicate there and is not offered. - pub fn available(self, cpus: usize) -> bool { - // Declared in `ALL` order, so the discriminant is the index. - let index = self as usize; - index == 0 || self.threads(cpus) > Self::ALL[index - 1].threads(cpus) - } - - /// How many of the four gauge bars `threads` workers fill: the presets - /// offered here that run no more than that, so a custom count reads on - /// the same scale. - pub fn signal(threads: usize, cpus: usize) -> usize { - Self::ALL - .into_iter() - .filter(|preset| { - preset.available(cpus) && preset.threads(cpus) <= threads - }) - .count() - .max(1) - } -} - -pub fn workers(count: usize) -> String { - let unit = if count == 1 { "worker" } else { "workers" }; - format!("{count} {unit}") -} - -pub fn cpu_threads() -> usize { - std::thread::available_parallelism().map_or(1, usize::from) -} - -/// Follow each desktop's user configuration location; never write beside -/// the executable or scanned root. No home/config location means session-only. -pub fn settings_path() -> Option { - let home = std::env::home_dir(); - let base = if cfg!(target_os = "macos") { - home.map(|home| home.join("Library/Application Support")) - } else if cfg!(windows) { - std::env::var_os("APPDATA").map(PathBuf::from) - } else { - std::env::var_os("XDG_CONFIG_HOME") - .map(PathBuf::from) - .filter(|path| path.is_absolute()) - .or_else(|| home.map(|home| home.join(".config"))) - }; - base.map(|base| base.join("disktree/power-efficiency")) -} - -pub fn load(path: &Path) -> io::Result { - match std::fs::read_to_string(path) { - Ok(value) => PowerEfficiency::parse(value.trim()).ok_or_else(|| { - io::Error::new(io::ErrorKind::InvalidData, "unknown power preset") - }), - Err(error) if error.kind() == io::ErrorKind::NotFound => { - Ok(PowerEfficiency::default()) - } - Err(error) => Err(error), - } -} - -pub fn save(path: &Path, preset: PowerEfficiency) -> io::Result<()> { - let parent = path.parent().ok_or_else(|| { - io::Error::new(io::ErrorKind::InvalidInput, "no settings directory") - })?; - std::fs::create_dir_all(parent)?; - // Atomic replacement leaves the previous choice intact after a failed - // write, and readers never see a half-written setting. - let mut file = tempfile::NamedTempFile::new_in(parent)?; - writeln!(file, "{}", preset.key())?; - file.persist(path).map_err(|error| error.error)?; - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn presets_are_fixed_and_show_the_effective_cpu_limit() { - for (preset, expected) in - PowerEfficiency::ALL.into_iter().zip([2, 4, 8, 18]) - { - assert_eq!(preset.threads(18), expected); - assert_eq!(preset.threads(1), 1); - } - assert_eq!(PowerEfficiency::Balanced.threads(3), 3); - assert_eq!( - PowerEfficiency::DrainMyBattery.label(18), - "Drain My Battery (18 workers)" - ); - } - - #[test] - fn presets_that_add_no_workers_are_not_offered() { - use PowerEfficiency as P; - let offered = |cpus| { - P::ALL - .into_iter() - .filter(|preset| preset.available(cpus)) - .collect::>() - }; - assert_eq!(offered(18), P::ALL); - assert_eq!(offered(10), P::ALL); - assert_eq!(offered(8), [P::Miser, P::Balanced, P::Aggressive]); - assert_eq!(offered(6), [P::Miser, P::Balanced, P::Aggressive]); - assert_eq!(offered(4), [P::Miser, P::Balanced]); - assert_eq!(offered(3), [P::Miser, P::Balanced]); - assert_eq!(offered(2), [P::Miser]); - assert_eq!(offered(1), [P::Miser]); - // The gauge counts what is offered, so a small machine running - // everything it has reads as full as the menu allows. - assert_eq!(P::signal(4, 18), 2); - assert_eq!(P::signal(18, 18), 4); - assert_eq!(P::signal(4, 4), 2); - assert_eq!(P::signal(1, 18), 1); - assert_eq!(P::signal(12, 18), 3); - } - - #[test] - fn saved_choice_survives_replacement_and_bad_data_is_reported() { - let dir = tempfile::tempdir().expect("tempdir"); - let path = dir.path().join("config/power-efficiency"); - assert_eq!(load(&path).expect("missing"), PowerEfficiency::Balanced); - for preset in PowerEfficiency::ALL { - save(&path, preset).expect("save"); - assert_eq!(load(&path).expect("load"), preset); - } - std::fs::write(&path, "not-a-preset").expect("corrupt"); - assert_eq!( - load(&path).expect_err("invalid").kind(), - io::ErrorKind::InvalidData - ); - assert!(save(dir.path(), PowerEfficiency::Miser).is_err()); - } -} diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index e7c8d62..b2a3a4b 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -903,15 +903,6 @@ pub struct Disktree { pub remote_identity: Option, pub home: Option, pub options: ScanOptions, - pub power_choice: Option, - pub power_settings_path: Option, - /// The Power Efficiency menu, when open: the row the arrow keys are on, - /// as an index into [`crate::power::PowerEfficiency::ALL`]. - pub power_menu: Option, - /// The pointer is on the menu's button. A press there is the button's - /// to toggle, not a press outside the menu that closes it first. - pub power_hover: bool, - pub cpu_threads: usize, scanner: Scanner, pub arena: Option>, pub freshness: Option, @@ -1097,11 +1088,6 @@ impl Disktree { remote_identity: None, home, options, - power_choice: None, - power_settings_path: crate::power::settings_path(), - power_menu: None, - power_hover: false, - cpu_threads: crate::power::cpu_threads(), scanner, arena: None, freshness: None, @@ -1820,108 +1806,6 @@ impl Disktree { cx.notify(); } - /// Changing resource policy leaves the current scan and result intact; - /// rescan, navigation to a new root and restart use the new fixed budget. - pub fn set_power_efficiency( - &mut self, - preset: crate::power::PowerEfficiency, - cx: &mut Context<'_, Self>, - ) { - self.power_menu = None; - // Not offered here: it would run the same workers as the preset - // below it, under a name that promises more. - if !preset.available(self.cpu_threads) { - cx.notify(); - return; - } - self.options.threads = Some(preset.threads(self.cpu_threads)); - self.power_choice = Some(preset); - let label = preset.label(self.cpu_threads); - self.notice = Some(match self.power_settings_path.as_deref() { - Some(path) => match crate::power::save(path, preset) { - Ok(()) => ( - format!("{label} from the next scan; r rescans now"), - Status::Success, - ), - Err(error) => ( - format!( - "{label} from the next scan, but it could not be \ - saved: {error}" - ), - Status::Warning, - ), - }, - None => ( - format!( - "{label} from the next scan; no settings directory to \ - save it in" - ), - Status::Warning, - ), - }); - cx.notify(); - } - - /// Open the Power Efficiency menu on the current preset, or close it. - pub fn toggle_power_menu(&mut self, cx: &mut Context<'_, Self>) { - use crate::power::PowerEfficiency; - self.power_menu = if self.power_menu.is_some() { - None - } else { - // On the current preset, or the nearest one below it that this - // machine offers: a custom count starts from Balanced. - let current = self.power_choice.unwrap_or_default() as usize; - (0..=current) - .rev() - .find(|&index| { - PowerEfficiency::ALL[index].available(self.cpu_threads) - }) - .or(Some(0)) - }; - cx.notify(); - } - - /// Keys while the Power Efficiency menu is open, as the sibling menu - /// takes them. The arrows step over presets this machine cannot offer. - fn on_power_key(&mut self, key: &str, cx: &mut Context<'_, Self>) -> bool { - use crate::power::PowerEfficiency; - let Some(highlighted) = self.power_menu else { - return false; - }; - let cpus = self.cpu_threads; - let offered: Vec = (0..PowerEfficiency::ALL.len()) - .filter(|&index| PowerEfficiency::ALL[index].available(cpus)) - .collect(); - let step = |forward: bool| { - let next = if forward { - offered.iter().find(|&&index| index > highlighted) - } else { - offered.iter().rev().find(|&&index| index < highlighted) - }; - next.copied().unwrap_or(highlighted) - }; - match key { - "down" | "j" => self.power_menu = Some(step(true)), - "up" | "k" => self.power_menu = Some(step(false)), - "home" => self.power_menu = offered.first().copied(), - "end" => self.power_menu = offered.last().copied(), - "enter" | "space" => { - self.set_power_efficiency( - PowerEfficiency::ALL[highlighted], - cx, - ); - } - "escape" => self.power_menu = None, - _ => { - self.power_menu = None; - cx.notify(); - return false; - } - } - cx.notify(); - true - } - /// Refresh the whole scanned root in the background. Keeping its old tree /// visible also preserves hardlink accounting across the current view and /// the rest of the root; a subtree-only scan could charge a link twice. @@ -4239,9 +4123,6 @@ impl Disktree { if self.crumb_menu.is_some() && self.on_menu_key(key, cx) { return; } - if self.power_menu.is_some() && self.on_power_key(key, cx) { - return; - } if self.show_help { if matches!(key, "escape" | "?" | "/" | "q") { @@ -4756,11 +4637,8 @@ impl Disktree { // ends up, and the drive the offer is about: reopening the folder // still on screen would walk it again. let root = self.widening_target().unwrap_or(&self.root_path); - let mut args = + let args = restart_args(&self.options, self.layout_options.max_depth, root); - if let Some(preset) = self.power_choice { - args.extend(["--power-efficiency".into(), preset.key().into()]); - } // 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 { diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rs index e46d85b..1c542d7 100644 --- a/crates/disktree-app/src/tests.rs +++ b/crates/disktree-app/src/tests.rs @@ -2474,11 +2474,7 @@ fn restart_arguments_parse_back_to_the_same_scan() { threads: Some(8), ..ScanOptions::default() }; - let default_with_threads = ScanOptions { - threads: Some(4.min(crate::power::cpu_threads())), - ..ScanOptions::default() - }; - for (options, depth) in [(changed, 5), (default_with_threads, 1)] { + 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); @@ -2503,126 +2499,3 @@ fn restart_arguments_parse_back_to_the_same_scan() { ); } } - -#[gpui_kit::test] -fn power_efficiency_menu_saves_without_discarding_the_tree( - cx: &mut TestAppContext, -) { - use crate::power::{self, PowerEfficiency as Power}; - use gpui_kit::Modifiers; - - cx.update(gpui_omarchy::init); - let temp = fixture(); - let config = tempfile::tempdir().expect("config"); - let path = config.path().join("power-efficiency"); - let (view, cx) = view_over(temp.path(), cx); - cx.simulate_resize(gpui_kit::size(px(900.), px(600.))); - update(&view, cx, |app, _| { - app.power_settings_path = Some(path.clone()); - // Enough CPUs that every preset is offered, whatever runs the test. - app.cpu_threads = 18; - }); - let epoch = read(&view, cx, |app| app.scan_epoch); - for preset in Power::ALL { - draw(cx); - let button = cx.debug_bounds("power-efficiency").expect("control"); - cx.simulate_click(button.center(), Modifiers::none()); - draw(cx); - let choice = cx.debug_bounds(preset.key()).expect("preset"); - cx.simulate_click(choice.center(), Modifiers::none()); - draw(cx); - assert_eq!(power::load(&path).expect("saved"), preset); - read(&view, cx, |app| { - assert_eq!(app.power_choice, Some(preset)); - assert_eq!( - app.options.threads, - Some(preset.threads(app.cpu_threads)) - ); - assert!(app.power_menu.is_none()); - assert_eq!(app.scan_epoch, epoch); - assert!(app.tree.is_some()); - }); - } - // Persistence failure must not masquerade as a saved preference. - update(&view, cx, |app, cx| { - app.power_settings_path = Some(config.path().to_owned()); - app.set_power_efficiency(Power::Miser, cx); - }); - assert!(read(&view, cx, |app| app.notice.as_ref().is_some_and( - |(message, _)| message.contains("could not be saved") - ))); - update(&view, cx, Disktree::start_scan); - assert_eq!(read(&view, cx, |app| app.scan_epoch), epoch + 1); -} - -#[gpui_kit::test] -fn the_power_menu_offers_only_what_the_cpus_can_tell_apart( - cx: &mut TestAppContext, -) { - use crate::power::PowerEfficiency as Power; - use gpui_kit::Modifiers; - - cx.update(gpui_omarchy::init); - let temp = fixture(); - let config = tempfile::tempdir().expect("config"); - let (view, cx) = view_over(temp.path(), cx); - cx.simulate_resize(gpui_kit::size(px(900.), px(600.))); - update(&view, cx, |app, _| { - app.power_settings_path = Some(config.path().join("power")); - // Aggressive and Drain My Battery would both run four workers. - app.cpu_threads = 4; - app.power_choice = Some(Power::Balanced); - }); - draw(cx); - let toggle = cx.debug_bounds("power-efficiency").expect("control"); - cx.simulate_mouse_move(toggle.center(), None, Modifiers::none()); - cx.simulate_click(toggle.center(), Modifiers::none()); - draw(cx); - assert_eq!(read(&view, cx, |app| app.power_menu), Some(1)); - - // The pointer takes the highlight, and the check stays on what is saved. - let miser = cx.debug_bounds(Power::Miser.key()).expect("row"); - cx.simulate_mouse_move(miser.center(), None, Modifiers::none()); - draw(cx); - assert_eq!(read(&view, cx, |app| app.power_menu), Some(0)); - let balanced = cx.debug_bounds(Power::Balanced.key()).expect("row"); - let check = cx.debug_bounds("power-check").expect("check"); - assert!(balanced.contains(&check.center()), "check on {check:?}"); - - // A disabled row ignores the click and leaves the menu to be dismissed. - let drain = cx.debug_bounds(Power::DrainMyBattery.key()).expect("row"); - cx.simulate_click(drain.center(), Modifiers::none()); - draw(cx); - read(&view, cx, |app| { - assert_eq!(app.power_choice, Some(Power::Balanced)); - assert!(app.notice.is_none()); - }); - - // The arrows step over what is not offered, and Enter chooses. - update(&view, cx, |app, cx| { - app.power_menu = None; - app.toggle_power_menu(cx); - }); - press(cx, "down"); - assert_eq!(read(&view, cx, |app| app.power_menu), Some(1)); - press(cx, "up"); - assert_eq!(read(&view, cx, |app| app.power_menu), Some(0)); - press(cx, "enter"); - read(&view, cx, |app| { - assert_eq!(app.power_choice, Some(Power::Miser)); - assert_eq!(app.options.threads, Some(2)); - assert!(app.power_menu.is_none()); - }); - - // The button closes what it opened, rather than the press outside the - // menu closing it only for the click to open it again. - draw(cx); - let toggle = cx.debug_bounds("power-efficiency").expect("control"); - cx.simulate_mouse_move(toggle.center(), None, Modifiers::none()); - cx.simulate_click(toggle.center(), Modifiers::none()); - draw(cx); - assert!(read(&view, cx, |app| app.power_menu.is_some())); - cx.simulate_click(toggle.center(), Modifiers::none()); - draw(cx); - assert!(read(&view, cx, |app| app.power_menu.is_none())); -} diff --git a/crates/disktree-app/src/ui.rs b/crates/disktree-app/src/ui.rs index d8b76e8..cf81634 100644 --- a/crates/disktree-app/src/ui.rs +++ b/crates/disktree-app/src/ui.rs @@ -71,12 +71,6 @@ pub mod size { /// A crumb's sibling menu. pub const SIBLING_MENU: Rems = Rems(24.0); pub const SIBLING_MENU_HEIGHT: Rems = Rems(32.0); - /// The Power Efficiency menu: narrower than a sibling menu, since its - /// names are four known words, but wide enough for Drain My Battery - /// beside the check, bar and count. - pub const POWER_MENU: Rems = Rems(22.0); - /// One bar of the Power Efficiency gauge. - pub const SIGNAL_BAR: Rems = Rems(0.1875); /// A list row's share bar. pub const ROW_BAR: Rems = Rems(5.5); /// A legend or identity swatch. diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index f8ebc29..a945507 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -1482,206 +1482,6 @@ fn view_settings( .child(hidden) .child(apparent) .child(depth_control) - .child(power_efficiency(app, cx)) -} - -/// What the tooltip says the choice will do, where the gauge alone cannot. -/// Measured on an 18-core Apple silicon Mac scanning its whole Data volume -/// (medians of three): 4 workers 209 s and 433 CPU-seconds, 8 workers 133 s -/// and 580, 18 workers 137 s and 1,314. Elsewhere the shape is expected, not -/// measured, so it gives no numbers. -const POWER_TRADEOFF: &str = if cfg!(target_os = "macos") { - "Up to about 8 workers a scan finishes sooner: a whole drive took a \ - third less time with 8 than with Balanced. Past that it is no faster, \ - but uses over twice the CPU and runs the fans at full speed." -} else { - "More workers finish a scan sooner only up to a point. Past it they \ - use more CPU for no gain, and can run the fans at full speed." -}; - -/// How hard a scan may work, as a signal gauge framed like Depth; the -/// presets are in a menu built like the sibling menu, so the control costs -/// the bar no more than one button. Like the other settings, focus returns -/// to the treemap. -fn power_efficiency(app: &Disktree, cx: &Context<'_, Disktree>) -> Div { - use crate::power::{self, PowerEfficiency}; - - let theme = cx.omarchy().clone(); - let cpus = app.cpu_threads; - let threads = app.options.threads.unwrap_or(cpus).min(cpus); - let name = app.power_choice.map_or("Custom", PowerEfficiency::name); - let open = app.power_menu.is_some(); - let trigger = div() - .id("power-efficiency") - .debug_selector(|| "power-efficiency".into()) - .flex() - .flex_row() - .items_center() - .border_1() - .border_color(theme.control_border()) - .on_hover(cx.listener(|this, hovered: &bool, _, cx| { - this.power_hover = *hovered; - cx.notify(); - })) - .child( - button("power-toggle", "", ButtonVariant::Secondary, cx) - .accessibility_label(format!("Power Efficiency: {name}")) - .selected(open) - .tab_stop(false) - .child(widgets::signal( - PowerEfficiency::signal(threads, cpus), - cx, - )) - .child( - div() - .text_size(text::CAPTION) - .text_color(theme.secondary) - .child("\u{25be}"), - ) - .on_click(cx.listener(|this, _, window, cx| { - this.toggle_power_menu(cx); - window.focus(&this.focus, cx); - })), - ); - // An open menu says it all; the tooltip would only cover it. - let trigger = if open { - trigger - } else { - with_tooltip( - trigger, - format!( - "Power Efficiency: {name} \u{00b7} {} of {cpus} CPUs\n\ - {POWER_TRADEOFF}\nUsed from the next scan, and remembered.", - power::workers(threads) - ), - ) - }; - let mut control = div().relative().child(trigger); - let Some(highlighted) = app.power_menu else { - return control; - }; - - let mut menu = div() - .id("power-menu") - .debug_selector(|| "power-menu".into()) - .occlude() - .flex() - .flex_col() - .w(size::POWER_MENU) - .p(space::XS) - .bg(theme.surface) - .border_1() - .border_color(theme.control_border()) - .shadow_lg() - .on_mouse_down_out(cx.listener(|this, _, _, cx| { - if !this.power_hover { - this.power_menu = None; - cx.notify(); - } - })) - .child( - div() - .flex() - .flex_row() - .justify_between() - .px(space::SM) - .py(space::XS) - .text_size(text::CAPTION) - .text_color(theme.secondary.opacity(0.8)) - .child("Scan workers") - .child(format!("{cpus} CPUs")), - ); - for (index, preset) in PowerEfficiency::ALL.into_iter().enumerate() { - let offered = preset.available(cpus); - let current = app.power_choice == Some(preset); - let count = preset.threads(cpus); - let row = div() - .id(preset.key()) - .debug_selector(move || preset.key().into()) - .flex() - .flex_row() - .items_center() - .gap(space::MD) - .px(space::SM) - .py(space::XS) - .when(index == highlighted && offered, |this| { - this.bg(theme.hover_fill()) - }) - // The saved preset keeps its check wherever the highlight goes; - // bold alone read as losing to the fill under the pointer. - .child(div().flex_shrink_0().w(icon::SM).when(current, |this| { - this.debug_selector(|| "power-check".into()).child( - gpui_omarchy::icon(gpui_omarchy::IconName::Check) - .size(icon::SM) - .text_color(theme.accent), - ) - })) - .child( - div() - .flex_1() - .min_w_0() - .text_size(text::BODY) - .text_color(theme.bright) - .when(current, |this| this.font_weight(FontWeight::BOLD)) - .whitespace_nowrap() - .overflow_hidden() - .text_ellipsis() - .child(preset.name()), - ) - .child(div().flex_shrink_0().w(size::ROW_BAR).child(widgets::bar( - count as f32 / cpus as f32, - theme.accent, - cx, - ))) - .child( - div() - .flex_shrink_0() - .w(size::SIZE_LANE) - .flex() - .justify_end() - .text_size(text::BODY) - .text_color(theme.secondary) - .child(power::workers(count)), - ); - // A preset this machine cannot tell apart from the one below it is - // shown, so the scale stays the same everywhere, but not offered. - let row = if offered { - // The pointer moves the one highlight the arrows move, so two - // filled rows never compete with the check. - row.on_hover(cx.listener(move |this, hovered: &bool, _, cx| { - if *hovered && this.power_menu.is_some() { - this.power_menu = Some(index); - cx.notify(); - } - })) - .on_click(cx.listener(move |this, _, window, cx| { - this.set_power_efficiency(preset, cx); - window.focus(&this.focus, cx); - })) - } else { - let below = PowerEfficiency::ALL[index - 1].name(); - with_tooltip( - row.opacity(0.45), - format!("Same as {below} with {cpus} CPUs"), - ) - }; - menu = menu.child(row); - } - control = control.child( - div().absolute().top_full().right_0().child( - deferred( - // Hung from the gauge's right edge: the bar's last control, - // so the menu opens inward rather than off the window. - anchored() - .anchor(gpui_kit::Anchor::TopRight) - .snap_to_window_with_margin(px(8.)) - .offset(gpui_kit::point(px(0.), px(4.))) - .child(menu), - ) - .with_priority(2), - ), - ); - control } // ── trail and legend ──────────────────────────────────────────────────── diff --git a/crates/disktree-app/src/widgets.rs b/crates/disktree-app/src/widgets.rs index a187680..c95bf20 100644 --- a/crates/disktree-app/src/widgets.rs +++ b/crates/disktree-app/src/widgets.rs @@ -417,37 +417,6 @@ pub fn bar(fraction: f32, color: Hsla, cx: &App) -> Div { ) } -/// Four rising bars with `filled` of them lit, as a signal meter reads: -/// how hard a scan is allowed to work, without a word in the bar. -pub fn signal(filled: usize, cx: &App) -> Div { - let theme = cx.omarchy(); - let mut bars = div() - .flex() - .flex_row() - .items_end() - .gap(space::XXS) - .h(crate::ui::icon::SM); - for step in 1..=SIGNAL_STEPS { - // Heights step by quarters of the icon slot, so the tallest bar is - // the height of the text beside it. - let height = crate::ui::icon::SM.0 * step as f32 / SIGNAL_STEPS as f32; - bars = bars.child( - div() - .w(crate::ui::size::SIGNAL_BAR) - .h(gpui_kit::Rems(height)) - .bg(if step <= filled { - theme.bright - } else { - theme.control_border() - }), - ); - } - bars -} - -/// One bar per Power Efficiency preset. -const SIGNAL_STEPS: usize = crate::power::PowerEfficiency::ALL.len(); - /// A square of colour, for a legend or an identity. pub fn swatch(color: Hsla) -> Div { div() diff --git a/crates/disktree-cli/src/main.rs b/crates/disktree-cli/src/main.rs index becc711..3363165 100644 --- a/crates/disktree-cli/src/main.rs +++ b/crates/disktree-cli/src/main.rs @@ -255,9 +255,7 @@ fn print_plain_summary( }; let now = disktree_scanner::unix_now(); let freshness_label = match &snapshot.freshness { - Freshness::Fresh { newest_at, .. } => { - format!("cached {}", human_age(now.saturating_sub(*newest_at))) - } + Freshness::Fresh { .. } => "fresh".to_owned(), Freshness::Stale { newest_at, .. } => { format!("stale {}", human_age(now.saturating_sub(*newest_at))) } diff --git a/crates/disktree-cli/src/tui.rs b/crates/disktree-cli/src/tui.rs index 42c4ce2..fbacf6a 100644 --- a/crates/disktree-cli/src/tui.rs +++ b/crates/disktree-cli/src/tui.rs @@ -539,13 +539,9 @@ impl App { } } else { match &self.freshness { - Some(Freshness::Fresh { newest_at, .. }) => ( - format!( - "CACHED · {}", - human_age(now.saturating_sub(*newest_at)) - ), - Color::Green, - ), + Some(Freshness::Fresh { .. }) => { + ("FRESH".to_owned(), Color::Green) + } Some(Freshness::Live { .. }) => { ("LIVE".to_owned(), Color::Green) } @@ -692,13 +688,9 @@ impl App { ("updating…".to_owned(), Color::Cyan) } else { match node.status() { - SubtreeStatus::Fresh { scanned_at } => ( - format!( - "fresh {}", - human_age(now.saturating_sub(scanned_at)) - ), - Color::Green, - ), + SubtreeStatus::Fresh { .. } => { + ("fresh".to_owned(), Color::Green) + } SubtreeStatus::Stale { scanned_at } => ( format!( "stale {}", diff --git a/crates/disktree-scanner/src/walk.rs b/crates/disktree-scanner/src/walk.rs index 4cf2434..d00f476 100644 --- a/crates/disktree-scanner/src/walk.rs +++ b/crates/disktree-scanner/src/walk.rs @@ -293,6 +293,25 @@ pub struct WalkOutcome { pub cancelled: bool, } +/// Choose a balanced worker count from the host's logical CPU count when the +/// caller does not pass an explicit `--scan-threads` override. +/// +/// Metadata walks scale strongly up to ~6–8 workers; past 8, VFS lock +/// contention adds CPU heat and fan noise without meaningful wall-time gains. +#[must_use] +pub const fn default_worker_threads(cpus: usize) -> usize { + if cpus <= 1 { + 1 + } else if cpus <= 4 { + cpus + } else if cpus <= 8 { + 4 + } else { + let half = cpus / 2; + if half > 8 { 8 } else { half } + } +} + /// Walk `root` in parallel, grafting any fresh subtrees returned by /// `config.skip_oracle`, and returning the aggregated, sorted [`TreeArena`]. pub fn walk_parallel( @@ -394,15 +413,16 @@ pub fn walk_parallel( Ok(()) }; - if let Some(threads) = config.options.threads { - let pool = rayon::ThreadPoolBuilder::new() - .num_threads(threads.max(1)) - .build() - .map_err(io::Error::other)?; - pool.install(run_walk)?; - } else { - run_walk()?; - } + let cpus = std::thread::available_parallelism().map_or(1, usize::from); + let threads = config + .options + .threads + .map_or_else(|| default_worker_threads(cpus), |n| n.clamp(1, cpus)); + let pool = rayon::ThreadPoolBuilder::new() + .num_threads(threads) + .build() + .map_err(io::Error::other)?; + pool.install(run_walk)?; let scanned_at = unix_now(); let cancelled = ctx.cancel.load(Ordering::Relaxed); @@ -1397,6 +1417,17 @@ mod tests { } } + #[test] + fn default_worker_heuristic_scales_and_caps_quietly() { + assert_eq!(default_worker_threads(0), 1); + assert_eq!(default_worker_threads(1), 1); + assert_eq!(default_worker_threads(4), 4); + assert_eq!(default_worker_threads(8), 4); + assert_eq!(default_worker_threads(12), 6); + assert_eq!(default_worker_threads(18), 8); + assert_eq!(default_worker_threads(64), 8); + } + #[test] fn gate_machine_nested_holds_and_terminal_cancel() { use gate_machine::{Effect, Event, State, step};