diff --git a/crates/ui-widgets/src/menu/icon_row.rs b/crates/ui-widgets/src/menu/icon_row.rs index bedb44edf0..80a545194e 100644 --- a/crates/ui-widgets/src/menu/icon_row.rs +++ b/crates/ui-widgets/src/menu/icon_row.rs @@ -1,7 +1,7 @@ //! `MenuIconRow`: one stop in a menu that holds a row of icons. use super::item::{RowInput, close_on_pick}; -use super::level::{MenuLevel, Row}; +use super::level::MenuLevel; use crate::contract::{ Access, Common, Component, Cx, MeasureCx, Name, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Role, SetPosition, Styled as _, }; @@ -90,7 +90,7 @@ impl<'a> MenuIconRow<'a> { } fn register(&self, ctx: &Context, level: &MenuLevel, id: Id, label: &str, enabled: bool) { - level.register(ctx.cumulative_pass_nr(), Row { id, text: label.to_owned(), own: None, enabled: self.runs(enabled) }); + level.register(ctx.cumulative_pass_nr(), id, label, None, self.runs(enabled)); } } diff --git a/crates/ui-widgets/src/menu/item.rs b/crates/ui-widgets/src/menu/item.rs index aa2d26c9dd..fcfeac79a3 100644 --- a/crates/ui-widgets/src/menu/item.rs +++ b/crates/ui-widgets/src/menu/item.rs @@ -13,13 +13,13 @@ use crate::runtime::commands::{CommandRef, FireSource, ResolvedCommand}; use crate::runtime::env::Label; use crate::runtime::frame; use crate::style::{ComponentStyle, Flags, IconLook, StyleCx, SurfaceLook, TextLook, TypeRole}; -use craft_behavior::{ColumnKey, Flow, IconId, Insets, Metrics, NavMove, PartKey, Sense}; +use craft_behavior::{ColumnKey, Flow, IconId, Insets, Metrics, NavMove, PartKey, Proposal, Sense}; use craft_keymap::mnemonic; use craft_theme::{Contrast, MenuTint, Rgba, States}; use egui::{Context, Id, Rect, Response, Vec2, pos2}; use std::borrow::Cow; -use super::level::{MenuLevel, Row}; +use super::level::MenuLevel; /// The part a row's shortcut text shows in, as the face of a `Kbd`. const SHORTCUT: PartKey = PartKey::new("shortcut"); @@ -454,7 +454,7 @@ impl<'a> MenuItem<'a> { } fn register(&self, ctx: &Context, level: &MenuLevel, id: Id, label: &str, enabled: bool) { - level.register(ctx.cumulative_pass_nr(), Row { id, text: label.to_owned(), own: self.mnemonic, enabled }); + level.register(ctx.cumulative_pass_nr(), id, label, self.mnemonic, enabled); } /// The row's mark and icon columns with the gap after each: as wide as the column group of the menu body gives @@ -479,7 +479,14 @@ impl<'a> MenuItem<'a> { let command = cx.command(); let (mark, icon) = self.lead_columns(cx.ui.ctx(), side, cx.gap(), command, level); let sample = self.sample_column(cx.ui.ctx(), line, cx.style.shortcut_gap.max(cx.gap())); - let trail = if self.submenu { side } else { self.keys(command).map_or(0.0, |keys| cx.face(keys).x) }; + let trail = if self.submenu { + side + } else { + self.keys(command).map_or(0.0, |keys| { + let least = cx.proposal == Proposal::Min; + level.shortcut_width(cx.ui.ctx().cumulative_pass_nr(), cx.id, least, || cx.face(keys).x) + }) + }; Columns { mark, icon, sample, trail } } diff --git a/crates/ui-widgets/src/menu/level.rs b/crates/ui-widgets/src/menu/level.rs index 3173e2f532..f4d77007e4 100644 --- a/crates/ui-widgets/src/menu/level.rs +++ b/crates/ui-widgets/src/menu/level.rs @@ -6,7 +6,7 @@ use crate::runtime::env::{AppValues, EnvValue}; use craft_behavior::NavMove; use craft_i18n::Folder; use craft_keymap::mnemonic; -use egui::{Id, Pos2, Rect, pos2}; +use egui::{Id, IdMap, Pos2, Rect, pos2}; use std::sync::{Arc, Mutex, PoisonError}; /// Whether the pointer at `now`, having come from `from`, heads for `submenu`: it lies inside the triangle from @@ -21,12 +21,12 @@ pub fn heads_toward(from: Pos2, now: Pos2, submenu: Rect) -> bool { } /// A row as it registered with its level in one pass. -pub(super) struct Row { - pub(super) id: Id, - pub(super) text: String, +struct Row { + id: Id, + text: String, /// The letter the row asks for in place of the level's pick, shown or not in its text. - pub(super) own: Option, - pub(super) enabled: bool, + own: Option, + enabled: bool, } /// A row's mnemonic as the level assigned it when the user last saw the rows: the letter and its character index @@ -77,21 +77,36 @@ struct LevelState { /// letter in every pass, and assigning them all for each row made opening a long menu or submenu cost many times /// a plain row's frame: the letters are assigned again only when the labels or the folder change. letters: Option, + /// How many rows of `now`, from the first, are known to match the labels `letters` was assigned for. + matched: usize, + /// The shortcut width each row measured in the pass `widths_pass`, at the ideal and at the least proposal. + widths: IdMap<[Option; 2]>, + widths_pass: u64, } impl LevelState { - /// The letter of each row of this pass, in order, assigned once for these labels. - fn letters(&mut self, folder: Folder) -> &[Option<(char, Option)>] { - let same = self.letters.as_ref().is_some_and(|(kept, labels, _)| { - *kept == folder - && labels.len() == self.now.len() - && labels.iter().zip(&self.now).all(|((text, own), row)| *text == row.text && *own == row.own) - }); + /// The letter of each row of this pass, in order, assigned once for these labels. A pass in which no measuring + /// run registered the rows registers them one at a time as each row runs: while the rows so far match the start of + /// the kept labels, the kept letters of the whole level serve, so a row gets the letter it has among all its + /// siblings and not among the rows before it. `whole` asks for letters assigned for exactly the rows of `now`. + fn letters(&mut self, folder: Folder, whole: bool) -> &[Option<(char, Option)>] { + let same = match &self.letters { + Some((kept, labels, _)) if *kept == folder && labels.len() >= self.now.len() && (!whole || labels.len() == self.now.len()) => { + let start = self.matched.min(self.now.len()); + let rest = labels[start..].iter().zip(&self.now[start..]).all(|((text, own), row)| *text == row.text && *own == row.own); + if rest { + self.matched = self.now.len(); + } + rest + } + _ => false, + }; if !same { let labels: Vec<&str> = self.now.iter().map(|row| row.text.as_str()).collect(); let own: Vec> = self.now.iter().map(|row| row.own).collect(); let assigned = mnemonic::assign_with(&labels, &own, &folder); self.letters = Some((folder, self.now.iter().map(|row| (row.text.clone(), row.own)).collect(), assigned)); + self.matched = self.now.len(); } self.letters.as_ref().map_or(&[], |(_, _, assigned)| assigned.as_slice()) } @@ -191,32 +206,71 @@ impl MenuLevel { state.pass = pass; state.now.clear(); } - let letters = if let Some(folder) = state.lettered { state.letters(folder).to_vec() } else { vec![None; state.now.len()] }; + let letters = if let Some(folder) = state.lettered { state.letters(folder, true).to_vec() } else { vec![None; state.now.len()] }; state.shown = state.now.iter().zip(letters).map(|(row, mnemonic)| Assigned { id: row.id, mnemonic, enabled: row.enabled }).collect(); }); } - pub(super) fn register(&self, pass: u64, row: Row) { + /// Registers the row `id` for the pass `pass`. A row registers several times in a pass, in the measuring run and + /// in the real run, each time right after the one before it: the last row registered is looked at first. + pub(super) fn register(&self, pass: u64, id: Id, text: &str, own: Option, enabled: bool) { self.with(|state| { if state.pass != pass { state.pass = pass; state.now.clear(); + state.matched = 0; } - match state.now.iter_mut().find(|known| known.id == row.id) { - Some(known) => *known = row, - None => state.now.push(row), + let at = match state.now.last() { + Some(last) if last.id == id => Some(state.now.len() - 1), + _ => state.now.iter().position(|known| known.id == id), }; + match at { + Some(at) => { + let known = &mut state.now[at]; + if known.text != text || known.own != own { + known.text = text.to_owned(); + known.own = own; + state.matched = state.matched.min(at); + } + known.enabled = enabled; + } + None => state.now.push(Row { id, text: text.to_owned(), own, enabled }), + } }); } pub(super) fn mnemonic_of(&self, id: Id) -> Option<(char, Option)> { self.with(|state| { let folder = state.lettered?; - let at = state.now.iter().position(|row| row.id == id)?; - state.letters(folder).get(at).copied().flatten() + let at = state.now.iter().rposition(|row| row.id == id)?; + state.letters(folder, false).get(at).copied().flatten() }) } + /// The width of the shortcut of row `id` at the least proposal (`least`) or the ideal one, measured by `measure` + /// once in the pass `pass`: a row's measure and parts ask for it several times in a pass. Outside a menu it is + /// measured each time. + pub(super) fn shortcut_width(&self, pass: u64, id: Id, least: bool, measure: impl FnOnce() -> f32) -> f32 { + let Some(state) = &self.state else { return measure() }; + let kept = { + let mut state = state.lock().unwrap_or_else(PoisonError::into_inner); + if state.widths_pass != pass { + state.widths_pass = pass; + state.widths.clear(); + } + state.widths.get(&id).and_then(|widths| widths[usize::from(least)]) + }; + if let Some(width) = kept { + return width; + } + let width = measure(); + let mut state = state.lock().unwrap_or_else(PoisonError::into_inner); + if state.widths_pass == pass { + state.widths.entry(id).or_default()[usize::from(least)] = Some(width); + } + width + } + /// The enabled rows the user last saw with a mnemonic, and the letter of each. pub(crate) fn lettered_rows(&self) -> Vec<(char, Id)> { self.with(|state| state.shown.iter().filter(|row| row.enabled).filter_map(|row| row.mnemonic.map(|(letter, _)| (letter, row.id))).collect()) diff --git a/crates/ui-widgets/tests/it/menu/mod.rs b/crates/ui-widgets/tests/it/menu/mod.rs index fc32c6587e..0a085eb15c 100644 --- a/crates/ui-widgets/tests/it/menu/mod.rs +++ b/crates/ui-widgets/tests/it/menu/mod.rs @@ -26,6 +26,8 @@ pub(crate) mod rows; pub(crate) mod runs_per_row; pub(crate) mod search; +pub(crate) mod steady_pass; + pub(crate) mod submenus; use craft_behavior::IconId; diff --git a/crates/ui-widgets/tests/it/menu/steady_pass.rs b/crates/ui-widgets/tests/it/menu/steady_pass.rs new file mode 100644 index 0000000000..f76801a013 --- /dev/null +++ b/crates/ui-widgets/tests/it/menu/steady_pass.rs @@ -0,0 +1,50 @@ +//! An open menu in a pass with no measuring run, where each row registers with its level as the row runs: the letter +//! each row announces, and how often a row's shortcut is measured. + +use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft_ui::menu::{Menu, MenuItem}; +use craft_ui::testing::{Fixture, last_pass_measure_asks, last_pass_measuring_runs, trial}; + +/// A row takes the letter it has among all its siblings, not among the rows before it: "Save" leaves S to the later +/// "&Select All" and takes A, in every frame the open menu runs. +#[trial] +fn a_row_announces_the_letter_it_has_among_all_its_siblings() { + let mut fixture = Fixture::new(|ui| { + let mut open = true; + let _ = Menu::new("File").open(Bind::bound(&mut open)).id_salt("menu").show(ui, |ui, _| { + MenuItem::new("Save").show(ui); + MenuItem::new("&Select All").show(ui); + }); + }); + fixture.settle(); + for frame in 0..3 { + let key = |fixture: &Fixture, label: &str| { + let row = fixture.by_label(label).expect("the menu shows the row"); + fixture.tree().access_key_of(row.node) + }; + assert!(last_pass_measuring_runs(fixture.ctx()).is_empty(), "frame {frame}: the settled menu runs no measuring run"); + assert_eq!(key(&fixture, "Save"), Some('A'), "frame {frame}: Save leaves S to Select All"); + assert_eq!(key(&fixture, "Select All"), Some('S'), "frame {frame}: Select All keeps its marked letter"); + fixture.frame(vec![]); + } +} + +/// Each row of an open menu measures its shortcut once in a pass, though its measure and parts ask for the width +/// several times. +#[trial] +fn an_open_menu_measures_each_shortcut_once_a_pass() { + const ROWS: u32 = 20; + let mut fixture = Fixture::new(|ui| { + let mut open = true; + let _ = Menu::new("Items").open(Bind::bound(&mut open)).id_salt("menu").show(ui, |ui, _| { + for key in 0..ROWS { + MenuItem::new(format!("Item {key}")).shortcut(format!("Ctrl+{key}")).id_salt(key).show(ui); + } + }); + }); + fixture.settle().idle(2); + let asks = last_pass_measure_asks(fixture.ctx()); + let of = |name: &str| asks.iter().filter(|(ty, _)| ty.ends_with(name)).map(|(_, count)| *count).sum::(); + assert!(of("::MenuItem<'_>") > ROWS, "the rows are asked to measure more than once each: {asks:?}"); + assert_eq!(of("::Kbd"), ROWS, "each row measures its shortcut once: {asks:?}"); +}