From 129eeb35902aaffee940e9c62567d3f9234264b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:52:02 -0800 Subject: [PATCH] macOS menu bar: every item shows its shortcut and takes it as its key equivalent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The native menu bar handed AppKit items without shortcuts: only the Window rows carried one, and Settings › General… carried the default ⌘K. Save, Open, Undo, Group and the other items showed no keys and had no key equivalents. - The native menu now gives each item the shortcut the menus show for it, else its command's chord in the window's keymap, the user's own set included, as the in-window bar's rows look it up. A rebound command shows its new key. - Settings › General… shows Preferences' current shortcut instead of the default one. - The Window rows' and Settings' shortcuts are read when the native menu is laid out, so they no longer stay empty after the first frame. --- crates/ui-egui/src/menus.rs | 4 +- crates/ui-egui/src/menus/labels.rs | 16 ++++++-- crates/ui-egui/src/menus/model.rs | 3 +- crates/ui-egui/src/menus/native.rs | 20 ++++++---- crates/ui-egui/src/menus/state.rs | 38 +++++++++++++------ crates/ui-egui/src/menus/tree.rs | 14 +++---- crates/ui-egui/src/tests/nativemenu.rs | 51 ++++++++++++++++++++++++++ 7 files changed, 112 insertions(+), 34 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 0ce4ff457a..5291000751 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -83,14 +83,14 @@ pub(crate) use invoke::graph_dialog; pub use invoke::{click_target, invoke}; pub(crate) use labels::shows_a_name; pub use labels::{CONTEXT_LABELS, DYNAMIC_LABELS, display_label, dynamic_label, item_shortcut, menu_strings}; -pub(crate) use labels::{holds_plugin_commands, lists_plugin}; +pub(crate) use labels::{holds_plugin_commands, item_shortcut_in, lists_plugin}; pub(crate) use model::{MAC_LABELS, home_key, home_showing}; pub use run::{check_params, run_ui_command}; pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; #[cfg(test)] use slots::RECENT_FONT_IDS; -pub(crate) use state::why_off; pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state}; +pub(crate) use state::{command_shortcuts, why_off}; pub(crate) use submenus::PATH_EFFECTS; pub use tree::{Listed, menu_tree, menu_tree_named}; pub use ui_commands::UI_COMMANDS; diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index bce650899b..1467de23c8 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -1,9 +1,10 @@ use super::slots::{perspective_grid, recent_slot, saved_selection_name, saved_selection_slot, saved_view, saved_view_slot}; -use super::state::{hidden_when_disabled, shortcut_of}; +use super::state::{command_shortcuts, hidden_when_disabled}; use super::tree::menu_tree; use super::ui_commands::UI_COMMANDS; use super::{Node, Value, VectorcraftApp, unbound}; -use craft::keymap::Chord; +use craft::keymap::{Chord, CommandRef}; +use vectorcraft_engine::cmd::prefscmds::PREF_CATEGORIES; /// Label for toggles whose text flips (Outline/Preview, Hide/Show …). pub fn dynamic_label(app: &VectorcraftApp, id: &str, label: &str) -> String { @@ -250,11 +251,18 @@ pub(super) fn spelling_item_label(id: &str, p: &Value) -> Option { /// The shortcut a menu item shows: its command's (items without params), a panel's for the /// Window menu's `window.panel {panel}` items, an effect's for the Effect menu's items, or a filter -/// plug-in's for Object › Plug-ins' `plugin.dialog {id}` items. +/// plug-in's for Object › Plug-ins' `plugin.dialog {id}` items. Settings' first page shows +/// Preferences' shortcut. pub fn item_shortcut(app: &VectorcraftApp, id: &str, p: &Value) -> Option { + item_shortcut_in(&command_shortcuts(app), id, p) +} + +/// [`item_shortcut`] with each entry's command looked up in `chord` ([`command_shortcuts`]). +pub(crate) fn item_shortcut_in(chord: &dyn Fn(&CommandRef) -> Option, id: &str, p: &Value) -> Option { let field = |name: &str| p.get(name).and_then(Value::as_str); let key = match (id, field("panel")) { ("window.panel", Some(panel)) => format!("panel:{panel}"), + ("edit.preferences", _) if field("category") == PREF_CATEGORIES.first().copied() => id.to_string(), ("effect.dialog" | "effect.apply", _) => format!("effect:{}", field("effect")?), ("plugin.dialog", _) => format!("plugin:{}", field("id")?), // The Artboard tool's canvas menu passes the point its Paste goes to. @@ -265,7 +273,7 @@ pub fn item_shortcut(app: &VectorcraftApp, id: &str, p: &Value) -> Option _ if p.is_null() => id.to_string(), _ => return None, }; - shortcut_of(app, &key) + chord(&crate::keymap::command_of(&key)) } /// Labels only the canvas context menu ([`context_items`]) shows, so the catalog tests can insist diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 421b763038..f00174b4ac 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -485,7 +485,8 @@ impl Build<'_> { match id { // A panel row shows the chord of the panel's shortcut (`panel:`), which binds `window.panel {panel}`; // a Window row runs it with `toggle: true`, so the framework finds no chord for the row's own command. - "window.panel" => { + // Settings' first page shows Preferences' shortcut, which binds `edit.preferences` with no page. + "window.panel" | "edit.preferences" if !params.is_null() => { let mut item = item; item.shortcut = super::labels::item_shortcut(self.app, id, params); item diff --git a/crates/ui-egui/src/menus/native.rs b/crates/ui-egui/src/menus/native.rs index 62fbc97da3..b9004c1ebb 100644 --- a/crates/ui-egui/src/menus/native.rs +++ b/crates/ui-egui/src/menus/native.rs @@ -1,12 +1,13 @@ //! The macOS menu bar on craft-menu's native menu: installed once, polled and run before the UI //! each frame, and synced after it. +use craft::keymap::{Chord, CommandRef}; use craft::menu::{Gate, ItemKind, LayoutOptions, MenuBar, NativeMenu, Node, mac, mac_layout}; use craft::ui::runtime::commands::{FirePhase, FireSource, Fired, holder}; use crate::VectorcraftApp; use crate::menus::model::{APP_NAME, item_title, pressed_pass, recording_shortcut, refresh, state_key, translate_label}; -use crate::menus::unbound; +use crate::menus::{command_shortcuts, item_shortcut_in, unbound}; /// The layout options every Mac layout of VectorCraft's menus uses: the app's name and its /// translation of the labels the layout writes itself. @@ -56,16 +57,20 @@ pub(crate) fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) { app.services.native_menu = Some(menu); } -/// The menus with each item's title, and whether it is on and checked, as they are now: AppKit's items show their own, -/// where the in-window bar reads them from the command states. Read here and not from the model, which is built before -/// the frame's input: a drag released or an Escape in this frame already shows. +/// The menus with each item's title, shortcut, and whether it is on and checked, as they are now: AppKit's items show +/// their own, where the in-window bar reads them from the command states. Read here and not from the model, which is +/// built before the frame's input: a drag released or an Escape in this frame already shows. Each item's shortcut is +/// the one the menus show for it ([`crate::menus::item_shortcut`]), else its command's chord in the keymap, the user's +/// set included, as the in-window bar's rows show it. It is also the item's key equivalent. The model's own shortcuts +/// (Window rows, Settings' first page) are read again here: the model built before the window's first keymap has none. fn stated(app: &VectorcraftApp) -> MenuBar { - fn walk(app: &VectorcraftApp, lang: crate::i18n::Lang, nodes: &mut [Node]) { + fn walk(app: &VectorcraftApp, lang: crate::i18n::Lang, chord: &dyn Fn(&CommandRef) -> Option, nodes: &mut [Node]) { for node in nodes { match node { Node::Item(it) if unbound(&it.command.id) => it.enabled = false, Node::Item(it) => { let (id, params) = (it.command.id.as_str(), &it.command.params); + it.shortcut = item_shortcut_in(chord, id, params).or_else(|| chord(&it.command)); if let Some((enabled, checked)) = crate::menus::shown_state(app, id, params) { it.enabled = enabled; if let Some(on) = checked { @@ -78,15 +83,16 @@ fn stated(app: &VectorcraftApp) -> MenuBar { it.label = title; } } - Node::Submenu { children, .. } => walk(app, lang, children), + Node::Submenu { children, .. } => walk(app, lang, chord, children), _ => {} } } } let mut bar = app.menus.bar.clone(); let lang = crate::i18n::current(); + let chord = command_shortcuts(app); for menu in &mut bar.menus { - walk(app, lang, &mut menu.children); + walk(app, lang, &chord, &mut menu.children); } bar } diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index b608e72feb..bce31f0fd0 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -2,7 +2,7 @@ use super::run::{normalize_panel, toolbar_double, toolbar_panel}; use super::slots::{perspective_grid, recent_slot, saved_selection_name, saved_selection_slot, saved_view, saved_view_slot}; use super::{Brightness, Value, VectorcraftApp}; use crate::i18n::LangExt as _; -use craft::keymap::Chord; +use craft::keymap::{Chord, CommandRef}; use craft::ui::runtime::commands; /// Checked state for toggle items. @@ -190,17 +190,33 @@ pub fn plugin_revision() -> u64 { /// the window's keymap, under the user's set in use (Edit → Keyboard Shortcuts). `None` before the /// window's first frame. pub fn shortcut_of(app: &VectorcraftApp, key: &str) -> Option { - let ctx = app.ui_ctx.as_ref()?; - let command = crate::keymap::command_of(key); - let window = commands::keymap(ctx)?; - let (now, built) = (&*app.shortcut_overrides, window.overrides()); - if now.len() == built.len() && now.iter().all(|(k, texts)| built.get(k) == Some(texts)) { - return commands::chord(ctx, &command); - } + command_shortcuts(app)(&crate::keymap::command_of(key)) +} + +/// The shortcut each command shows, as [`shortcut_of`] reads it, for a caller that asks for many: the +/// keymap is read once. `None` for every command before the window's first frame. +pub(crate) fn command_shortcuts(app: &VectorcraftApp) -> impl Fn(&CommandRef) -> Option + '_ { + let ctx = app.ui_ctx.as_ref(); + let window = ctx.and_then(commands::keymap); // The window's keymap takes a change of the set (`shortcuts.set`) from its next frame; the set is read until then. - let mut keymap = (*window).clone(); - keymap.set_overrides(now.clone()); - keymap.bindings(&command).into_iter().find(|b| b.trigger.press == craft::keymap::PressKind::Single).map(|b| b.trigger.chord) + let pending = window.as_ref().and_then(|window| { + let (now, built) = (&*app.shortcut_overrides, window.overrides()); + if now.len() == built.len() && now.iter().all(|(k, texts)| built.get(k) == Some(texts)) { + return None; + } + let mut keymap = (**window).clone(); + keymap.set_overrides(now.clone()); + Some(keymap) + }); + move |command| { + let ctx = ctx.filter(|_| window.is_some())?; + match &pending { + None => commands::chord(ctx, command), + Some(keymap) => { + keymap.bindings(command).into_iter().find(|b| b.trigger.press == craft::keymap::PressKind::Single).map(|b| b.trigger.chord) + } + } + } } /// Is a command currently enabled? diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index c1ea0a7b84..2e1ce41559 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -890,15 +890,11 @@ fn not_mac() -> Platforms { fn app_menu() -> Vec { let settings: Vec = vectorcraft_engine::cmd::prefscmds::PREF_CATEGORIES .iter() - .enumerate() - .map(|(i, page)| { - let mut item = - Item::new(CommandRef::with_params("edit.preferences", json!({ "category": page })), format!("{page}…")).role(ItemRole::Settings); - // Only the first page carries Preferences' shortcut. - if i == 0 { - item.shortcut = crate::shortcut_editor::default_command_shortcut("edit.preferences").and_then(crate::keymap::stored::parse_vc); - } - Node::Item(item) + // Only the first page carries Preferences' shortcut, which the menus' model gives it from the keymap. + .map(|page| { + Node::Item( + Item::new(CommandRef::with_params("edit.preferences", json!({ "category": page })), format!("{page}…")).role(ItemRole::Settings), + ) }) .collect(); let mut language = vec![cp("Automatic", "app.language", json!({ "lang": "auto" })), Sep]; diff --git a/crates/ui-egui/src/tests/nativemenu.rs b/crates/ui-egui/src/tests/nativemenu.rs index 8a13fbda07..f1f6bcd09c 100644 --- a/crates/ui-egui/src/tests/nativemenu.rs +++ b/crates/ui-egui/src/tests/nativemenu.rs @@ -63,6 +63,57 @@ fn settings_lists_every_preferences_page() { assert_eq!(crate::prefs_dialog::page(&m.app), Some("Units")); } +/// The default shortcut of command `id`, as the shortcut editor lists it. +fn default_chord(id: &str) -> Option { + crate::shortcut_editor::default_command_shortcut(id).and_then(crate::keymap::stored::parse_vc) +} + +/// The Settings › General… item of `bar`. +fn general(bar: &MenuBar) -> &Item { + let page = PREF_CATEGORIES[0]; + bar.items().into_iter().find(|it| it.command.id == "edit.preferences" && it.command.params["category"] == page).expect("Settings › General…") +} + +/// The menu bar hands every item its command's shortcut, so Save, Open, Undo and Group show their keys and AppKit +/// takes them as key equivalents. +#[test] +fn native_items_carry_their_commands_shortcuts() { + let m = Mac::new(true); + let bar = m.fake.last(); + for id in ["file.save", "file.open", "edit.undo", "object.group"] { + let chord = default_chord(id); + assert!(chord.is_some(), "{id} has a default shortcut"); + assert_eq!(find(&bar, id).shortcut, chord, "{id}"); + } +} + +/// A command bound to another key shows that key in the menu bar, and its old key is no longer the item's. +#[test] +fn a_rebound_command_shows_its_new_key_in_the_menu_bar() { + let mut m = Mac::new(true); + let old = default_chord("object.group"); + m.app.run("shortcuts.set", json!({"id": "object.group", "shortcut": "Cmd+Alt+Shift+F8"})).unwrap(); + m.frame(vec![]); + m.frame(vec![]); + let shown = find(&m.fake.last(), "object.group").shortcut; + assert_eq!(shown, Chord::parse("Cmd+Alt+Shift+F8").ok()); + assert_ne!(shown, old); +} + +/// Settings › General… carries Preferences' shortcut as the user set it, not the default one. +#[test] +fn settings_general_follows_a_rebound_preferences() { + let mut m = Mac::new(true); + let old = default_chord("edit.preferences"); + assert_eq!(general(&m.fake.last()).shortcut, old); + m.app.run("shortcuts.set", json!({"id": "edit.preferences", "shortcut": "Cmd+Alt+Shift+F8"})).unwrap(); + m.frame(vec![]); + m.frame(vec![]); + let shown = general(&m.fake.last()).shortcut; + assert_eq!(shown, Chord::parse("Cmd+Alt+Shift+F8").ok()); + assert_ne!(shown, old); +} + /// A native menu can't turn a plain item into a check item in place: the app's read of the menus /// is guarded by a state key, and these tests count the reads through a fake backend. ///