From 6491d45d615525b5e402d7afb5d437440fa97449 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 21:26:01 +0700 Subject: [PATCH] menus-w1: net change of 1 commits - menus-w1: written by an agent --- crates/appkit/Cargo.toml | 9 ++- crates/appkit/src/lib.rs | 29 ++++++++-- crates/menu/README.md | 18 +++++- crates/menu/src/context.rs | 20 +++++-- crates/menu/src/driver.rs | 12 ++-- crates/menu/src/lib.rs | 19 +++++-- crates/menu/src/mac.rs | 55 ++++++++++-------- crates/menu/src/model.rs | 76 +++++++++++-------------- crates/menu/src/palette.rs | 2 +- crates/menu/tests/it/heading.rs | 57 +++++++++++++++++++ crates/menu/tests/it/main.rs | 1 + crates/menu/tests/it/native.rs | 30 +++++++++- crates/menu/tests/it/sample.rs | 1 + crates/ui-widgets/src/menu/item.rs | 56 ++++++++++++------ crates/ui-widgets/src/menu/stories.rs | 53 ++++++++++++++++- crates/ui-widgets/tests/it/menu/rows.rs | 66 ++++++++++++++++++++- crates/window/src/native_menu.rs | 9 ++- crates/window/src/native_menu/mac.rs | 47 ++++++++++++--- crates/window/src/native_menu/other.rs | 18 +++++- 19 files changed, 451 insertions(+), 127 deletions(-) create mode 100644 crates/menu/tests/it/heading.rs diff --git a/crates/appkit/Cargo.toml b/crates/appkit/Cargo.toml index f63250462..ad602e383 100644 --- a/crates/appkit/Cargo.toml +++ b/crates/appkit/Cargo.toml @@ -7,7 +7,14 @@ license.workspace = true rust-version.workspace = true repository.workspace = true -# The workspace table with `unsafe_code` at `deny`: the real body allows it for this crate's FFI calls, and design-lint's +# `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through +# `NSNotificationCenter` with a block. +[target.'cfg(target_os = "macos")'.dependencies] +block2 = "0.6.2" +objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSMenu"] } +objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] } + +# The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's # `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one # workspace lint. [lints.rust] diff --git a/crates/appkit/src/lib.rs b/crates/appkit/src/lib.rs index 897920716..78dd786b1 100644 --- a/crates/appkit/src/lib.rs +++ b/crates/appkit/src/lib.rs @@ -1,16 +1,37 @@ //! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking. macOS //! only; the crate is empty elsewhere. //! -//! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. +//! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every +//! block says why it is sound. #![warn(missing_docs)] #![cfg(target_os = "macos")] +#![allow(unsafe_code)] -use std::sync::Arc; +use std::ptr::NonNull; +use std::sync::{Arc, Once}; + +use block2::RcBlock; +use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification}; +use objc2_foundation::{NSNotification, NSNotificationCenter}; /// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)` /// when it ends (`NSMenuDidEndTrackingNotification`), from the thread that posts the notification. Observes once /// for the process; a later call replaces nothing and does nothing. pub fn observe_menu_tracking(on_change: Arc) { - let _ = on_change; - todo!("mn.M12") + static OBSERVE: Once = Once::new(); + OBSERVE.call_once(|| { + // SAFETY: AppKit initializes these immutable notification-name constants before any code of the app runs. + let names = unsafe { [(NSMenuDidBeginTrackingNotification, true), (NSMenuDidEndTrackingNotification, false)] }; + let center = NSNotificationCenter::defaultCenter(); + for (name, tracking) in names { + let on_change = on_change.clone(); + let block = RcBlock::new(move |_: NonNull| on_change(tracking)); + // SAFETY: `name` is one of AppKit's notification names and the block takes the notification by pointer + // without reading it. The center copies the block and keeps the observer for the process's lifetime; + // nothing removes it, so the returned token is not needed. + unsafe { + center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block); + } + } + }); } diff --git a/crates/menu/README.md b/crates/menu/README.md index fdda51669..9b8836743 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -33,8 +33,13 @@ parameter carries it in the `CommandRef`: `CommandRef::with_params("file.open_recent", json!({"index": 3}))`. Items built directly use `Item::new(command, label)` with `.shortcut(chord)`, `.enabled(..)`, `.check(..)` or `.radio(..)` (the item's `ItemKind`), `.role(..)`, `.platforms(..)`, `.tint(colour)` and -`.tooltip(text)` (both for the in-window bar only; the native macOS menu ignores them); submenus use -`Node::submenu(label, children)`, with `.role(..)` for a tagged one. A shortcut is a +`.tooltip(text)` and `.sample(aspect, face)` (a `craft_ui::primitives::FacePaint` painted in a +column of its own between the label and the shortcut, `aspect` times as wide as the row's text +line is high: a font menu's samples) (all three for the in-window bar only; the native macOS menu +ignores them); submenus use `Node::submenu(label, children)`, with `.role(..)` for a tagged one. +`Node::heading(label)` (`Node::Heading`) is a caption over the rows after it and never a command: +it takes no mnemonic letter and no help-search entry, the native menu shows it as a disabled +item, and `tidy` drops one with no item after it before the next separator. A shortcut is a `craft_keymap::Chord`: `cmd` is ⌘ and `ctrl` the Control key. macOS shows radio items as check items. The app's open documents go in `MenuBar::documents` (`Document::new(command, name)`, `.active(..)` for the one in front, `hidden` for one kept open but not listed), and the layouts @@ -214,7 +219,14 @@ sets it back to the app's state, so the app's state always wins. While a menu is open, a click or Escape in the window closes it and does not reach egui (no canvas gesture, no tool action); pointer moves pass through. Only one click is kept this way until the menu reports closed, so a menu wrongly reported open costs one click. Menu updates wait -until the menu closes. A rebuild that fails keeps the menus as they were. +until the menu closes; the end of tracking wakes egui, and that frame applies them. A rebuild that +fails keeps the menus as they were. + +AppKit's `NSMenuDidBeginTracking` and `NSMenuDidEndTracking` notifications say whether a menu is +open (`craft_window::native_menu::menu_tracking()`, safe from any thread). Each begin comes back +once as `Event::Opened`, and `NativeMenu::take_opened` reports it once, for an app that refreshes +what a menu lists (a scripts folder) as it opens. It changes nothing the menus show, so it does +not re-sync them. ## Per frame diff --git a/crates/menu/src/context.rs b/crates/menu/src/context.rs index ddf69cd5a..ec02aa99e 100644 --- a/crates/menu/src/context.rs +++ b/crates/menu/src/context.rs @@ -22,7 +22,8 @@ use crate::model::{Builtin, Item, ItemKind, Node}; /// Shows `nodes` as rows of the menu body `ui` is in: a context menu's /// (`Menu::context(label, &response).show(ui, |ui, _| craft_menu::context::rows(ui, &nodes))`) or any other menu's. /// -/// A [`Node::Item`] is a command row, a [`Node::Separator`] a divider and a [`Node::Submenu`] a submenu row; +/// A [`Node::Item`] is a command row, a [`Node::Separator`] a divider, a [`Node::Heading`] a caption that takes no +/// mnemonic letter and a [`Node::Submenu`] a submenu row; /// AppKit's own items ([`Node::Standard`]) are left out. The chord of a row without a binding is the item's own /// shortcut, written for the shell's operating system. pub fn rows(ui: &mut Ui, nodes: &[Node]) { @@ -93,7 +94,7 @@ impl<'a> Rows<'a> { /// The label a node shows as the menu's sibling, for the preferred letters and the English labels. pub(crate) fn node_labels(&self, nodes: &[Node]) -> Vec { - let shown: Vec<&Node> = nodes.iter().filter(|node| !matches!(node, Node::Separator | Node::Standard { .. })).collect(); + let shown: Vec<&Node> = nodes.iter().filter(|node| !takes_no_letter(node)).collect(); let mut labels = self .labels( &shown, @@ -116,7 +117,7 @@ impl<'a> Rows<'a> { .into_iter(); nodes .iter() - .map(|node| if matches!(node, Node::Separator | Node::Standard { .. }) { String::new() } else { labels.next().unwrap_or_default() }) + .map(|node| if takes_no_letter(node) { String::new() } else { labels.next().unwrap_or_default() }) .collect() } @@ -136,7 +137,9 @@ impl<'a> Rows<'a> { Menu::submenu_row(ui, label, |ui, _| self.show(ui, children)); } } - Node::Heading(_) => todo!("mn.M7"), + Node::Heading(text) => { + MenuItem::heading(text.clone()).show(ui); + } Node::Standard { .. } => {} } } @@ -201,9 +204,18 @@ fn command_row<'a>(ui: &Ui, item: &Item, label: String, shortcut: Option if let Some(tooltip) = &item.tooltip { row = row.tooltip(tooltip.clone()); } + if let Some((aspect, face)) = &item.sample { + row = row.sample(*aspect, face.clone()); + } row } +/// Whether `node` shows no row of its own to choose, so it takes no mnemonic letter and leaves its siblings' +/// letters as they are. +fn takes_no_letter(node: &Node) -> bool { + matches!(node, Node::Separator | Node::Heading(_) | Node::Standard { .. }) +} + /// The checked state the command itself reports. fn checked(ui: &Ui, command: &CommandRef) -> Option { commands::resolve(ui.ctx(), command.clone()).checked diff --git a/crates/menu/src/driver.rs b/crates/menu/src/driver.rs index ac076caec..facb5fc99 100644 --- a/crates/menu/src/driver.rs +++ b/crates/menu/src/driver.rs @@ -5,11 +5,12 @@ use std::collections::HashSet; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use craft_keymap::{Chord, CommandRef, Key, Mods}; +use craft_ui::menu::Alternate; use craft_ui::runtime::windows::{KeyEquivalent, WindowAction, WindowHost}; use crate::layout::{Clash, Layout}; use crate::modal::ModalRules; -use crate::model::{Alternate, Builtin, Item, ItemKind, MenuBar, Node}; +use crate::model::{Builtin, Item, ItemKind, MenuBar, Node}; /// What the native menu reports. #[derive(Clone, Debug, PartialEq)] @@ -225,7 +226,6 @@ pub struct NativeMenu { /// that `checked` going from `Some` to `None` doesn't rebuild the menus. checkable: HashSet, /// A backend reported [`Event::Opened`] since [`NativeMenu::take_opened`] last answered. - #[allow(dead_code)] // P3(menus-w1): mn.M10 opened: bool, } @@ -344,7 +344,11 @@ impl NativeMenu { Event::Tap(chord) => self.add_key(&host, &chord, true), Event::Click(command) => self.clicks.push(command), Event::Handled(_) => {} - Event::Opened => todo!("mn.M10"), + // A menu opening changes nothing the menus show, so it does not re-sync them. + Event::Opened => { + self.opened = true; + continue; + } } self.dirty = true; } @@ -352,7 +356,7 @@ impl NativeMenu { /// Whether a backend reported [`Event::Opened`] since the last call; reports it once and clears it. pub fn take_opened(&mut self) -> bool { - todo!("mn.M10") + std::mem::take(&mut self.opened) } /// `tap`: a press and its release, for a click that stands for the key (no key-up follows). diff --git a/crates/menu/src/lib.rs b/crates/menu/src/lib.rs index 086baa59c..debddd2ac 100644 --- a/crates/menu/src/lib.rs +++ b/crates/menu/src/lib.rs @@ -6,7 +6,10 @@ //! its in-window bar ([`from_items`]), gives each top-level menu its role ([`MenuRole`]), and //! tags the items the layouts put in fixed places ([`MenuBar::tag_item`], [`MenuBar::tag_submenu`]). //! Each item runs a [`craft_keymap::CommandRef`], its shortcut is a [`craft_keymap::Chord`], and -//! its [`ItemKind`] makes it plain, a check item or a radio item. [`layout`] +//! its [`ItemKind`] makes it plain, a check item or a radio item; [`Item::sample()`] gives its row a +//! painted sample in the in-window bar. A [`Node::Heading`] is a caption over the rows after it, +//! never a command: the native menu shows it as a disabled item, and [`tidy`] drops one with no +//! item after it. [`layout`] //! arranges them the way the platform's apps do, and [`NativeMenu`] hands the result to a platform //! [`Backend`] and brings its events back. This part is pure and platform-free, so it is tested //! everywhere and builds for the web; only the backend touches AppKit, in `craft_window::native_menu`. @@ -50,9 +53,9 @@ //! the others go without a shortcut. A system item gives way to the command the app's keymap //! gives the key to, in a menu or not ([`LayoutOptions::keys`]), and to an item that shows it. //! -//! **Alternates.** An [`Item`] or [`Row`] can carry an [`Alternate`]: while its modifiers are held -//! as the row is clicked, the row runs the alternate's command, in the in-window bar and the native -//! menu. Key equivalents are never swapped. +//! **Alternates.** An [`Item`] or [`Row`] can carry an [`Alternate`] (craft-ui's, which panel menus +//! share): while its modifiers are held as the row is clicked, the row runs the alternate's +//! command, in the in-window bar and the native menu. Key equivalents are never swapped. //! //! **Customization.** [`Customization`] drops the rows the user hid and tints the ones they //! coloured, before [`from_items`]. @@ -87,6 +90,10 @@ //! `mac::install_app_menu` (a minimal app menu, for apps without a [`MenuBar`]) both use it. //! [`NativeMenu::on_command`] sees each allowed click as it arrives, also while egui is idle. //! +//! A native menu opening is [`Event::Opened`]; [`NativeMenu::take_opened`] reports it once, for an +//! app that refreshes what a menu lists (a scripts folder) when it opens. It changes nothing the menus +//! show, so it does not re-sync them. +//! //! Per frame: [`NativeMenu::poll`], then [`NativeMenu::set_gate`], [`NativeMenu::take_clicks`] and run the commands, then //! [`NativeMenu::sync_with`], which lays the menus out again only when the app's state changed //! (or [`NativeMenu::sync`], which compares a layout built every frame). @@ -114,6 +121,7 @@ pub mod shortcuts; pub use bar::{EnglishHook, Labeled, MenuBarOutput, MenuBarUi}; pub use craft_keymap::{Chord, CommandRef}; +pub use craft_ui::menu::Alternate; pub use customize::Customization; pub use documents::DOCUMENT_COMMAND_PREFIX; pub use driver::{Backend, ClipboardKeys, CommandHook, Dispatch, Event, Gate, NativeMenu, had_input}; @@ -123,8 +131,7 @@ pub use language::{LANGUAGE_COMMAND, LanguageChoice, LanguageLabels, LanguageMen pub use layout::{Clash, Layout, LayoutOptions, Target, desktop_layout, layout, mac_layout, web_layout}; pub use modal::{ModalRules, NAVIGATION_COMMANDS, PendingRule}; pub use model::{ - Alternate, Builtin, Document, Item, ItemKind, ItemRole, Menu, MenuBar, MenuRole, Node, Platforms, Row, Standard, from_items, structure_key, tidy, - window_key, + Builtin, Document, Item, ItemKind, ItemRole, Menu, MenuBar, MenuRole, Node, Platforms, Row, Standard, from_items, structure_key, tidy, window_key, }; pub use theme::{THEME_COMMAND, ThemeChoice, ThemeLabels, ThemeMenu, ThemeRow}; diff --git a/crates/menu/src/mac.rs b/crates/menu/src/mac.rs index b20174f5e..df791a747 100644 --- a/crates/menu/src/mac.rs +++ b/crates/menu/src/mac.rs @@ -32,12 +32,11 @@ 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::{ - Alternate, Builtin, Item, ItemKind, Menu, MenuBar, MenuRole, Node, Standard, label_or_system, native_id, structure_key, window_key, -}; +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 @@ -147,38 +146,44 @@ impl Native { *lock(&self.targets) = targets; } } - - /// Nothing else may wake egui when the menu closes (Escape goes to the menu), so look again. - fn retry_later(&mut self, bar: MenuBar) { - self.pending = Some(bar); - craft_ui::runtime::frame::request_repaint_after(&self.ctx, 0.25); - } } /// 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. +/// 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) { let mut targets = HashMap::new(); - let menus = bar.menus.iter().map(|m| lower_menu(m, &mut targets)).collect(); + // 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) -> native::Menu { +fn lower_menu(m: &Menu, targets: &mut HashMap, 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)) + native::Menu::new(m.title.clone(), kind, lower_nodes(&m.children, targets, headings)) } -fn lower_nodes(nodes: &[Node], targets: &mut HashMap) -> Vec { +fn lower_nodes(nodes: &[Node], targets: &mut HashMap, headings: &mut usize) -> Vec { nodes .iter() .map(|n| match n { Node::Separator => native::Node::Separator, - Node::Submenu { label, children, .. } => native::Node::Submenu { label: label.clone(), children: lower_nodes(children, targets) }, - Node::Heading(_) => todo!("mn.M9"), + Node::Submenu { label, children, .. } => { + native::Node::Submenu { label: label.clone(), children: lower_nodes(children, targets, headings) } + } + // 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, @@ -221,8 +226,9 @@ fn native_label(it: &Item) -> String { 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. - self.retry_later(bar.clone()); + // 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; @@ -248,13 +254,14 @@ impl Backend for Native { } 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 let Some(bar) = self.pending.take() { - if self.bar.tracking() { - self.retry_later(bar); - } else { - self.update(&bar); - } + if !self.bar.tracking() + && let Some(bar) = self.pending.take() + { + self.update(&bar); } out } diff --git a/crates/menu/src/model.rs b/crates/menu/src/model.rs index ba537791f..f0e20235a 100644 --- a/crates/menu/src/model.rs +++ b/crates/menu/src/model.rs @@ -4,8 +4,10 @@ use std::hash::{DefaultHasher, Hash, Hasher}; use std::ops::BitOr; -use craft_keymap::{Chord, CommandRef, Mods}; +use craft_keymap::{Chord, CommandRef}; use craft_theme::Srgba; +use craft_ui::list::ThumbAspect; +use craft_ui::menu::Alternate; use craft_ui::primitives::FacePaint; /// The app's menus, in order, and its open documents. @@ -197,34 +199,10 @@ pub struct Item { pub tooltip: Option, /// The command the item runs instead while its modifiers are held as it is chosen. pub alternate: Option, - /// A small painted sample shown in the row (in-window bar only; the native menu ignores it, as it - /// ignores `tint`). - pub sample: Option, -} - -/// The command a row runs while `mods` are held as it is chosen (Alt on Merge Visible runs Stamp -/// Visible). -#[derive(Clone, Debug, PartialEq)] -#[non_exhaustive] -pub struct Alternate { - /// The modifiers that select the alternate. - pub mods: Mods, - /// The command a pick runs while they are held. - pub command: CommandRef, -} - -impl Alternate { - /// The alternate that runs `command` while `mods` are held. - pub fn new(mods: Mods, command: impl Into) -> Alternate { - Alternate { mods, command: command.into() } - } - - /// Whether `held` includes every modifier of the alternate. The one rule the in-window row and - /// the native dispatch share. - pub(crate) fn selected_by(&self, held: Mods) -> bool { - let m = self.mods; - (!m.cmd || held.cmd) && (!m.ctrl || held.ctrl) && (!m.alt || held.alt) && (!m.shift || held.shift) - } + /// A small painted sample shown in the row, its width `aspect` times the row's text height + /// (in-window bar only; the native menu ignores it, as it ignores `tint`). + // PLAN: mn.M6 gives `Option`, but the row's cell (mn.M14) needs the aspect too; the sheet follows q182. + pub sample: Option<(ThumbAspect, FacePaint)>, } /// A plain item, or one with a checked state. @@ -426,10 +404,10 @@ impl Item { self } - /// Show `sample` in the row, painted by the in-window bar. - pub fn sample(self, sample: FacePaint) -> Item { - let _ = sample; - todo!("mn.M6") + /// Show `face` in the row, painted by the in-window bar in a cell `aspect` times as wide as the row's text is high. + pub fn sample(mut self, aspect: ThumbAspect, face: FacePaint) -> Item { + self.sample = Some((aspect, face)); + self } } @@ -452,8 +430,7 @@ impl Node { /// A caption over the rows that follow it. pub fn heading(label: impl Into) -> Node { - let _ = label; - todo!("mn.M2") + Node::Heading(label.into()) } /// Give an item or a submenu a role: `Node::submenu("Theme", pages).role(ItemRole::Appearance)`. @@ -714,12 +691,15 @@ pub fn from_items(tops: &[&str], rows: &[Row]) -> MenuBar { MenuBar { menus, documents: Vec::new() } } -/// Drop separators at the start or end of a level and collapse runs of them, and drop empty -/// submenus, at every depth. A submenu holding only a disabled placeholder (`No Recent Files`) -/// stays. +/// Drop separators at the start or end of a level and collapse runs of them, drop empty +/// submenus, and drop a heading with no item or submenu after it before the next separator or the +/// end of its level, at every depth. A submenu holding only a disabled placeholder (`No Recent +/// Files`) stays. pub fn tidy(nodes: Vec) -> Vec { - let mut out: Vec = Vec::with_capacity(nodes.len()); - for n in nodes { + // Back to front, so a heading knows whether an item follows it in its group. + let mut kept: Vec = Vec::with_capacity(nodes.len()); + let mut item_after = false; + for n in nodes.into_iter().rev() { let n = match n { Node::Submenu { label, children, role, platforms } => { let children = tidy(children); @@ -730,6 +710,17 @@ pub fn tidy(nodes: Vec) -> Vec { } other => other, }; + match &n { + Node::Item(_) | Node::Submenu { .. } => item_after = true, + Node::Separator => item_after = false, + Node::Heading(_) if !item_after => continue, + _ => {} + } + kept.push(n); + } + // Separators last, so one left first or doubled by a dropped heading or submenu collapses too. + let mut out: Vec = Vec::with_capacity(kept.len()); + for n in kept.into_iter().rev() { if matches!(n, Node::Separator) && matches!(out.last(), None | Some(Node::Separator)) { continue; } @@ -742,7 +733,7 @@ pub fn tidy(nodes: Vec) -> Vec { } /// A hash of everything a native menu can only change by rebuilding: menus, roles, item -/// commands, kinds (plain, check or radio), shortcuts, submenu labels and the labels of AppKit's items. Item +/// commands, kinds (plain, check or radio), shortcuts, submenu labels, headings and the labels of AppKit's items. Item /// labels, enabled and checked are updated in place. Window's open documents (the items running a /// [`MenuBar::documents`] command) are left out: opening or closing a document rebuilds only the /// Window menu ([`window_key`]). @@ -789,7 +780,8 @@ fn hash_nodes(nodes: &[Node], h: &mut DefaultHasher) { ']'.hash(h); } Node::Standard { kind, label } => ('s', kind, label).hash(h), - Node::Heading(_) => todo!("mn.M4"), + // A heading's native item has no target to update in place, so its label is structure. + Node::Heading(label) => ('h', label).hash(h), } } } diff --git a/crates/menu/src/palette.rs b/crates/menu/src/palette.rs index 1303a1498..4f203db12 100644 --- a/crates/menu/src/palette.rs +++ b/crates/menu/src/palette.rs @@ -10,7 +10,7 @@ impl MenuBar { /// The commands of the menus as the help search and the command palette list them, in menu order. /// /// The menus are laid out for `target` first, so the paths are the titles the user sees in the bar - /// ("File › Export › PNG…"; on a Mac the app menu carries the app's name). Separators, submenu rows, + /// ("File › Export › PNG…"; on a Mac the app menu carries the app's name). Separators, headings, submenu rows, /// AppKit's own items and the [`Builtin`] commands (which the crate runs itself) are not listed; the open /// documents of the Window menu are. Chords and enabled state are the commands': the search shows each entry /// as a command row. diff --git a/crates/menu/tests/it/heading.rs b/crates/menu/tests/it/heading.rs new file mode 100644 index 000000000..65e2b44d8 --- /dev/null +++ b/crates/menu/tests/it/heading.rs @@ -0,0 +1,57 @@ +//! A heading is a caption over the rows after it: structure, never a command. + +use craft_host::target::Os; +use craft_menu::{CommandRef, Item, Labeled, LayoutOptions, Menu, MenuBar, MenuBarUi, Node, Target, tidy}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Key, Modifiers}; + +use crate::sample::ids; + +/// `tidy` keeps a heading only with an item after it in its group; the help search lists the items and not the +/// heading; the in-window menu shows it as a caption that takes no mnemonic letter, leaves its siblings' letters as +/// they are and runs nothing when clicked. +#[trial] +fn a_heading_is_structure_and_never_a_command() { + let nodes = tidy(vec![ + Node::heading("最近"), + Item::new("file.new", "新建").into(), + Item::new("file.open", "打开").into(), + Node::Separator, + Node::heading("Empty"), + Node::Separator, + Item::new("file.close", "关闭").into(), + Node::heading("Trailing"), + ]); + assert_eq!( + ids(&nodes), + ["#最近", "file.new", "file.open", "---", "file.close"], + "a heading with no item after it goes, and the separators it leaves collapse" + ); + + let bar = MenuBar::new(vec![Menu::new("文件", nodes)]); + let entries = bar.help_entries(Target::Linux, &LayoutOptions::new("Trial"), None); + let listed: Vec = entries.iter().map(|entry| entry.command().key()).filter(|key| key.starts_with("file.")).collect(); + assert_eq!(listed, ["file.new", "file.open", "file.close"], "the help search lists the items, never the heading"); + + let english = |labeled: Labeled<'_>| match labeled { + Labeled::Title("文件") => Some("File".to_owned()), + Labeled::Command(command) if *command == CommandRef::new("file.new") => Some("New".to_owned()), + Labeled::Command(command) if *command == CommandRef::new("file.open") => Some("Open".to_owned()), + Labeled::Command(command) if *command == CommandRef::new("file.close") => Some("Close".to_owned()), + _ => None, + }; + let mut fixture = Fixture::new(move |ui| { + MenuBarUi::new(&bar).english(&english).show(ui); + }); + // A Mac bar has no letters. + fixture.os(Os::Linux); + fixture.settle(); + fixture.key(Key::F, Modifiers::ALT); + fixture.settle(); + let heading = fixture.by_label("最近").expect("the heading shows as written, with no letter"); + for row in ["新建(N)", "打开(O)", "关闭(C)"] { + assert!(fixture.by_label(row).is_some(), "{row}: the rows after the heading keep their own letters"); + } + fixture.click(&heading).settle(); + assert!(fixture.by_label("新建(N)").is_some(), "a click on the heading runs nothing, so the menu stays open"); +} diff --git a/crates/menu/tests/it/main.rs b/crates/menu/tests/it/main.rs index dccdaddd3..ac2ba3860 100644 --- a/crates/menu/tests/it/main.rs +++ b/crates/menu/tests/it/main.rs @@ -1,5 +1,6 @@ //! The integration binary of craft-menu: every test is a registered trial. +mod heading; mod layout; mod mnemonic; mod native; diff --git a/crates/menu/tests/it/native.rs b/crates/menu/tests/it/native.rs index 564f66667..f7667978c 100644 --- a/crates/menu/tests/it/native.rs +++ b/crates/menu/tests/it/native.rs @@ -1,5 +1,5 @@ //! The driver between a platform menu and the app: the gate, display-only shortcuts, key -//! equivalents, clipboard keys and closing an open menu. A fake backend stands +//! equivalents, clipboard keys, closing an open menu and reporting one opening. A fake backend stands //! in for the platform, so the trials run everywhere. use std::cell::{Cell, RefCell}; @@ -309,3 +309,31 @@ fn an_option_click_runs_the_rows_alternate() { let key = dispatch.chosen(&merge, Some(&shortcut), false, true, held([true, false, true, true]), Some(&alternate)); assert_eq!(key, Event::Key(chord("Cmd+Alt+Shift+E")), "a key equivalent is never swapped"); } + +/// A native menu beginning to track comes back once from `take_opened`, however often the menu is polled, for an +/// app that refreshes a menu's list as it opens; it changes nothing the menus show, so it lays nothing out again. +#[trial] +fn a_native_menu_opening_is_reported_once() { + let (mut menu, synced, events, _) = driver(); + let ctx = egui::Context::default(); + let opts = LayoutOptions::new("Sample"); + let builds = Cell::new(0); + let build = || { + builds.set(builds.get() + 1); + mac_layout(&sample(false, true), &opts) + }; + menu.sync_with(1, build); + assert!(!menu.take_opened(), "nothing opened yet"); + + events.borrow_mut().push(Event::Opened); + menu.poll(&ctx); + menu.poll(&ctx); + assert!(menu.take_opened(), "the opening is reported"); + assert!(!menu.take_opened(), "once"); + menu.sync_with(1, build); + assert_eq!((builds.get(), synced.borrow().len()), (1, 1), "an opening neither lays the menus out nor syncs them again"); + + events.borrow_mut().push(Event::Opened); + menu.poll(&ctx); + assert!(menu.take_opened(), "the next opening is reported too"); +} diff --git a/crates/menu/tests/it/sample.rs b/crates/menu/tests/it/sample.rs index f2116d79b..a13f3303e 100644 --- a/crates/menu/tests/it/sample.rs +++ b/crates/menu/tests/it/sample.rs @@ -83,6 +83,7 @@ pub fn ids(nodes: &[Node]) -> Vec { Node::Separator => "---".into(), Node::Submenu { label, .. } => format!("[{label}]"), Node::Standard { kind, .. } => format!("<{kind:?}>"), + Node::Heading(label) => format!("#{label}"), _ => "?".into(), }) .collect() diff --git a/crates/ui-widgets/src/menu/item.rs b/crates/ui-widgets/src/menu/item.rs index 2f1610f66..c894582cd 100644 --- a/crates/ui-widgets/src/menu/item.rs +++ b/crates/ui-widgets/src/menu/item.rs @@ -30,6 +30,9 @@ const MARKS: ColumnKey = ColumnKey::new("menu_marks"); /// The column of a level's row icons, and the gap after it, after the mark column. const ICONS: ColumnKey = ColumnKey::new("menu_icons"); +/// The column of a level's samples, and the gap before it, between the label and the shortcut. +const SAMPLES: ColumnKey = ColumnKey::new("menu_samples"); + /// The seconds the pointer rests on a row it crossed on its way to another row's open submenu before the row takes /// over: opens its own submenu, or closes the open one. A row the pointer does not cross that way takes over at once. const AIM_REST: f64 = 0.3; @@ -120,10 +123,11 @@ impl Outcome for MenuItemOutput { } /// The widths of a row's columns and its trailing items, in points; zero for a column the row does not show. The mark -/// and icon columns include the gap after them. +/// and icon columns include the gap after them, the sample column the gap before it. struct Columns { mark: f32, icon: f32, + sample: f32, trail: f32, } @@ -132,6 +136,7 @@ struct Placed { mark: Rect, icon: Rect, label: Rect, + sample: Rect, trail: Rect, } @@ -158,6 +163,7 @@ fn label_line(area: Rect, detail: f32) -> Rect { /// the text readable on (`MenuTint`); the active, open and disabled looks win over it. The row keeps its text, so the /// colour is never the only cue. #[derive(crate::contract::Component, crate::contract::Props)] +#[component(content_painter)] pub struct MenuItem<'a> { #[common] common: Common, @@ -193,7 +199,6 @@ pub struct MenuItem<'a> { /// The checked state of the entry the row shows: a radio mark in a value menu, a check mark elsewhere while true. #[prop(name = "entry_checked")] entry: Option, - #[allow(dead_code)] // P3(menus-w1): mn.M14 sample: Option<(crate::list::ThumbAspect, crate::primitives::FacePaint)>, ran: bool, opens: bool, @@ -230,9 +235,9 @@ impl<'a> MenuItem<'a> { /// A content-painted cell after the label and before the shortcut, in a column shared by the level's rows: as high /// as the row's text line and as wide as that height times `aspect`. #[must_use] - pub fn sample(self, aspect: crate::list::ThumbAspect, face: crate::primitives::FacePaint) -> Self { - let _ = (aspect, face); - todo!("mn.M14") + pub fn sample(mut self, aspect: crate::list::ThumbAspect, face: crate::primitives::FacePaint) -> Self { + self.sample = Some((aspect, face)); + self } /// A row bound to `command`: its label, chord, enabled state and checked state follow the command, and running it @@ -304,7 +309,8 @@ impl<'a> MenuItem<'a> { let (mark, flow) = Flow::new(line, rtl).take_start(columns.mark); let (icon, flow) = flow.take_start(columns.icon); let (trail, flow) = flow.take_end(step(columns.trail, trail_gap)); - Placed { mark, icon, label: flow.rect(), trail } + let (sample, flow) = flow.take_end(columns.sample); + Placed { mark, icon, label: flow.rect(), sample, trail } } fn register(&self, ctx: &Context, level: &MenuLevel, id: Id, label: &str, enabled: bool) { @@ -323,12 +329,22 @@ impl<'a> MenuItem<'a> { (shared(&MARKS, own(self.mark(command, level).is_some())), shared(&ICONS, own(self.lead_icon(command).is_some()))) } - fn columns(&self, cx: &MeasureCx<'_, Self>, level: &MenuLevel) -> Columns { + /// The row's sample column with the gap before it: as wide as the column group of the menu body gives it (the + /// widest sample of its rows), or the row's own outside a group. A sample is as high as the label line, `line` + /// high; a level with no sample has no column. + fn sample_column(&self, ctx: &Context, line: f32, gap: f32) -> f32 { + let own = self.sample.as_ref().map_or(0.0, |(aspect, _)| gap + aspect.of(line)); + crate::layout::ambient_width(ctx, &SAMPLES, own).unwrap_or(own) + } + + /// The row's columns, for a label line `line` high. + fn columns(&self, cx: &MeasureCx<'_, Self>, level: &MenuLevel, line: f32) -> Columns { let side = cx.icon(); 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.gap()); let trail = if self.submenu { side } else { self.keys(command).map_or(0.0, |keys| cx.face(keys).x) }; - Columns { mark, icon, trail } + Columns { mark, icon, sample, trail } } /// The size of the detail line; zero without one. @@ -383,20 +399,21 @@ impl Component for MenuItem<'_> { if !self.heading { self.register(cx.ui.ctx(), &level, cx.id, cx.resolved.label, cx.resolved.enabled); } - let columns = self.columns(cx, &level); let detail = self.detail_size(cx); let text = mnemonic::marked(cx.resolved.label, &cx.env.folder()).0; let run = TextRun::new(text.as_str()).role(self.label_look(cx.style).role); let label = if text.is_empty() { Vec2::ZERO } else { cx.layout_at(&run, f32::INFINITY).size() }; + let line = label.y.max(cx.icon()); + let columns = self.columns(cx, &level, line); let gap = cx.gap(); let step = |width: f32, gap: f32| if width > 0.0 { width + gap } else { 0.0 }; let rest = label.x.max(detail.x) + step(columns.trail, cx.style.shortcut_gap.max(gap)); let padding = cx.style.metrics.padding; - // A row measured before the level's widest mark or icon read narrower columns: the body's group adds the - // widest columns to what the rows reach past them. - crate::layout::report_beyond(cx.ui.ctx(), &[MARKS, ICONS], padding.start + padding.end + rest); - let width = columns.mark + columns.icon + rest; - Vec2::new(cx.room.map_or(width, |room| width.min(room)), label.y.max(cx.icon()) + detail.y) + // A row measured before the level's widest mark, icon or sample read narrower columns: the body's group adds + // the widest columns to what the rows reach past them. + crate::layout::report_beyond(cx.ui.ctx(), &[MARKS, ICONS, SAMPLES], padding.start + padding.end + rest); + let width = columns.mark + columns.icon + columns.sample + rest; + Vec2::new(cx.room.map_or(width, |room| width.min(room)), line + detail.y) } fn fills(&self) -> Option { @@ -410,12 +427,12 @@ impl Component for MenuItem<'_> { /// The shortcut's slot, which paints as the face of a `Kbd`. fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { let level = cx.env.get::(); - let columns = self.columns(cx, &level); + let line = label_line(cx.content_rect, self.detail_size(cx).y); + let columns = self.columns(cx, &level, line.height()); if columns.trail == 0.0 || self.submenu || self.heading { return; } let rtl = cx.flow.is_rtl(); - let line = label_line(cx.content_rect, self.detail_size(cx).y); let placed = self.place(&columns, line, rtl, cx.style.shortcut_gap.max(cx.gap())); let (rect, _) = Flow::new(placed.trail, rtl).take_end(columns.trail); cx.part(SHORTCUT, rect); @@ -540,8 +557,9 @@ impl Component for MenuItem<'_> { detail.as_ref().map(|detail| TextRun::new(detail.as_str()).role(cx.style.detail.role).color(cx.resolve(&cx.style.detail.color))); let detail_height = detail_run.as_ref().map_or(0.0, |run| draw.layout(run, f32::INFINITY).size().y); let trail = if self.submenu { side } else { cx.part_if_declared(SHORTCUT).map_or(0.0, |part| part.rect.width()) }; - let columns = Columns { mark: mark_column, icon: icon_column, trail }; let line = label_line(cx.content_rect, detail_height); + let sample_column = self.sample_column(&cx.core.ctx, line.height(), gap); + let columns = Columns { mark: mark_column, icon: icon_column, sample: sample_column, trail }; let placed = self.place(&columns, line, rtl, cx.style.shortcut_gap.max(gap)); let ink = cx.resolve(&cx.style.icon.color); let centred = |slot: Rect| Rect::from_center_size(slot.center(), Vec2::splat(side)); @@ -575,6 +593,10 @@ impl Component for MenuItem<'_> { let x = if rtl { placed.label.max.x - size.x } else { placed.label.min.x }; draw.galley(pos2(x, line.max.y), &layout); } + // Samples start at one edge of the shared column, after its gap, so a level's samples line up. + if let Some((aspect, face)) = &self.sample { + face.paint(&ui.content_painter(cx), Flow::new(placed.sample, rtl).span(gap, aspect.of(line.height()))); + } if self.submenu { let slot = Flow::new(placed.trail, rtl).take_end(side).0; draw.icon(centred(slot), &crate::controls::disclosure::DisclosureGlyph::submenu().color(ink)); diff --git a/crates/ui-widgets/src/menu/stories.rs b/crates/ui-widgets/src/menu/stories.rs index 10372fea9..bf4254dfe 100644 --- a/crates/ui-widgets/src/menu/stories.rs +++ b/crates/ui-widgets/src/menu/stories.rs @@ -1,14 +1,20 @@ //! Stories of the menu rows and the menu. -use super::{Menu, MenuItem}; +use super::{Alternate, Menu, MenuItem, PanelMenu, PanelRow}; use crate::buttons::Button; use crate::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Trigger}; use crate::display::Divider; +use crate::fonts::FontRef; use crate::layout_components::Stack; +use crate::list::ThumbAspect; +use crate::primitives::{DocRun, DocText, FacePaint}; +use crate::runtime::commands::EditCommands; +use crate::style::DataColor; use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_behavior::IconId; +use craft_keymap::Mods; use craft_theme::ControlSize; -use egui::Ui; +use egui::{Color32, Ui, pos2}; #[story(MenuItem<'static>, covers = [Default], drive = Drive::Activate)] fn menu_item(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { @@ -43,6 +49,36 @@ fn menu_item_marks_and_submenu(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { .unwrap_or_default() } +/// A sample of `font` that paints "Handgloves" across its cell, as a font menu shows a family. +fn family_sample(key: u64, font: FontRef, italic: bool) -> FacePaint { + FacePaint::new(key, move |painter, rect| { + let mut run = DocRun::new("Handgloves", font.clone(), rect.height() * 0.75, DataColor::new(painter.ink())); + if italic { + run = run.italic(); + } + let runs = [run]; + let layout = painter.layout(&DocText { wrap: Some(rect.width()), ..DocText::new(&runs) }.elide()); + let at = pos2(rect.left(), rect.center().y - layout.size().y / 2.0); + painter.painter.galley(at, layout.galley, Color32::PLACEHOLDER); + }) +} + +/// A "Font family" menu: each row shows its face in the level's sample column, between the label and the shortcut. +#[story(MenuItem<'static>, covers = [], drive = Drive::Never)] +fn menu_item_samples(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + let families = [ + (1, "Sans", FontRef::proportional(), false, "Ctrl+1"), + (2, "Sans Italic", FontRef::proportional(), true, "Ctrl+2"), + (3, "Mono", FontRef::monospace(), false, "Ctrl+3"), + ]; + let shown = Menu::inline("Font family").show(ui, |ui, _| { + for (key, label, font, italic, shortcut) in families { + MenuItem::new(label).shortcut(shortcut).sample(ThumbAspect::new(4, 1), family_sample(key, font, italic)).show(ui); + } + }); + StoryOutput::from(shown.output) +} + /// Shows `story` in a row as wide as the room: the opener sits at the start edge and the menu hangs from it, so the /// menu's place mirrors with the direction. fn in_row(ui: &mut Ui, mut story: impl FnMut(&mut Ui) -> StoryOutput) -> StoryOutput { @@ -92,6 +128,19 @@ fn menu_taller_than_the_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput }) } +/// A panel menu whose Undo row runs Redo while Alt is held, and shows it then, as the bar's rows with an alternate do. +#[story(PanelMenu, covers = [], drive = Drive::Never)] +fn panel_menu_alternate(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + in_row(ui, |ui| { + let opener = Button::new("Panel menu").show(ui); + let shown = Menu::new("Panel menu").open(Bind::bound(data.value("open", true))).opened_by(&opener, Trigger::Click).show(ui, |ui, _| { + let undo = PanelRow::Alternated(EditCommands::Undo.into(), Alternate::new(Mods::ALT, EditCommands::Redo)); + PanelMenu::new(vec![undo], vec![PanelRow::Command(EditCommands::Copy.into())]).show(ui); + }); + StoryOutput::from(shown.output) + }) +} + /// Enough font names to run past any window the gallery shows. const FONTS: [&str; 48] = [ "Arial", diff --git a/crates/ui-widgets/tests/it/menu/rows.rs b/crates/ui-widgets/tests/it/menu/rows.rs index 6af4950b9..d0d741607 100644 --- a/crates/ui-widgets/tests/it/menu/rows.rs +++ b/crates/ui-widgets/tests/it/menu/rows.rs @@ -1,10 +1,15 @@ -//! Menu rows: the detail line under the label and the row's own tooltip. +//! Menu rows: the detail line under the label, the row's own tooltip and the sample column. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; use craft_ui::buttons::Button; use craft_ui::contract::tooltip::DELAY; use craft_ui::contract::{Props as _, Show as _, ShowContainer as _, Trigger}; +use craft_ui::list::ThumbAspect; use craft_ui::menu::{Menu, MenuItem}; -use craft_ui::testing::{Fixture, pointer, trial}; +use craft_ui::primitives::FacePaint; +use craft_ui::testing::{Fixture, Room, pointer, trial}; #[trial] fn a_detail_shows_as_a_second_line_under_the_label() { @@ -105,3 +110,60 @@ fn the_menu_highlight_moves_to_the_next_row_in_the_frame_the_pointer_reaches_it( assert_eq!(fills_in(&shapes, redo), [lit], "the row the pointer reached paints the full highlight at once"); assert!(fills_in(&shapes, undo).is_empty(), "the row the pointer left paints no highlight at once: {:?}", fills_in(&shapes, undo)); } + +/// The rect each sample was painted in, by the face's key. +type Cells = Arc>>; + +/// A label long enough that a menu of it is wider than a popup's least width, so a sample column shows in the width. +const LONG: &str = "Neue Grotesk Display Condensed Extra Light Italic"; + +/// An open "Font family" menu of a long-labelled row and a short one, with a wide and a narrow sample when `samples`: +/// the fixture and where the samples were painted. +fn font_family(samples: bool) -> (Fixture, Cells) { + let cells = Cells::default(); + let painted = cells.clone(); + let mut fixture = Fixture::new(move |ui| { + let opener = Button::new("Open").show(ui); + Menu::new("Font family").opened_by(&opener, Trigger::Click).show(ui, |ui, _| { + for (key, label, wide) in [(1_u64, LONG, 12_u16), (2, "Mono", 6)] { + let mut row = MenuItem::new(label); + if samples { + let painted = painted.clone(); + row = row.sample( + ThumbAspect::new(wide, 1), + FacePaint::new(key, move |_, rect| { + painted.lock().unwrap().insert(key, rect); + }), + ); + } + row.show(ui); + } + }); + }); + // A window's room, so the long row shows unelided beside its sample. + fixture.in_room(Room::Window).settle(); + let opener = fixture.by_label("Open").expect("the opener"); + fixture.click(&opener).settle(); + (fixture, cells) +} + +/// A font menu's samples sit in one column after the labels: the narrower sample starts where the wider one does, +/// and the column widens the menu by the widest sample once. A menu without samples reserves no column. +#[trial] +fn a_level_with_samples_shares_one_sample_column_and_a_level_without_has_none() { + let (sampled, cells) = font_family(true); + let cells = cells.lock().unwrap().clone(); + let (wide, narrow) = (cells[&1], cells[&2]); + assert!(wide.width() > narrow.width(), "the aspect sets a sample's width"); + assert!((wide.height() - narrow.height()).abs() < 0.5, "every sample is as high as its row's text line"); + assert!((wide.min.x - narrow.min.x).abs() < 0.5, "the narrower sample starts where the wider one does: one column"); + let row = |fixture: &Fixture, label: &str| fixture.by_label(label).expect("the menu is open").rect; + assert!(row(&sampled, "Mono").expand(0.5).contains_rect(narrow), "the sample lies inside its row"); + let label = |text: &str| sampled.texts().iter().find(|run| run.text == text).map(|run| run.rect).expect("the label is painted"); + assert!(label(LONG).max.x <= wide.min.x + 0.5, "the long label ends before the column"); + + let (plain, none) = font_family(false); + assert!(none.lock().unwrap().is_empty(), "a level without samples paints none"); + let grown = row(&sampled, "Mono").width() - row(&plain, "Mono").width(); + assert!(grown >= wide.width() && grown < wide.width() + narrow.width(), "the column is the widest sample and its gap, once: {grown}"); +} diff --git a/crates/window/src/native_menu.rs b/crates/window/src/native_menu.rs index d4908cce1..ae8f82483 100644 --- a/crates/window/src/native_menu.rs +++ b/crates/window/src/native_menu.rs @@ -254,13 +254,13 @@ impl Options { /// Whether a menu is open. Safe from any thread; false where there is no application menu bar. pub fn menu_tracking() -> bool { - todo!("mn.M12") + imp::menu_tracking() } /// Whether a menu began tracking since the last call, which clears it. Safe from any thread; false where there is /// no application menu bar. pub fn take_menu_began() -> bool { - todo!("mn.M12") + imp::take_menu_began() } /// The installed menu bar. @@ -273,8 +273,7 @@ impl NativeBar { /// without an application menu bar. It replaces a menu from [`install_app_menu`]. `wake` is called when menu /// tracking ends. pub fn install(bar: &Bar, options: Options, wake: Wake) -> Option { - let _ = wake; // P3(menus-w1): mn.M13 - imp::Installed::install(bar, options).map(NativeBar) + imp::Installed::install(bar, options, wake).map(NativeBar) } /// Where chosen items go. The process has one handler, the one set last. @@ -296,7 +295,7 @@ impl NativeBar { /// Whether a menu began tracking since the last call ([`take_menu_began`]). pub fn take_began(&self) -> bool { - todo!("mn.M13") + self.0.take_began() } /// Close the open menu, if there is one. diff --git a/crates/window/src/native_menu/mac.rs b/crates/window/src/native_menu/mac.rs index 99832b04d..9193a44f4 100644 --- a/crates/window/src/native_menu/mac.rs +++ b/crates/window/src/native_menu/mac.rs @@ -22,7 +22,7 @@ use std::collections::{HashMap, HashSet}; use std::panic::{AssertUnwindSafe, catch_unwind}; use std::str::FromStr; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; use muda::accelerator::{Accelerator, Code, Modifiers}; use muda::{CheckMenuItem, MenuEvent, MenuItem, PredefinedMenuItem, Submenu}; @@ -30,11 +30,40 @@ use objc2::{MainThreadMarker, sel}; use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSEventType}; use objc2_foundation::{NSBundle, NSLocale, NSObjectProtocol, NSString}; -use super::{Bar, Chosen, Handler, Held, Item, Menu, MenuKind, Node, Options, Platform, Shortcut}; +use super::{Bar, Chosen, Handler, Held, Item, Menu, MenuKind, Node, Options, Platform, Shortcut, Wake}; /// Set by [`Installed::install`]: there is one full menu bar per process. static INSTALLED: AtomicBool = AtomicBool::new(false); +/// A menu is tracking: set when AppKit posts `NSMenuDidBeginTracking`, cleared on `NSMenuDidEndTracking`. An atomic, +/// so it reads right off the main thread too; AppKit can deliver window input while a menu still tracks +/// (asynchronous menu presentation). +static TRACKING: AtomicBool = AtomicBool::new(false); + +/// A menu began tracking since the last [`take_menu_began`]; set on begin only. +static BEGAN: AtomicBool = AtomicBool::new(false); + +pub(super) fn menu_tracking() -> bool { + TRACKING.load(Ordering::Relaxed) +} + +pub(super) fn take_menu_began() -> bool { + BEGAN.swap(false, Ordering::Relaxed) +} + +/// Keep [`TRACKING`] and [`BEGAN`] in step with AppKit's notifications, and call `wake` when tracking ends so the +/// app applies the changes it held back while the menu was open. +fn observe_tracking(wake: Wake) { + craft_appkit::observe_menu_tracking(Arc::new(move |tracking| { + TRACKING.store(tracking, Ordering::Relaxed); + if tracking { + BEGAN.store(true, Ordering::Relaxed); + } else { + wake(); + } + })); +} + /// Where the menu event handler sends events: the handler set last. static ROUTE: Mutex> = Mutex::new(None); @@ -190,7 +219,7 @@ pub(super) struct Installed { } impl Installed { - pub(super) fn install(bar: &Bar, options: Options) -> Option { + pub(super) fn install(bar: &Bar, options: Options, wake: Wake) -> Option { MainThreadMarker::new()?; if INSTALLED.swap(true, Ordering::SeqCst) { return None; @@ -200,6 +229,7 @@ impl Installed { INSTALLED.store(false, Ordering::SeqCst); return None; } + observe_tracking(wake); Some(installed) } @@ -332,13 +362,12 @@ impl Installed { rebuilt } - /// A menu bar menu is open while one of its titles is highlighted. - /// - /// This assumes AppKit sets the main menu's `highlightedItem` while one of its menus is open - /// and clears it when the menu closes; not yet confirmed on every macOS version. If it stayed - /// set, a caller that waits for the menu to close would wait for good. pub(super) fn tracking(&self) -> bool { - MainThreadMarker::new().and_then(|mtm| NSApplication::sharedApplication(mtm).mainMenu()).is_some_and(|m| m.highlightedItem().is_some()) + menu_tracking() + } + + pub(super) fn take_began(&self) -> bool { + take_menu_began() } pub(super) fn cancel_tracking(&self) { diff --git a/crates/window/src/native_menu/other.rs b/crates/window/src/native_menu/other.rs index 3ae5e3c9e..288d0a4e3 100644 --- a/crates/window/src/native_menu/other.rs +++ b/crates/window/src/native_menu/other.rs @@ -2,13 +2,23 @@ use std::convert::Infallible; -use super::{Bar, Handler, Options}; +use super::{Bar, Handler, Options, Wake}; + +/// No menu bar here, so no menu is ever open. +pub(super) fn menu_tracking() -> bool { + false +} + +/// No menu bar here, so no menu ever begins tracking. +pub(super) fn take_menu_began() -> bool { + false +} /// Never built: [`Installed::install`] returns `None`. pub(super) struct Installed(Infallible); impl Installed { - pub(super) fn install(_: &Bar, _: Options) -> Option { + pub(super) fn install(_: &Bar, _: Options, _: Wake) -> Option { None } @@ -24,6 +34,10 @@ impl Installed { match self.0 {} } + pub(super) fn take_began(&self) -> bool { + match self.0 {} + } + pub(super) fn cancel_tracking(&self) { match self.0 {} }