diff --git a/crates/disktree-app/src/power.rs b/crates/disktree-app/src/power.rs index 6f6428c..c4a05bd 100644 --- a/crates/disktree-app/src/power.rs +++ b/crates/disktree-app/src/power.rs @@ -55,9 +55,28 @@ impl PowerEfficiency { } pub fn label(self, cpus: usize) -> String { - let count = self.threads(cpus); - let unit = if count == 1 { "thread" } else { "threads" }; - format!("{} ({count} {unit})", self.name()) + 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 policy(self, cpus: usize) -> ScanThreads { @@ -70,6 +89,11 @@ impl PowerEfficiency { } } +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) } @@ -134,10 +158,36 @@ mod tests { assert_eq!(PowerEfficiency::Balanced.threads(3), 3); assert_eq!( PowerEfficiency::DrainMyBattery.label(18), - "Drain My Battery (18 threads)" + "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"); diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index 83d091a..30f7d35 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -329,7 +329,12 @@ pub struct Disktree { pub options: ScanOptions, pub power_choice: Option, pub power_settings_path: Option, - pub power_menu_open: bool, + /// 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, pub tree: Option>, pub scan: Option, @@ -468,7 +473,8 @@ impl Disktree { options, power_choice: None, power_settings_path: crate::power::settings_path(), - power_menu_open: false, + power_menu: None, + power_hover: false, cpu_threads: crate::power::cpu_threads(), tree: None, scan: None, @@ -814,28 +820,101 @@ impl Disktree { 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 = preset.policy(self.cpu_threads); self.power_choice = Some(preset); - self.power_menu_open = false; + 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!("{} saved; applies to the next scan", preset.label(self.cpu_threads)), + format!("{label} from the next scan; r rescans now"), Status::Success, ), Err(error) => ( - format!("Applies to the next scan, but could not save Power Efficiency: {error}"), + format!( + "{label} from the next scan, but it could not be \ + saved: {error}" + ), Status::Warning, ), }, None => ( - "Power Efficiency applies to the next scan; no settings directory is available".into(), + 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 + } + /// Start a fresh scan, abandoning any walk still in progress. pub fn start_scan(&mut self, cx: &mut Context<'_, Self>) { if let Some(scan) = &self.scan { @@ -2486,6 +2565,9 @@ 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") { diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rs index 168e9ae..ca17a81 100644 --- a/crates/disktree-app/src/tests.rs +++ b/crates/disktree-app/src/tests.rs @@ -1674,6 +1674,8 @@ fn power_efficiency_menu_saves_without_discarding_the_tree( 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 { @@ -1692,7 +1694,7 @@ fn power_efficiency_menu_saves_without_discarding_the_tree( preset.threads(app.cpu_threads) ); assert!(!app.options.threads.adaptive); - assert!(!app.power_menu_open); + assert!(app.power_menu.is_none()); assert_eq!(app.scan_epoch, epoch); assert!(app.tree.is_some()); }); @@ -1702,10 +1704,72 @@ fn power_efficiency_menu_saves_without_discarding_the_tree( 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 save")))); + 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)); + + // 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.max_threads, 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 c79ace0..5b6763c 100644 --- a/crates/disktree-app/src/ui.rs +++ b/crates/disktree-app/src/ui.rs @@ -72,6 +72,11 @@ 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. + pub const POWER_MENU: Rems = Rems(20.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 57d842d..0e85f4d 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -476,10 +476,13 @@ fn trail(app: &Disktree, theme: &Theme, cx: &Context<'_, Disktree>) -> Div { } else { 0..0 }; + // Short of room, the trail gives up its start, never the crumb you are + // in and its menu: content packed to the end overflows to the left. let mut row = div() .flex() .flex_row() .items_center() + .justify_end() .gap(space::XXS) .min_w_0() .overflow_hidden(); @@ -969,113 +972,196 @@ fn view_settings( div() .flex() - .flex_col() - .items_end() - .gap(space::XS) + .flex_row() + .items_center() + .gap(space::SM) .flex_shrink_0() - .child( - div() - .flex() - .items_center() - .gap(space::SM) - .child(history) - .child(mode) - .child(hidden) - .child(apparent) - .child(depth_control), - ) + .child(history) + .child(mode) + .child(hidden) + .child(apparent) + .child(depth_control) .child(power_efficiency(app, cx)) } -/// Keep the four labeled choices in a popup so even the smallest window can -/// show the controls. Like the other settings, focus returns to the treemap. +/// What the tooltip says the choice will do, where the gauge alone cannot. +/// The numbers were measured on Apple silicon; elsewhere the fans are only +/// a likely cost, not a measured one. +const POWER_TRADEOFF: &str = if cfg!(target_os = "macos") { + "Above Balanced, a scan finishes only about 20% sooner but uses about \ + twice the CPU, and runs the fans at full speed." +} else { + "Above Balanced, a scan finishes only about 20% sooner but uses about \ + twice the CPU, 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 { - let label = app.power_choice.map_or_else( - || "Custom".to_owned(), - |preset| preset.label(app.cpu_threads), - ); - let mut control = div().relative().child( - div() - .id("power-efficiency") - .debug_selector(|| "power-efficiency".into()) - .child( - button( - "power-toggle", - format!("Power Efficiency: {label}"), - ButtonVariant::Secondary, - cx, - ) + use crate::power::{self, PowerEfficiency}; + + let theme = cx.omarchy().clone(); + let cpus = app.cpu_threads; + let threads = app.options.threads.max_threads.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) - .on_click(cx.listener( - |this, _, window, cx| { - this.power_menu_open = !this.power_menu_open; - window.focus(&this.focus, cx); - cx.notify(); - }, - )), - ), - ); - if app.power_menu_open { - let theme = cx.omarchy().clone(); - let mut menu = div() - .id("power-menu") - .debug_selector(|| "power-menu".into()) - .occlude() - .flex() - .flex_col() - .w(size::SIBLING_MENU) - .p(space::SM) - .gap(space::XS) - .bg(theme.surface) - .border_1() - .border_color(theme.control_border()) - .shadow_lg() - .on_mouse_down_out(cx.listener(|this, _, _, cx| { - this.power_menu_open = false; - cx.notify(); - })); - for preset in crate::power::PowerEfficiency::ALL { - let variant = if app.power_choice == Some(preset) { - ButtonVariant::Primary - } else { - ButtonVariant::Secondary - }; - menu = menu.child( - div() - .id(preset.key()) - .debug_selector(move || preset.key().into()) - .child( - button( - preset.key(), - preset.label(app.cpu_threads), - variant, - cx, - ) - .w_full() - .tab_stop(false) - .on_click(cx.listener( - move |this, _, window, cx| { - this.set_power_efficiency(preset, cx); - window.focus(&this.focus, cx); - }, - )), - ), - ); - } - menu = menu.child(div().text_size(text::CAPTION) - .text_color(theme.secondary) - .child("Saved for the next scan. Limits scan workers, not whole-app CPU or battery use.")); - control = control.child( - div().absolute().top_full().right_0().child( - deferred( - anchored() - .snap_to_window_with_margin(px(space::SM.0 * app.rem)) - .child(menu), + .child(widgets::signal( + PowerEfficiency::signal(threads, cpus), + cx, + )) + .child( + div() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child("\u{25be}"), ) - .with_priority(2), - ), + .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()) + }) + .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 { + row.hover(|style| style.bg(theme.hover_fill())).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 } diff --git a/crates/disktree-app/src/widgets.rs b/crates/disktree-app/src/widgets.rs index 3ba4137..905c04f 100644 --- a/crates/disktree-app/src/widgets.rs +++ b/crates/disktree-app/src/widgets.rs @@ -423,6 +423,37 @@ 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()