Menus: collect the Help search's commands only while Help shows; shown chords without allocating

Two costs every frame paid, found in a profile of PhotoCraft on the
framework (storytold/photocraft#15493):

- `MenuBarUi::show` collected the Help search's entries (every row of
  every menu, with English labels) on every pass whenever the bar had a
  Help menu, open or not. `MenuHelp::built` takes a builder the bar runs
  only in a pass that shows the Help menu; `MenuHelp::new` keeps taking a
  ready list.
- `Keymap::shown_chord`, which every menu row, tooltip and button asks
  each pass, built the command's key string for every `find` and ran a
  full `lookup` per binding, cloning the winning commands only to look
  their keys up again. `find` now looks up a command without parameters
  by its id, and `press_runs` decides on catalog positions. Answers are
  unchanged; a new test covers tools sharing a chord (a cycle within a
  group, the first of two groups), which no test covered.

Measured in PhotoCraft (Windows 11, idle machine, three runs, together
with PhotoCraft's own storytold/photocraft#15496): UI pass with a pointer
over the canvas 8.7-11.3 ms -> 4.9-5.0 ms, during a menu hover
9.2-10.2 ms -> 6.7-7.1 ms.

Part of storytold/photocraft#15493.
This commit is contained in:
David Mann
2026-11-17 21:04:10 +01:00
parent e602156696
commit c78c49e2f7
5 changed files with 164 additions and 17 deletions
+44 -6
View File
@@ -423,15 +423,47 @@ impl Keymap {
ScopeKind::Panel => Active::panel(name[0]),
ScopeKind::Context => Active { panel: None, contexts: &name, typing: false },
};
match self.lookup(&trigger.chord, false, &active) {
Lookup::None => false,
Lookup::Run(c) => self.find(&c) == Some(i),
Lookup::Cycle(cycle) => cycle.iter().any(|c| self.find(c) == Some(i)),
}
self.press_runs(&trigger.chord, &active, i)
};
single().filter(|(_, scope)| scope == home).chain(single().filter(|(_, scope)| scope != home)).find(runs).map(|(trigger, _)| trigger.chord)
}
/// Whether a single press of `chord` with `active` focus runs catalog entry `i`, alone or in a cycle: what
/// [`lookup`](Self::lookup) answers, decided on catalog positions without building the answer's commands.
/// [`shown_chord`](Self::shown_chord) asks it for each binding of every command a frame shows.
fn press_runs(&self, chord: &Chord, active: &Active, i: usize) -> bool {
let want = Trigger { chord: chord.effective(self.platform), double: false };
let held = active.typing && !self.typing.fires(&want.chord, self.platform);
let Some(holders) = self.by_trigger.get(&want) else { return false };
// Each command's nearest rank, as `lookup_nested` ranks them: `holders` is in catalog order, so a command's
// bindings are consecutive.
let ranked = || {
let mut out: Vec<(usize, u8)> = Vec::new();
for &(j, k) in holders {
let Some(r) = self.at(j, k).and_then(|(_, s)| self.scopes.rank_nested(s, active, &[])) else { continue };
if held && r != 0 {
continue;
}
match out.last_mut() {
Some((last, best)) if *last == j => *best = (*best).min(r),
_ => out.push((j, r)),
}
}
out
};
let ranks = ranked();
let Some(best) = ranks.iter().map(|(_, r)| *r).min() else { return false };
let mut winners = ranks.iter().filter(|(_, r)| *r == best).map(|(j, _)| *j);
let Some(first) = winners.next() else { return false };
let rest: Vec<usize> = winners.collect();
if rest.is_empty() || !rest.iter().all(|j| self.same_group(first, *j)) {
// One winner, or several of different groups: the first runs.
return first == i;
}
// A cycle of the winners.
first == i || rest.contains(&i)
}
/// The command that holds `chord` for a surface that takes the key whatever has focus (a system menu item): the
/// command a single press runs with no panel focused (a cycle's first), else the first command in catalog order
/// that binds it in a panel or context scope.
@@ -604,7 +636,13 @@ impl Keymap {
}
fn find(&self, command: &CommandRef) -> Option<usize> {
self.index.get(&command.key()).copied()
// A command without parameters is keyed by its id (`CommandRef::key`): look it up without building the key.
// Menu rows, tooltips and buttons ask for their chords on every frame.
match &command.params {
serde_json::Value::Null => self.index.get(command.id.as_str()).copied(),
serde_json::Value::Object(params) if params.is_empty() => self.index.get(command.id.as_str()).copied(),
_ => self.index.get(&command.key()).copied(),
}
}
fn resolve_key(&self, key: &str) -> Option<usize> {
+24
View File
@@ -195,3 +195,27 @@ fn the_alt_variant_follows_the_commands_key_and_yields_to_a_bound_alt_chord() {
let km = Keymap::new(vec![app("layer.new.layer", &["F2"])], Scopes::new(), Platform::Mac);
assert!(hit(&km, &alt(Key::F2, false, false)).is_none(), "a command that did not opt in has no Alt variant");
}
/// Tools that share a chord: within one group a press cycles through them, so each shows the chord; across groups the
/// first in catalog order runs, so only it shows the chord. `shown_chord` decides on catalog positions (#15493) and
/// must answer as the lookup does.
#[test]
fn tools_sharing_a_chord_show_it_as_the_lookup_runs_them() {
use craft_keymap::CommandKind;
let tool = |id: &str, group: &str, keys: &[&str]| app(id, keys).with_kind(CommandKind::Tool { group: Some(group.into()) });
let catalog = vec![
tool("tool.marquee", "select", &["M"]),
tool("tool.ellipse", "select", &["M"]),
tool("tool.move", "move", &["V"]),
tool("tool.artboard", "board", &["V"]),
];
let km = Keymap::new(catalog, scopes(), Platform::Mac);
assert_eq!(press(&km, "M", &Active::NONE), Lookup::Cycle(vec![cmd("tool.marquee"), cmd("tool.ellipse")]));
assert_eq!(km.shown_chord(&cmd("tool.marquee")), Some(chord("M")), "a cycle runs its first tool");
assert_eq!(km.shown_chord(&cmd("tool.ellipse")), Some(chord("M")), "and its other tools");
assert_eq!(press(&km, "V", &Active::NONE), run("tool.move"));
assert_eq!(km.shown_chord(&cmd("tool.move")), Some(chord("V")), "of two groups the first runs");
assert_eq!(km.shown_chord(&cmd("tool.artboard")), None, "the other group's tool never runs on V");
// A command with empty parameters is the same command.
assert_eq!(km.shown_chord(&CommandRef::with_params("tool.move", serde_json::json!({}))), Some(chord("V")));
}
+4 -2
View File
@@ -134,10 +134,12 @@ impl<'a> MenuBarUi<'a> {
let titles: Vec<MenuTitle<'_>> =
self.bar.menus.iter().zip(labels).map(|(menu, label)| MenuTitle::new(label, move |ui| shared.show(ui, &menu.children))).collect();
let help = self.help_search.then(|| self.bar.menus.iter().position(|menu| menu.role == MenuRole::Help)).flatten();
let entries = if help.is_some() { entries_of(self.bar, self.english) } else { Vec::new() };
// Collecting the search's commands walks every row of every menu: the bar does it only while Help is open.
let (bar_model, english) = (self.bar, self.english);
let entries = move || entries_of(bar_model, english);
let mut bar = Bar::new(env.words::<BarWords>().label.clone(), titles).keyboard(self.keyboard.unwrap_or(self.target != Target::Mac));
if let Some(menu) = help {
bar = bar.help(MenuHelp::new(menu, &entries));
bar = bar.help(MenuHelp::built(menu, &entries));
}
MenuBarOutput { titles: bar.show(ui).titles }
}
+45 -9
View File
@@ -173,17 +173,50 @@ impl<'a> MenuTitle<'a> {
}
/// The Help menu's search: the index of the menu that starts with the field, and the commands it searches.
#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy)]
#[non_exhaustive]
pub struct MenuHelp<'a> {
menu: usize,
entries: &'a [HelpEntry],
entries: HelpEntries<'a>,
}
/// Where the help search's commands come from: a list the caller built, or a builder the bar runs only while the
/// Help menu is open.
#[derive(Clone, Copy)]
enum HelpEntries<'a> {
Listed(&'a [HelpEntry]),
Built(&'a dyn Fn() -> Vec<HelpEntry>),
}
impl std::fmt::Debug for MenuHelp<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let entries = match self.entries {
HelpEntries::Listed(entries) => format!("{} listed", entries.len()),
HelpEntries::Built(_) => "built when opened".to_string(),
};
f.debug_struct("MenuHelp").field("menu", &self.menu).field("entries", &entries).finish()
}
}
impl<'a> MenuHelp<'a> {
/// A search field at the top of the menu `menu` (its position among the titles) over `entries`.
pub fn new(menu: usize, entries: &'a [HelpEntry]) -> Self {
MenuHelp { menu, entries }
MenuHelp { menu, entries: HelpEntries::Listed(entries) }
}
/// A search field at the top of the menu `menu` over the commands `entries` builds. The bar runs it only in a pass
/// that shows the Help menu, so an app whose command list is costly to collect (every row of its menus) pays
/// nothing while the menu is closed.
pub fn built(menu: usize, entries: &'a dyn Fn() -> Vec<HelpEntry>) -> Self {
MenuHelp { menu, entries: HelpEntries::Built(entries) }
}
/// The commands, built now for a builder.
fn entries(&self) -> std::borrow::Cow<'a, [HelpEntry]> {
match self.entries {
HelpEntries::Listed(entries) => std::borrow::Cow::Borrowed(entries),
HelpEntries::Built(build) => std::borrow::Cow::Owned(build()),
}
}
}
@@ -524,9 +557,10 @@ impl Component for MenuBar<'_> {
let folder = cx.env.folder();
let texts = self.texts(&cx.env);
let help = self.help;
let help_rows = help
.filter(|help| opened == Some(Open::Title(help.menu)))
.map(|help| Self::help_texts(help.entries, &cx.env, cx.env.words::<CommonWords>().path_separator.as_str()));
// Only a pass that shows the Help menu needs its commands; a builder runs here and nowhere else.
let help_entries = help.filter(|help| opened == Some(Open::Title(help.menu))).map(|help| help.entries());
let help_rows =
help_entries.as_deref().map(|entries| Self::help_texts(entries, &cx.env, cx.env.words::<CommonWords>().path_separator.as_str()));
// The search starts empty each time the Help menu opens.
let mut query = if help_rows.is_some() { cx.memory::<Query>().clone() } else { Query::default() };
let mut stepped = None;
@@ -542,7 +576,9 @@ impl Component for MenuBar<'_> {
Menu::inline(Label::from(name.clone()))
.show(ui, |ui, menu| match slot {
Open::Title(at) => {
if let (Some(help), Some(rows)) = (help.filter(|help| help.menu == *at), help_rows.as_ref()) {
if let (Some(_), Some(rows), Some(entries)) =
(help.filter(|help| help.menu == *at), help_rows.as_ref(), help_entries.as_deref())
{
// The field sits in a padded frame: its edge lines up with the row labels and it keeps clear of the first row.
// The field drives the menu: Up, Down, Home and End move its active row and Enter runs
// it, or the first enabled match, while typing stays in the field.
@@ -574,14 +610,14 @@ impl Component for MenuBar<'_> {
let listed: Vec<usize> = search_order(&folder, &query.0, &refs)
.into_iter()
.filter(|at| {
let command = help.entries[*at].command();
let command = entries[*at].command();
let fresh = !seen.contains(&command);
seen.push(command);
fresh
})
.collect();
for at in &listed {
let entry = &help.entries[*at];
let entry = &entries[*at];
let row = MenuItem::command(entry.command().clone()).label(entry.label().clone());
if entry.path().is_empty() {
row.show(ui)
+47
View File
@@ -146,3 +146,50 @@ fn a_pointer_move_over_menu_rows_lights_the_row_under_it_in_that_frame() {
}
}
}
/// A help search over built entries builds them only in a pass that shows the Help menu: a bar whose menus stay closed
/// never runs the builder, an open File menu doesn't either, and the open Help menu searches what it built.
#[trial]
fn built_help_entries_are_collected_only_while_the_help_menu_shows() {
use std::cell::Cell;
use std::rc::Rc;
let builds = Rc::new(Cell::new(0u32));
let counted = builds.clone();
let mut fixture = Fixture::new(move |ui| {
let titles = vec![
MenuTitle::new("&File", |ui| {
MenuItem::new("&New").show(ui);
}),
MenuTitle::new("&Help", |ui| {
MenuItem::new("&About").show(ui);
}),
];
let counted = counted.clone();
let build = move || {
counted.set(counted.get() + 1);
entries()
};
MenuBar::new("Main menu", titles).help(MenuHelp::built(1, &build)).show(ui);
});
fixture.settle();
fixture.settle();
assert_eq!(builds.get(), 0, "closed menus build nothing");
let file = fixture.by_label("File").expect("the File title");
fixture.click(&file);
fixture.settle();
assert!(fixture.by_label("New").is_some(), "File is open");
assert_eq!(builds.get(), 0, "another open menu builds nothing");
fixture.key(Key::Escape, Modifiers::NONE);
fixture.settle();
let help = fixture.by_label("Help").expect("the Help title");
fixture.click(&help);
fixture.settle();
assert!(builds.get() > 0, "the open Help menu builds its entries");
let search = fixture.by_label("Search menus").expect("the search field");
fixture.click(&search);
fixture.type_text("duplic");
fixture.settle();
assert!(fixture.by_label("Copy").is_some(), "the search finds a built entry by its English label");
}