Files
craft-libs/crates/menu/src/mac.rs
T
Dylan M. Taylor b138b533fe Merge remote-tracking branch 'upstream/next' into pr-2809-merge
# Conflicts:
#	crates/automation/Cargo.toml
#	crates/automation/src/access.rs
#	crates/automation/src/synthetic.rs
#	crates/automation/tests/it/access.rs
#	crates/automation/tests/it/synthetic.rs
#	crates/behavior/src/codec.rs
#	crates/behavior/src/edit_history.rs
#	crates/behavior/src/lib.rs
#	crates/behavior/src/wheel.rs
#	crates/color-ui/src/ui/paint_chip.rs
#	crates/color-ui/src/ui/pair.rs
#	crates/color-ui/src/ui/palette.rs
#	crates/color-ui/src/ui/palette/stories.rs
#	crates/dialogs/src/service.rs
#	crates/draw/src/ui/transform/transform_box.rs
#	crates/draw/src/ui/transform/transform_box/stories.rs
#	crates/draw/tests/it/transform_box.rs
#	crates/font-manager/src/glyphs.rs
#	crates/font-manager/src/picker.rs
#	crates/font-manager/src/picker/rank.rs
#	crates/font-manager/src/picker/rows.rs
#	crates/font-manager/src/picker/stories.rs
#	crates/font-manager/tests/it/picker.rs
#	crates/host/src/lib.rs
#	crates/menu/src/context.rs
#	crates/menu/src/mac.rs
#	crates/menu/src/model.rs
#	crates/pages/src/ui/view.rs
#	crates/platform/README.md
#	crates/platform/src/browser_files.rs
#	crates/print/src/ui/dialog.rs
#	crates/print/src/ui/mod.rs
#	crates/print/src/ui/panel.rs
#	crates/print/src/ui/stories.rs
#	crates/print/tests/it/dialog.rs
#	crates/text/src/ui/character.rs
#	crates/text/src/ui/character/rows.rs
#	crates/text/src/ui/editor.rs
#	crates/text/tests/it/editor.rs
#	crates/text/tests/it/main.rs
#	crates/ui-canvas/src/canvas/mod.rs
#	crates/ui-canvas/src/canvas/split/stories.rs
#	crates/ui-canvas/src/canvas/tool_host.rs
#	crates/ui-canvas/src/canvas_controls/outline/mod.rs
#	crates/ui-canvas/src/canvas_controls/task_bar.rs
#	crates/ui-canvas/src/canvas_controls/task_bar/stories.rs
#	crates/ui-canvas/tests/it/canvas/navigate.rs
#	crates/ui-canvas/tests/it/canvas/tool_keys.rs
#	crates/ui-canvas/tests/it/canvas_controls/task_bar.rs
#	crates/ui-contract/src/contract/collection/props.rs
#	crates/ui-contract/src/contract/cx/pointer.rs
#	crates/ui-contract/src/contract/items/access.rs
#	crates/ui-contract/src/contract/items/drag.rs
#	crates/ui-contract/src/contract/items/lead.rs
#	crates/ui-contract/src/contract/label.rs
#	crates/ui-contract/src/contract/mod.rs
#	crates/ui-contract/src/contract/run.rs
#	crates/ui-contract/src/contract/steps/report.rs
#	crates/ui-contract/src/contract/steps/update.rs
#	crates/ui-contract/src/primitives/mod.rs
#	crates/ui-contract/src/primitives/sensing.rs
#	crates/ui-contract/src/primitives/text_adapter.rs
#	crates/ui-contract/src/primitives/text_input.rs
#	crates/ui-contract/src/runtime/access/emit.rs
#	crates/ui-contract/src/runtime/access/text.rs
#	crates/ui-contract/src/runtime/commands/board.rs
#	crates/ui-contract/src/runtime/commands/mod.rs
#	crates/ui-contract/src/runtime/drag.rs
#	crates/ui-contract/src/runtime/egui/access.rs
#	crates/ui-contract/src/runtime/egui/access/tree.rs
#	crates/ui-contract/src/runtime/egui/input.rs
#	crates/ui-contract/src/runtime/env.rs
#	crates/ui-contract/src/runtime/focus/nav.rs
#	crates/ui-contract/src/runtime/frame.rs
#	crates/ui-contract/src/runtime/keys.rs
#	crates/ui-contract/src/runtime/keys/claims.rs
#	crates/ui-contract/src/runtime/keys/input.rs
#	crates/ui-contract/src/runtime/keys/route.rs
#	crates/ui-contract/src/runtime/pointer.rs
#	crates/ui-contract/src/runtime/windows.rs
#	crates/ui-contract/src/testing/fixture.rs
#	crates/ui-contract/src/testing/host_key_trials.rs
#	crates/ui-contract/tests/it/collection/rows.rs
#	crates/ui-contract/tests/it/drag/mod.rs
#	crates/ui-contract/tests/it/runtime/wheel.rs
#	crates/ui-macros/src/props.rs
#	crates/ui-panels/src/dialog/mod.rs
#	crates/ui-panels/src/dialog/prompts.rs
#	crates/ui-panels/src/dialog/recovery.rs
#	crates/ui-panels/src/dialog/trials.rs
#	crates/ui-panels/src/dialog/words.rs
#	crates/ui-panels/src/rails/drawer.rs
#	crates/ui-panels/src/rails/drawer/stories.rs
#	crates/ui-panels/src/rails/tool/trials.rs
#	crates/ui-panels/src/sections/footer.rs
#	crates/ui-panels/tests/it/rails/drawer.rs
#	crates/ui-patterns/src/patterns/dock/area.rs
#	crates/ui-patterns/src/patterns/form_dialogs/about.rs
#	crates/ui-patterns/src/patterns/form_dialogs/dialog.rs
#	crates/ui-patterns/src/patterns/form_dialogs/dialog/stories.rs
#	crates/ui-patterns/src/patterns/form_dialogs/host_requests.rs
#	crates/ui-patterns/src/patterns/form_dialogs/mod.rs
#	crates/ui-patterns/src/patterns/form_dialogs/param.rs
#	crates/ui-patterns/src/patterns/form_dialogs/properties.rs
#	crates/ui-patterns/src/patterns/form_dialogs/properties/stories.rs
#	crates/ui-patterns/src/patterns/form_dialogs/rows.rs
#	crates/ui-patterns/src/patterns/form_dialogs/rows/stories.rs
#	crates/ui-patterns/src/patterns/panels/history.rs
#	crates/ui-patterns/src/patterns/preferences/document/model.rs
#	crates/ui-patterns/src/patterns/preferences/model.rs
#	crates/ui-patterns/src/patterns/preferences/page.rs
#	crates/ui-patterns/src/patterns/preferences/rows.rs
#	crates/ui-patterns/src/patterns/preferences/window.rs
#	crates/ui-patterns/src/patterns/preferences/window/stories.rs
#	crates/ui-patterns/src/patterns/presets/browser.rs
#	crates/ui-patterns/tests/it/docking/group_view.rs
#	crates/ui-patterns/tests/it/form_dialogs/dialog.rs
#	crates/ui-patterns/tests/it/form_dialogs/params.rs
#	crates/ui-patterns/tests/it/preferences/model.rs
#	crates/ui-shell/src/shell/start.rs
#	crates/ui-shell/src/shell/start/stories.rs
#	crates/ui-widgets/src/buttons/icon_button.rs
#	crates/ui-widgets/src/buttons/mod.rs
#	crates/ui-widgets/src/buttons/stories.rs
#	crates/ui-widgets/src/choice/swatch.rs
#	crates/ui-widgets/src/choice/swatch_table.rs
#	crates/ui-widgets/src/display/text.rs
#	crates/ui-widgets/src/form/slider_field.rs
#	crates/ui-widgets/src/layout_components/mod.rs
#	crates/ui-widgets/src/list/mod.rs
#	crates/ui-widgets/src/list/row/paint.rs
#	crates/ui-widgets/src/list/row/show.rs
#	crates/ui-widgets/src/list/stories.rs
#	crates/ui-widgets/src/list/view.rs
#	crates/ui-widgets/src/list/view_stories.rs
#	crates/ui-widgets/src/menu/mod.rs
#	crates/ui-widgets/src/menu/stories.rs
#	crates/ui-widgets/src/pickers/select.rs
#	crates/ui-widgets/src/tabs/document.rs
#	crates/ui-widgets/src/text/number.rs
#	crates/ui-widgets/src/text/zoom_field.rs
#	crates/ui-widgets/src/tile_grid/grid.rs
#	crates/ui-widgets/src/tile_grid/grid/stories.rs
#	crates/ui-widgets/src/tile_grid/mod.rs
#	crates/ui-widgets/tests/it/label/tooltip.rs
#	crates/ui-widgets/tests/it/popover/popup.rs
#	crates/ui-widgets/tests/it/tabs.rs
#	crates/ui-widgets/tests/it/text/mod.rs
#	crates/ui-widgets/tests/it/text/number.rs
#	crates/ui-widgets/tests/it/tile_grid/grid.rs
#	crates/window/Cargo.toml
#	docs/components-index.md
#	docs/porting.md
2026-11-23 19:01:32 -05:00

312 lines
15 KiB
Rust

//! The macOS menu bar. This module lowers the platform-free menu model to the plain description
//! [`craft_window::native_menu`] shows, and turns the platform's events into the driver's
//! [`Event`]s. AppKit itself is in craft-window; off macOS [`install`] returns `None`.
//!
//! - An item's native id is its command's [`craft_keymap::CommandRef::key`]. Native ids must be
//! unique: a command shown twice (Keyboard Shortcuts in Edit and Window) has `key` for its first
//! item and `key#2` for its second, and both report the command.
//! - A radio item is a check item: AppKit menus have no radio look.
//! - A structure change ([`crate::structure_key`]: a new Open Recent file, a language switch)
//! rebuilds the menu bar; labels, enabled and checked are updated in place. Opening or closing a
//! document ([`crate::window_key`]) rebuilds only the Window menu.
//! - A chosen item is a click or a key equivalent: the platform says which. A key equivalent goes
//! back to egui as the key press that was made (the event's modifiers, not the item's: AppKit may
//! match ⌘R to a ⇧⌘R item), so the app's key rules still apply. A shortcut the layout assigned
//! ([`crate::Item::layout_shortcut`]) stays a click: the app's keys don't know it. While a text
//! field has the keys, a key equivalent is a click unless the field handles it
//! ([`NativeMenu::set_gate`]).
//! - Only shortcuts with ⌘ or ⌃ become key equivalents. The others (`B`, `⇧B`, `⌥B`, `F5`) are not
//! shown in the native menu: muda 0.21 has no handle on the `NSMenuItem`, and its
//! `set_attributed_title` needs an `NSAttributedString` with a font and a tab stop, which
//! objc2 builds only with `unsafe` calls (the workspace forbids unsafe code).
//! - Hide ([`crate::Builtin::Hide`]) and Hide Others ([`crate::Builtin::HideOthers`]) are custom items
//! calling `NSApplication hide:` and `hideOtherApplications:`, because the predefined ones always
//! take ⌘H and ⌥⌘H.
//! - Standard items (Services, Show All, Minimize, Zoom, Bring All to Front, Close Window) and the
//! Hide Others and Minimize built-ins use the system's localized titles when the app supplies no
//! translation, that is when the label is still the English name.
//! - While a menu is open, changes wait until it closes.
use std::collections::HashMap;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use craft_keymap::{Chord, CommandRef, Key, Mods};
use craft_ui::menu::Alternate;
use craft_window::native_menu as native;
use crate::driver::{Backend, Dispatch, Event, NativeMenu, native_ok};
use crate::model::{Builtin, Item, ItemKind, Menu, MenuBar, MenuRole, Node, Standard, label_or_system, native_id, structure_key, window_key};
/// Install the native menu bar for `bar` (a [`crate::mac_layout`] result) and return the driver
/// for it. Call it once, on the main thread, in eframe's creator closure, so winit's default menu
/// doesn't stay up. `None` when AppKit refused the menus (the app keeps its in-window menus), off
/// the main thread, when a menu bar is already installed, and on platforms without an application
/// menu bar. It replaces an app menu from [`install_app_menu`].
///
/// craft-menu owns the process's menu event handler.
pub fn install(ctx: &egui::Context, bar: &MenuBar) -> Option<NativeMenu> {
install_with(ctx, bar, MacOptions::default())
}
/// How [`install_with`] sets up the native menus.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct MacOptions {
/// Make the [`MenuRole::Window`] menu AppKit's Windows menu, which lists the app's windows
/// after the menu's own items. On by default. An app that lists its documents itself
/// in the Window menu ([`MenuBar::documents`]) and keeps them in one window turns it off: AppKit
/// would list that window as well.
pub window_list: bool,
}
impl Default for MacOptions {
fn default() -> MacOptions {
MacOptions { window_list: true }
}
}
impl MacOptions {
/// Set [`MacOptions::window_list`].
pub fn window_list(mut self, on: bool) -> MacOptions {
self.window_list = on;
self
}
}
/// [`install`] with `options`.
pub fn install_with(ctx: &egui::Context, bar: &MenuBar, options: MacOptions) -> Option<NativeMenu> {
let (spec, targets) = lower(bar);
let wake: native::Wake = Arc::new({
let ctx = ctx.clone();
move || ctx.request_repaint()
});
let installed = native::NativeBar::install(&spec, native::Options::default().window_list(options.window_list), wake)?;
let (tx, rx) = channel();
let backend = Native { ctx: ctx.clone(), bar: installed, targets: Arc::new(Mutex::new(targets)), tx, rx, pending: None };
// `NativeMenu::new` attaches the driver's dispatch, which points the handler at this menu.
Some(NativeMenu::new(Box::new(backend)))
}
/// Replace winit's default macOS app menu with a minimal one whose Quit (⌘Q) asks the app first,
/// for an app without a [`MenuBar`] of its own: About, Services, Hide, Hide Others, Show All and
/// Quit, labelled in English with `app_name` ("Quit WordCraft").
///
/// winit's Quit ends the process without asking, so unsaved work is lost. This Quit has the id
/// [`craft_quit::QUIT_MENU_ID`] and runs [`craft_quit::on_menu_event`]: it asks the root window to
/// close, and the app's unsaved-changes check runs as for the close button. Call it once from the eframe app creator: winit
/// builds its default menu before that and would replace one installed earlier.
///
/// Does nothing when this menu or a full menu bar ([`install`]) is already installed, and on
/// platforms without an application menu bar. On error winit's menu stays: the app still runs, but
/// ⌘Q quits without asking.
pub fn install_app_menu(ctx: &egui::Context, app_name: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let ctx = ctx.clone();
let handler = Arc::new(move |id: &str, _: native::Chosen| {
craft_quit::on_menu_event(&ctx, id);
// Choosing an item is not window input, so nothing else wakes egui.
ctx.request_repaint();
});
native::install_app_menu(app_name, craft_quit::QUIT_MENU_ID, handler)
}
/// What each native item runs, by native id, for the handler.
type Targets = Arc<Mutex<HashMap<String, Target>>>;
/// What choosing an item reports.
#[derive(Clone)]
struct Target {
/// The command (several items can share one).
command: CommandRef,
chord: Option<Chord>,
layout_shortcut: bool,
/// The command a click runs instead while the alternate's modifiers are held.
alternate: Option<Alternate>,
}
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(PoisonError::into_inner)
}
struct Native {
ctx: egui::Context,
bar: native::NativeBar,
/// The items' targets, for the menu event handler.
targets: Targets,
tx: Sender<Event>,
rx: Receiver<Event>,
/// The latest menus, waiting for the open menu to close.
pending: Option<MenuBar>,
}
impl Native {
fn update(&mut self, bar: &MenuBar) {
let (spec, targets) = lower(bar);
if self.bar.apply(&spec) {
*lock(&self.targets) = targets;
}
}
}
/// The plain description of `bar` and what each of its native ids runs. The n-th item of a
/// command, depth first, has the n-th native id of that command; the n-th heading of the bar,
/// depth first, has the id `heading#n`.
fn lower(bar: &MenuBar) -> (native::Bar, HashMap<String, Target>) {
let mut targets = HashMap::new();
// One count for the whole bar: native ids are unique across menus, and a rebuild numbers the
// headings in the same order, so their ids stay while the structure does.
let mut headings = 0;
let menus = bar.menus.iter().map(|m| lower_menu(m, &mut targets, &mut headings)).collect();
(native::Bar::new(menus, structure_key(bar), window_key(bar)), targets)
}
fn lower_menu(m: &Menu, targets: &mut HashMap<String, Target>, headings: &mut usize) -> native::Menu {
let kind = match m.role {
MenuRole::Window => native::MenuKind::Windows,
MenuRole::Help => native::MenuKind::Help,
_ => native::MenuKind::Plain,
};
native::Menu::new(m.title.clone(), kind, lower_nodes(&m.children, targets, headings))
}
fn lower_nodes(nodes: &[Node], targets: &mut HashMap<String, Target>, headings: &mut usize) -> Vec<native::Node> {
nodes
.iter()
.map(|n| match n {
Node::Separator => native::Node::Separator,
// A native submenu is disabled while it has no children: a disabled one goes over empty.
Node::Submenu { label, children, enabled, .. } => {
native::Node::Submenu { label: label.clone(), children: if *enabled { lower_nodes(children, targets, headings) } else { Vec::new() } }
}
// A disabled item with no target: it shows the caption and nothing reports it. It has no command for
// `native_id` to key on, so its id is its place among the bar's headings.
Node::Heading(label) => {
let id = format!("heading#{headings}");
*headings += 1;
native::Node::Item(native::Item::new(id, label.clone()).enabled(false))
}
Node::Standard { kind, label } => native::Node::Platform {
kind: match kind {
Standard::Services => native::Platform::Services,
Standard::ShowAll => native::Platform::ShowAll,
Standard::Minimize => native::Platform::Minimize,
Standard::Zoom => native::Platform::Zoom,
Standard::BringAllToFront => native::Platform::BringAllToFront,
Standard::CloseWindow => native::Platform::CloseWindow,
},
title: label_or_system(label, kind.english(), native::system_title),
},
Node::Item(it) => {
let id = native_id(&it.command, |id| targets.contains_key(id));
let shortcut = it.shortcut.as_ref().filter(|c| native_ok(c)).and_then(shortcut);
let checked = match it.kind {
ItemKind::Check(c) | ItemKind::Radio(c) => Some(c),
ItemKind::Plain => None,
};
let item = native::Item::new(id.clone(), native_label(it)).enabled(it.enabled).checked(checked).shortcut(shortcut);
targets.insert(
id,
Target { command: it.command.clone(), chord: it.shortcut, layout_shortcut: it.layout_shortcut, alternate: it.alternate.clone() },
);
native::Node::Item(item)
}
})
.collect()
}
/// The label shown for `it`: Hide Others and Minimize take the system title when the app has no
/// translation.
fn native_label(it: &Item) -> String {
match Builtin::of(&it.command) {
Some(Builtin::HideOthers) => label_or_system(&it.label, "Hide Others", native::system_title),
Some(Builtin::Minimize) => label_or_system(&it.label, Standard::Minimize.english(), native::system_title),
_ => it.label.clone(),
}
}
impl Backend for Native {
fn sync(&mut self, bar: &MenuBar) {
if self.bar.tracking() {
// The driver counts this sync as done and may not send these menus again: `drain` applies them in
// the frame the end of tracking wakes ([`native::Wake`]).
self.pending = Some(bar.clone());
return;
}
self.pending = None;
self.update(bar);
}
fn drain(&mut self) -> Vec<Event> {
let mut out = Vec::new();
while let Ok(event) = self.rx.try_recv() {
// With asynchronous menu presentation the menu can stay on screen after its item ran.
self.bar.cancel_tracking();
// Hide and Hide Others run here. While a shortcut is recorded their key equivalents
// arrive as key presses instead, for the recorder.
if let Event::Click(command) = &event
&& let Some(hide @ (Builtin::Hide | Builtin::HideOthers)) = Builtin::of(command)
{
if hide == Builtin::Hide {
native::hide_app()
} else {
native::hide_other_apps()
}
continue;
}
out.push(event);
}
if self.bar.take_began() {
out.push(Event::Opened);
}
// After the events: they were chosen from the menus as they were.
if !self.bar.tracking()
&& let Some(bar) = self.pending.take()
{
self.update(&bar);
}
out
}
fn tracking(&self) -> bool {
self.bar.tracking()
}
fn attach(&mut self, dispatch: Dispatch) {
let (ctx, targets, tx) = (self.ctx.clone(), self.targets.clone(), self.tx.clone());
self.bar.set_handler(Arc::new(move |id: &str, chosen: native::Chosen| {
let target = lock(&targets).get(id).cloned();
// Ids that aren't ours are AppKit's own items (Services, Zoom, …), already handled.
if let Some(t) = target {
let h = chosen.held;
let mods = Mods { cmd: h.command, ctrl: h.control, alt: h.option, shift: h.shift };
let event = dispatch.chosen(&t.command, t.chord.as_ref(), t.layout_shortcut, chosen.key_down, mods, t.alternate.as_ref());
// The receiver goes away only with the app.
let _ = tx.send(event);
}
// Choosing an item is not window input, so nothing else wakes egui: without this the item
// runs only with the next input event, 8 to 90 seconds later in measurements.
ctx.request_repaint();
}));
}
fn cancel_tracking(&mut self) {
self.bar.cancel_tracking();
}
}
/// The key equivalent for a shortcut: `command` is ⌘ and `control` is ⌃, never folded together.
fn shortcut(c: &Chord) -> Option<native::Shortcut> {
let m = c.mods;
let mods_empty = !(m.cmd || m.ctrl || m.alt || m.shift);
// The shifted symbols name the key they are typed on, and a menu item that wants the shift writes it as a
// modifier; AppKit has no key equivalent for the context-menu key, the extra key of an ISO keyboard or F25 and up.
let code: &'static str = match c.key {
Key::Menu | Key::IntlBackslash => return None,
Key::OpenCurlyBracket | Key::CloseCurlyBracket | Key::Pipe | Key::Colon | Key::Questionmark | Key::Exclamationmark => return None,
Key::F25 | Key::F26 | Key::F27 | Key::F28 | Key::F29 | Key::F30 | Key::F31 | Key::F32 | Key::F33 | Key::F34 | Key::F35 => return None,
Key::Escape | Key::Enter | Key::Tab | Key::Space if mods_empty => return None,
key => key.code_name(),
};
Some(native::Shortcut { held: native::Held { command: m.cmd, control: m.ctrl, option: m.alt, shift: m.shift }, code })
}