top-w1: net change of 2 commits

- top-w1: written by an agent
- top-w1: review fixes (review-1)
This commit is contained in:
aiongg
2026-11-15 04:46:09 +00:00
parent e28bb2d2b5
commit de5d6b3199
15 changed files with 536 additions and 57 deletions
+14 -1
View File
@@ -8,7 +8,7 @@ rust-version.workspace = true
repository.workspace = true
[lib]
# Every test lives in the `it` integration binary, so `cargo test` builds the library once.
# Every test lives in the `it` integration binary, except the AppKit one (`mac_appkit`, no harness), so `cargo test` builds the library once.
test = false
[dependencies]
@@ -37,5 +37,18 @@ path = "tests/it/main.rs"
harness = false
required-features = ["screen-testing"]
# AppKit end to end: runs on the main thread, so no harness; on other platforms it does nothing.
[[test]]
name = "mac_appkit"
path = "tests/mac_appkit.rs"
harness = false
required-features = ["screen-testing"]
# The test reads AppKit's menu bar back and feeds it real events, through safe objc2 calls.
[target.'cfg(target_os = "macos")'.dev-dependencies]
objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSApplication", "NSControl", "NSEvent", "NSMenu", "NSMenuItem", "NSResponder"] }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSDate", "NSGeometry", "NSRunLoop", "NSString"] }
[lints]
workspace = true
+10 -2
View File
@@ -11,6 +11,7 @@ use craft_ui::display::Divider;
use craft_ui::menu::{Menu, MenuItem};
use craft_ui::runtime::commands;
use craft_ui::runtime::env::Env;
use craft_ui::runtime::pointer;
use craft_ui::runtime::windows::{WindowAction, WindowHost};
use egui::{Ui, ViewportId};
@@ -63,7 +64,7 @@ impl<'a> Rows<'a> {
) -> Vec<String> {
let english: Vec<String> = siblings.iter().map(|sibling| english(sibling).unwrap_or_default()).collect();
let english_refs: Vec<&str> = english.iter().map(String::as_str).collect();
let letters = mnemonic::assign(&english_refs, &craft_i18n::Folder::new("en")); // P3(top-w1): tp.T4, tp.T9
let letters = mnemonic::assign(&english_refs, &craft_i18n::Folder::new("en"));
siblings
.iter()
.zip(letters)
@@ -177,7 +178,14 @@ fn local(ui: &mut Ui, item: &Item, label: String, shortcut: Option<String>) -> c
/// The command row of `item`: the label and mnemonic come from the model, the state from the command.
fn command_row<'a>(ui: &Ui, item: &Item, label: String, shortcut: Option<String>) -> MenuItem<'a> {
let mut row = MenuItem::command(item.command.clone()).label(label).enabled(item.enabled);
// The alternate swaps the command only; the label, kind, shortcut, tint and tooltip stay the
// item's. The salt is the item's own command, so hover and focus stay on the row through the swap.
let held = pointer::frame(ui.ctx()).mods;
let command = match &item.alternate {
Some(alternate) if alternate.selected_by(held) => alternate.command.clone(),
_ => item.command.clone(),
};
let mut row = MenuItem::command(command).label(label).enabled(item.enabled).id_salt(item.command.key());
row = match item.kind {
ItemKind::Plain => row,
ItemKind::Check(on) => row.check(checked(ui, &item.command).unwrap_or(on)),
+6 -2
View File
@@ -25,7 +25,11 @@ impl Customization {
/// Drops the rows whose command id is hidden and sets the tint of the rows whose id has a
/// colour. Separators stay; `from_items` tidies them.
pub fn apply(&self, rows: &mut Vec<Row>) {
let _ = rows;
todo!("tp.T53")
rows.retain(|row| !self.hidden.contains(&row.command.id));
for row in rows.iter_mut() {
if let Some(color) = self.colors.get(&row.command.id) {
row.tint = Some(*color);
}
}
}
}
+21 -5
View File
@@ -137,8 +137,10 @@ struct Shared {
impl Dispatch {
/// The event for an item with `command`, its `shortcut` and [`Item::layout_shortcut`],
/// chosen with the modifiers `held` for a key-down (⌘, ⌃, ⌥, ⇧ as AppKit reports them) or
/// `None` for a mouse click, under the current gate. A click the gate allows on an app command
/// chosen by a key press (`key_down`) or a click, with the modifiers `mods` held (⌘, ⌃, ⌥, ⇧ as
/// AppKit reports them), under the current gate. A click whose `mods` include the
/// `alternate`'s runs the alternate's command instead; a key press never does. A click the
/// gate allows on an app command
/// (not a [`Builtin`]) also goes to the app's [`NativeMenu::on_command`] hook, before this
/// returns; when the hook ran it, the event is [`Event::Handled`].
pub fn chosen(
@@ -150,8 +152,12 @@ impl Dispatch {
mods: Mods,
alternate: Option<&Alternate>,
) -> Event {
let _ = alternate; // P3(top-w1): tp.T5
// P3(top-w1): tp.T5 — the old `held` argument: `Some` for a key-down, `None` for a click.
// Only a click swaps: a key equivalent belongs to the row's own command, so ⌥⇧⌘E on
// Merge Visible's ⇧⌘E stays the key the app's key handling sees.
let command = match alternate {
Some(alternate) if !key_down && alternate.selected_by(mods) => &alternate.command,
_ => command,
};
let held = key_down.then_some(mods);
let (gate, rules, hook) = {
let shared = self.lock();
@@ -206,6 +212,8 @@ pub struct NativeMenu {
paste: bool,
gate: Gate,
rules: ModalRules,
/// The revision of the rules last set; `None` before the first call.
rules_revision: Option<u64>,
dispatch: Dispatch,
/// The menus last laid out, before the gate greyed anything, and the gate they were last
/// synced with: a gate change re-syncs them without laying them out again.
@@ -231,6 +239,7 @@ impl NativeMenu {
paste: false,
gate: Gate::default(),
rules: ModalRules::default(),
rules_revision: None,
dispatch,
bar: None,
synced_gate: None,
@@ -247,10 +256,17 @@ impl NativeMenu {
/// The per-command rules under the gate ([`Gate::allows_under`]), set beside
/// [`NativeMenu::set_gate`] when they change: the items they forbid are greyed, and their
/// clicks and key equivalents dropped, as for the gate.
///
/// Rules hold a closure and can't be compared: the caller bumps [`ModalRules::revision`] when
/// they change, and a call with the revision it last set does nothing.
pub fn set_modal_rules(&mut self, rules: ModalRules) {
if self.rules_revision == Some(rules.revision) {
return;
}
self.rules_revision = Some(rules.revision);
self.dispatch.lock().rules = rules.clone();
self.rules = rules;
// Rules hold a closure and can't be compared: sync the greying again without laying out.
// Sync the greying again without laying out.
self.synced_gate = None;
}
+12
View File
@@ -50,6 +50,16 @@
//! the others go without a shortcut. Shortcuts the app binds outside its menus count too
//! ([`LayoutOptions::extra_shortcuts`]).
//!
//! **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.
//!
//! **Customization.** [`Customization`] drops the rows the user hid and tints the ones they
//! coloured, before [`from_items`].
//!
//! **Appearance.** [`ThemeMenu`] builds the Appearance submenu and the quick favourites rows, as
//! [`LanguageMenu`] does for languages.
//!
//! The labels the layout writes itself are English unless the app passes its translations in
//! [`LayoutOptions::label`].
//!
@@ -96,6 +106,7 @@ mod layout;
mod modal;
mod model;
mod palette;
mod theme;
pub mod mac;
@@ -115,6 +126,7 @@ pub use model::{
Alternate, 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};
#[cfg(feature = "screen-testing")]
/// The stories and words this crate registers, for the story tests.
+5 -4
View File
@@ -35,7 +35,7 @@ use craft_keymap::{Chord, CommandRef, Key, Mods};
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};
use crate::model::{Alternate, 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
@@ -115,6 +115,8 @@ struct Target {
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> {
@@ -189,7 +191,7 @@ fn lower_nodes(nodes: &[Node], targets: &mut HashMap<String, Target>) -> Vec<nat
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 });
targets.insert(id, Target { command: it.command.clone(), chord: it.shortcut, layout_shortcut: it.layout_shortcut, alternate: it.alternate.clone() });
native::Node::Item(item)
}
})
@@ -257,10 +259,9 @@ impl Backend for Native {
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 {
// P3(top-w1): tp.T7 — passes `Chosen` through; the target's `alternate` is not kept yet.
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, None);
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);
}
+12 -1
View File
@@ -212,6 +212,13 @@ impl Alternate {
pub fn new(mods: Mods, command: impl Into<CommandRef>) -> 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 plain item, or one with a checked state.
@@ -751,7 +758,11 @@ pub fn window_key(bar: &MenuBar) -> u64 {
fn hash_nodes(nodes: &[Node], h: &mut DefaultHasher) {
for n in nodes {
match n {
Node::Item(it) => ('i', it.command.key(), std::mem::discriminant(&it.kind), &it.shortcut, it.role, it.layout_shortcut).hash(h),
Node::Item(it) => {
('i', it.command.key(), std::mem::discriminant(&it.kind), &it.shortcut, it.role, it.layout_shortcut).hash(h);
// The native target table is swapped only on a rebuild, so the alternate is structure.
it.alternate.as_ref().map(|a| (a.command.key(), a.mods)).hash(h);
}
Node::Separator => '-'.hash(h),
Node::Submenu { label, children, role, .. } => {
('[', label, role).hash(h);
+154
View File
@@ -0,0 +1,154 @@
//! The Appearance menu: "Sync with System", the light and dark themes as radio rows, and a row
//! that steps to the next mode.
//!
//! The Mac layout puts the submenu in the app menu ([`crate::ItemRole::Appearance`]); Windows and
//! Linux keep it where the app puts it. Choosing a row reports [`THEME_COMMAND`] with the choice;
//! the app stores it and installs the theme. The app passes the theme rows, so this crate needs
//! no theme store.
use craft_keymap::CommandRef;
use craft_theme::ThemeId;
use crate::model::{Item, ItemRole, Node, tidy};
/// The command every Appearance row runs: `{"mode":"system"}`, `{"mode":"next"}` or
/// `{"theme": "<id>", "dark": <bool>}`.
pub const THEME_COMMAND: &str = "app.theme";
/// What an Appearance row chose.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ThemeChoice {
/// Follow the system's light or dark mode.
System,
/// A theme in its light (`dark: false`) or dark mode.
Theme {
/// The theme.
id: ThemeId,
/// Whether its dark mode is chosen.
dark: bool,
},
/// Step to the next mode.
NextMode,
}
impl ThemeChoice {
/// The choice a command made, `None` for any other command or an unknown parameter.
pub fn from_command(command: &CommandRef) -> Option<ThemeChoice> {
if command.id != THEME_COMMAND {
return None;
}
if let Some(mode) = command.params.get("mode") {
return match mode.as_str()? {
"system" => Some(ThemeChoice::System),
"next" => Some(ThemeChoice::NextMode),
_ => None,
};
}
let id = ThemeId::parse(command.params.get("theme")?.as_str()?).ok()?;
let dark = command.params.get("dark")?.as_bool()?;
Some(ThemeChoice::Theme { id, dark })
}
/// The command that makes this choice.
pub fn command(&self) -> CommandRef {
let params = match self {
ThemeChoice::System => serde_json::json!({ "mode": "system" }),
ThemeChoice::NextMode => serde_json::json!({ "mode": "next" }),
ThemeChoice::Theme { id, dark } => serde_json::json!({ "theme": id.as_str(), "dark": dark }),
};
CommandRef::with_params(THEME_COMMAND, params)
}
}
/// One theme row: the theme, its mode and its shown name.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ThemeRow {
/// The theme.
pub id: ThemeId,
/// Whether the row is the theme's dark mode.
pub dark: bool,
/// The name shown.
pub name: String,
}
impl ThemeRow {
/// A row for `id` in its light or dark mode, shown as `name`.
pub fn new(id: ThemeId, dark: bool, name: impl Into<String>) -> ThemeRow {
ThemeRow { id, dark, name: name.into() }
}
}
/// The Appearance submenu.
///
/// Rows: Sync with System, a separator, the light rows, a separator, the dark rows, a separator and
/// the mode toggle. A separator shows only between non-empty groups. The current choice is the
/// selected radio row (a check mark on macOS).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ThemeMenu {
rows: Vec<ThemeRow>,
current: ThemeChoice,
favorites: Vec<ThemeId>,
}
impl ThemeMenu {
/// The menu of `rows` (light and dark in the order shown), with `current` selected.
pub fn new(rows: Vec<ThemeRow>, current: ThemeChoice) -> Self {
ThemeMenu { rows, current, favorites: Vec::new() }
}
/// The themes [`ThemeMenu::favorite_items`] lists.
pub fn favorites(mut self, ids: &[ThemeId]) -> Self {
self.favorites = ids.to_vec();
self
}
fn row_item(&self, row: &ThemeRow) -> Node {
let on = matches!(&self.current, ThemeChoice::Theme { id, dark } if *id == row.id && *dark == row.dark);
Node::Item(Item::new(ThemeChoice::Theme { id: row.id.clone(), dark: row.dark }.command(), row.name.as_str()).radio(on))
}
/// The light rows, then the dark rows, that pass `keep`, with a separator between the groups.
fn mode_groups(&self, keep: impl Fn(&ThemeRow) -> bool) -> Vec<Node> {
let group = |dark: bool| self.rows.iter().filter(|r| r.dark == dark && keep(r)).map(|r| self.row_item(r)).collect::<Vec<_>>();
let mut nodes = group(false);
nodes.push(Node::Separator);
nodes.extend(group(true));
nodes
}
/// The rows as radio items running [`THEME_COMMAND`], with the mode toggle last.
pub fn items(&self, labels: &ThemeLabels) -> Vec<Node> {
let system = ThemeChoice::System;
let mut nodes = vec![Node::Item(Item::new(system.command(), labels.system.as_str()).radio(self.current == system)), Node::Separator];
nodes.extend(self.mode_groups(|_| true));
nodes.push(Node::Separator);
nodes.push(Node::Item(Item::new(ThemeChoice::NextMode.command(), labels.toggle.as_str())));
tidy(nodes)
}
/// The rows for a quick menu: the Appearance Settings row running `settings`, then the
/// favourite themes (see [`ThemeMenu::favorites`]), light then dark.
pub fn favorite_items(&self, labels: &ThemeLabels, settings: CommandRef) -> Vec<Node> {
let mut nodes = vec![Node::Item(Item::new(settings, labels.settings.as_str())), Node::Separator];
nodes.extend(self.mode_groups(|r| self.favorites.contains(&r.id)));
tidy(nodes)
}
/// The "Appearance" submenu, tagged [`crate::ItemRole::Appearance`].
pub fn submenu(&self, labels: &ThemeLabels) -> Node {
Node::submenu(labels.theme.as_str(), self.items(labels)).role(ItemRole::Appearance)
}
}
craft_ui::words! {
/// The Appearance menu's labels, English by default.
#[non_exhaustive]
pub struct ThemeLabels {
theme: "theme.menu" = "Appearance";
system: "theme.system" = "Sync with System";
toggle: "theme.toggle" = "Next Mode";
settings: "theme.settings" = "Appearance Settings…";
}
}
+37 -20
View File
@@ -4,8 +4,10 @@
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use craft_menu::{Backend, Builtin, ClipboardKeys, CommandRef, Dispatch, Event, Gate, LayoutOptions, MenuBar, NativeMenu, mac_layout, structure_key};
use craft_keymap::Mods;
use craft_menu::{Alternate, Backend, Builtin, Chord, ClipboardKeys, CommandRef, Dispatch, Event, Gate, LayoutOptions, MenuBar, NativeMenu, mac_layout, structure_key};
use craft_ui::contract::{Props as _, Show as _};
use craft_ui::testing::focus::key_release;
use craft_ui::testing::input::key_press;
@@ -261,31 +263,46 @@ fn shortcuts_the_layout_assigns_come_back_as_clicks() {
let cmd_q = chord("Cmd+Q");
let cmd_held = held([true, false, false, false]);
assert_eq!(chosen_held(&dispatch, &cmd("file.exit"), Some(&cmd_q), true, cmd_held), Event::Click("file.exit".into()));
assert_eq!(chosen_held(&dispatch, &cmd("file.quit"), Some(&cmd_q), false, cmd_held), Event::Key(cmd_q));
let chosen = |command: &CommandRef, chord: Option<&Chord>, layout_shortcut: bool, key_down: bool, mods: Mods| {
dispatch.chosen(command, chord, layout_shortcut, key_down, mods, None)
};
assert_eq!(chosen(&cmd("file.exit"), Some(&cmd_q), true, true, cmd_held), Event::Click("file.exit".into()));
assert_eq!(chosen(&cmd("file.quit"), Some(&cmd_q), false, true, cmd_held), Event::Key(cmd_q));
// ⇧ held on a ⌘R item: the key press that was made.
assert_eq!(chosen(&cmd("view.reload"), Some(&chord("Cmd+R")), false, true, held([true, false, false, true])), Event::Key(chord("Cmd+Shift+R")));
assert_eq!(chosen(&cmd("file.quit"), Some(&cmd_q), false, false, Mods::default()), Event::Click("file.quit".into()), "a mouse click");
assert_eq!(
chosen_held(&dispatch, &cmd("view.reload"), Some(&chord("Cmd+R")), false, held([true, false, false, true])),
Event::Key(chord("Cmd+Shift+R"))
);
assert_eq!(chosen_held(&dispatch, &cmd("file.quit"), Some(&cmd_q), false, None), Event::Click("file.quit".into()), "a mouse click");
assert_eq!(
chosen_held(&dispatch, &Builtin::Minimize.command(), Some(&chord("Ctrl+Cmd+M")), false, held([true, true, false, false])),
chosen(&Builtin::Minimize.command(), Some(&chord("Ctrl+Cmd+M")), false, true, held([true, true, false, false])),
Event::Click(Builtin::Minimize.command())
);
// ↩ inside the open menu: on a ⌘ item without ⌘ held, and on a bare tool key.
let enter = held([false; 4]);
assert_eq!(chosen_held(&dispatch, &cmd("file.quit"), Some(&cmd_q), false, enter), Event::Click("file.quit".into()));
assert_eq!(chosen_held(&dispatch, &cmd("tool.brush"), Some(&chord("B")), false, enter), Event::Click("tool.brush".into()));
assert_eq!(chosen(&cmd("file.quit"), Some(&cmd_q), false, true, enter), Event::Click("file.quit".into()));
assert_eq!(chosen(&cmd("tool.brush"), Some(&chord("B")), false, true, enter), Event::Click("tool.brush".into()));
}
// P3(top-w1): tp.T5 — the tests still speak the old `held` argument; phase 3 rewrites them for `key_down`, `mods` and `alternate`.
fn chosen_held(
dispatch: &craft_menu::Dispatch,
command: &CommandRef,
chord: Option<&craft_menu::Chord>,
layout_shortcut: bool,
held: Option<craft_keymap::Mods>,
) -> Event {
dispatch.chosen(command, chord, layout_shortcut, held.is_some(), held.unwrap_or_default(), None)
/// ⌥ on a row with an alternate runs the alternate, for a click only: the row's key equivalent
/// keeps its own command, so the app's key handling still sees the key that was made.
#[trial]
fn an_option_click_runs_the_rows_alternate() {
let (mut menu, _, _, dispatch) = driver();
let seen: Arc<Mutex<Vec<CommandRef>>> = Arc::default();
let hook_seen = seen.clone();
menu.on_command(Box::new(move |c| {
hook_seen.lock().unwrap().push(c.clone());
false
}));
let merge = cmd("layer.mergeVisible");
let stamp = cmd("layer.stampVisible");
let alternate = Alternate::new(Mods::ALT, stamp.clone());
let shortcut = chord("Cmd+Shift+E");
let click = |mods: Mods| dispatch.chosen(&merge, Some(&shortcut), false, false, mods, Some(&alternate));
assert_eq!(click(held([false, false, true, false])), Event::Click(stamp.clone()));
assert_eq!(*seen.lock().unwrap(), [stamp.clone()], "the hook sees the alternate");
assert_eq!(click(Mods::default()), Event::Click(merge.clone()), "no ⌥: the row's own command");
assert_eq!(click(held([false, false, false, true])), Event::Click(merge.clone()), "another modifier is not the alternate's");
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");
}
+3 -3
View File
@@ -7,9 +7,9 @@ pub fn chord(s: &str) -> Chord {
Chord::parse(s).unwrap()
}
/// The modifiers held for a key-down: ⌘, ⌃, ⌥, ⇧.
pub fn held([cmd, ctrl, alt, shift]: [bool; 4]) -> Option<Mods> {
Some(Mods { cmd, ctrl, alt, shift })
/// The modifiers held: ⌘, ⌃, ⌥, ⇧.
pub fn held([cmd, ctrl, alt, shift]: [bool; 4]) -> Mods {
Mods { cmd, ctrl, alt, shift }
}
pub fn typing(text_editing: bool) -> Gate {
+30 -1
View File
@@ -1,6 +1,10 @@
//! The table's model through the dialog: which rows are listed and which count as conflicts.
use craft_keymap::{Binding, CommandRef, Platform, Policy};
use std::sync::Arc;
use craft_host::{AppInfo, Host};
use craft_keymap::{Binding, CommandDef, CommandRef, Keymap, Platform, Policy, Scope, Scopes};
use craft_ui::contract::Role;
use craft_ui::testing::trial;
use super::fixture::{self, Rig};
@@ -29,3 +33,28 @@ fn every_row_that_can_take_a_shortcut_has_its_add_button() {
assert!(rig.has(&add), "{label:?} has no add button; buttons {:?}", rig.names_with(craft_ui::contract::Role::BUTTON, "Add a shortcut"));
}
}
/// A query typed in capitals finds the row: the search folds the dotted capital İ to `i`, where a lowercase fold
/// gives `i` plus a combining dot and finds nothing. The English alias finds it too.
#[trial]
fn the_search_folds_dotted_capitals() {
let (i18n, _) = craft_i18n::I18n::from_owned([("az".to_owned(), String::new(), String::new())], &["az"]);
let lang = i18n.from_code("az").expect("az is offered");
let host = Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).i18n(Arc::new(i18n)).lang(lang).build());
let path: Vec<String> = ["Image", "Image Size…"].iter().map(|s| (*s).to_owned()).collect();
let size = CommandDef::new("image.size", "Şəkil ölçüsü…", Scope::app()).with_path(path).with_alias("Image Size");
let other = CommandDef::new("file.save", "Saxla", Scope::app());
let listed = |query: &str| {
let keymap = Keymap::new(vec![size.clone(), other.clone()], Scopes::new(), Platform::Mac);
let mut rig = Rig::new(keymap, fixture::options(), None);
rig.fixture.host(host.clone());
rig.pass();
let field = rig.find("Search:");
rig.fixture.click(&field);
rig.fixture.type_text(query);
rig.fixture.idle(2);
(!rig.names_with(Role::ROW, "Şəkil ölçüsü").is_empty(), !rig.names_with(Role::ROW, "Saxla").is_empty())
};
assert_eq!(listed("ŞƏKİL ÖLÇÜSÜ"), (true, false), "capitals with the dotted İ");
assert_eq!(listed("IMAGE SIZE"), (true, false), "the English alias");
}
+210
View File
@@ -0,0 +1,210 @@
//! The macOS menu bar end to end, on the main thread (`harness = false`): install the sample bar through
//! `craft_menu::mac::install`, read AppKit's menu bar back, update it in place, then choose items the ways AppKit
//! can: a key equivalent (a real ⌘R key-down through `-[NSMenu performKeyEquivalent:]`) must reach egui as the key
//! press it was, a click (`-[NSMenu performActionForItemAtIndex:]`) must come back from `take_clicks`, also when the
//! click is ↩ inside the open menu, and a click made with ⌥ held on a row with an alternate runs the alternate.
// The one sample bar the `it` trials use. This binary needs only `sample()` and its constructors.
#[cfg(target_os = "macos")]
#[allow(dead_code)]
#[path = "it/sample.rs"]
mod sample;
#[cfg(target_os = "macos")]
fn main() {
use craft_keymap::Mods;
use craft_menu::{Alternate, CommandRef, Document, Gate, Item, LayoutOptions, MenuRole, Node, mac, mac_layout};
use craft_ui::testing::Frames;
use objc2::MainThreadMarker;
use objc2::rc::Retained;
use objc2_app_kit::{NSApplication, NSEvent, NSEventMask, NSEventModifierFlags, NSEventSubtype, NSEventType, NSMenu};
use objc2_foundation::{NSPoint, NSString};
// Without a harness nothing answers cargo-nextest's `--list`, so it ran the whole test as its listing and failed
// on the output. List the one test, as libtest's terse format would, and nothing for `--ignored` (nextest asks
// twice). Running it passes `<name> --exact`, which falls through to the test below.
let args: Vec<String> = std::env::args().collect();
if args.iter().any(|a| a == "--list") {
if !args.iter().any(|a| a == "--ignored") {
println!("mac_appkit: test");
}
return;
}
let Some(mtm) = MainThreadMarker::new() else {
println!("mac_appkit: harness = false runs on the main thread");
std::process::exit(1);
};
let nsapp = NSApplication::sharedApplication(mtm);
nsapp.finishLaunching();
let titles = |menu: &NSMenu| -> Vec<String> {
(0..menu.numberOfItems()).filter_map(|i| menu.itemAtIndex(i)).filter(|it| !it.isSeparatorItem()).map(|it| it.title().to_string()).collect()
};
let submenu = |menu: &NSMenu, title: &str| -> Retained<NSMenu> {
(0..menu.numberOfItems())
.filter_map(|i| menu.itemAtIndex(i))
.find(|it| it.title().to_string() == title)
.and_then(|it| it.submenu())
.unwrap_or_else(|| panic!("no {title} submenu in {:?}", titles(menu)))
};
let index = |menu: &NSMenu, title: &str| -> isize {
(0..menu.numberOfItems())
.find(|&i| menu.itemAtIndex(i).is_some_and(|it| it.title().to_string() == title))
.unwrap_or_else(|| panic!("no {title} in {:?}", titles(menu)))
};
let main_menu = || nsapp.mainMenu().expect("a main menu");
// Make `event` AppKit's current event, as the run loop does before dispatching it.
let dequeue = |event: &NSEvent| {
nsapp.postEvent_atStart(event, true);
let mode = NSString::from_str("kCFRunLoopDefaultMode");
let got = nsapp.nextEventMatchingMask_untilDate_inMode_dequeue(NSEventMask::Any, None, &mode, true).expect("the posted event");
assert_eq!(got.r#type(), event.r#type());
got
};
let key_down = |chars: &str, code: u16, flags: NSEventModifierFlags| {
let s = NSString::from_str(chars);
NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
NSEventType::KeyDown,
NSPoint::new(0.0, 0.0),
flags,
0.0,
0,
None,
&s,
&s,
false,
code,
)
.expect("a key event")
};
// The current event of a mouse click on a menu row: not a key-down, with `flags` held.
let other = |flags: NSEventModifierFlags| {
NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
NSEventType::ApplicationDefined,
NSPoint::new(0.0, 0.0),
flags,
0.0,
0,
None,
NSEventSubtype::ApplicationActivated.0,
0,
0,
)
.expect("an application-defined event")
};
// The sample bar with View › Rulers on ⌘R, and Merge Visible with Stamp Visible as its ⌥ alternate.
let bar = |documents: usize| {
let mut bar = sample::sample(false, true);
if let Some(view) = bar.menus.iter_mut().find(|m| m.role == MenuRole::View) {
view.children.push(Node::Item(Item::new("view.rulers", "Rulers").shortcut(sample::chord("Cmd+R"))));
view.children.push(Node::Item(Item::new("layer.mergeVisible", "Merge Visible").alternate(Alternate::new(Mods::ALT, "layer.stampVisible"))));
}
for n in 1..documents {
bar.documents.push(Document::new(format!("doc.{n}"), format!("Untitled-{}", n + 1)));
}
bar
};
let options = LayoutOptions::new("Sample");
let layout = |documents: usize| mac_layout(&bar(documents), &options);
let mut frames = Frames::new();
frames.ctx.set_os(egui::os::OperatingSystem::Mac);
let Some(mut menu) = mac::install(&frames.ctx, &layout(1).bar) else {
println!("mac_appkit: the menu bar did not install");
std::process::exit(1);
};
// One frame, as an app runs it: poll before and after, run the clicks. Returns what egui saw of the input and
// the commands the menu returned.
let pass = |menu: &mut craft_menu::NativeMenu, frames: &mut Frames| -> (Vec<egui::Event>, Vec<CommandRef>) {
menu.poll(&frames.ctx);
let mut seen = Vec::new();
let mut clicks = Vec::new();
frames.frame(vec![], |ui| {
seen = ui.ctx().input(|input| input.events.clone());
clicks = menu.take_clicks(ui.ctx());
});
menu.poll(&frames.ctx);
(seen, clicks)
};
// The Mac layout, as AppKit has it.
let main = main_menu();
let tops: Vec<String> = (0..main.numberOfItems()).filter_map(|i| main.itemAtIndex(i)?.submenu()).map(|m| m.title().to_string()).collect();
assert_eq!(tops, ["Sample", "File", "Edit", "View", "Window", "Help"]);
let app_menu = submenu(&main, "Sample");
let quit = app_menu.itemAtIndex(index(&app_menu, "Quit Sample")).expect("Quit");
assert_eq!(quit.keyEquivalent().to_string(), "q");
assert_eq!(quit.keyEquivalentModifierMask(), NSEventModifierFlags::Command);
assert!(!titles(&submenu(&main, "File")).iter().any(|n| n == "Exit"), "Exit moved to the app menu as Quit");
assert_eq!(nsapp.windowsMenu().map(|m| m.title().to_string()).as_deref(), Some("Window"), "AppKit knows the Window menu");
assert_eq!(nsapp.helpMenu().map(|m| m.title().to_string()).as_deref(), Some("Help"), "AppKit knows the Help menu");
// A gate change greys File › New in place: same NSMenu, no rebuild.
let new_enabled = |bar: &NSMenu| {
let file = submenu(bar, "File");
file.itemAtIndex(index(&file, "New")).expect("New").isEnabled()
};
assert!(new_enabled(&main), "no dialog: New is enabled");
menu.set_gate(Gate::default().modal(true));
menu.sync_with(1, || layout(1));
assert!(Retained::as_ptr(&main) == Retained::as_ptr(&main_menu()), "the gate updated the menu, not rebuilt it");
assert!(!new_enabled(&main_menu()), "a dialog greys New");
menu.set_gate(Gate::default());
menu.sync_with(1, || layout(1));
assert!(new_enabled(&main_menu()), "New is enabled again");
// A key equivalent: ⌘R reaches egui as the key press ⌘R, once, and is no click.
let press = dequeue(&key_down("r", 15, NSEventModifierFlags::Command));
assert!(main_menu().performKeyEquivalent(&press), "⌘R is View › Rulers' key equivalent");
let (seen, clicks) = pass(&mut menu, &mut frames);
let keys: Vec<_> =
seen.iter().filter_map(|e| if let egui::Event::Key { key, pressed, modifiers, .. } = e { Some((*key, *pressed, modifiers.command)) } else { None }).collect();
// AppKit took only the key-down; winit delivers the key-up itself.
assert_eq!(keys, [(egui::Key::R, true, true)], "the key press");
assert!(clicks.is_empty(), "a key equivalent is no click: {clicks:?}");
// A click: View › Rulers chosen with the mouse comes back as a click, and no key press reaches egui.
let view = submenu(&main_menu(), "View");
let rulers = index(&view, "Rulers");
dequeue(&other(NSEventModifierFlags::empty()));
view.performActionForItemAtIndex(rulers);
let (seen, clicks) = pass(&mut menu, &mut frames);
assert!(!seen.iter().any(|e| matches!(e, egui::Event::Key { .. })), "a click is no key press: {seen:?}");
assert_eq!(clicks, [CommandRef::new("view.rulers")], "the click");
// ↩ inside the open menu is a key-down without ⌘: still a click.
dequeue(&key_down("\r", 36, NSEventModifierFlags::empty()));
view.performActionForItemAtIndex(rulers);
let (seen, clicks) = pass(&mut menu, &mut frames);
assert!(!seen.iter().any(|e| matches!(e, egui::Event::Key { .. })), "↩ in the menu is a click: {seen:?}");
assert_eq!(clicks, [CommandRef::new("view.rulers")], "↩ on Rulers");
// A row with an alternate: a plain click runs the row's command, a click with ⌥ held runs the alternate.
let merge = index(&view, "Merge Visible");
dequeue(&other(NSEventModifierFlags::empty()));
view.performActionForItemAtIndex(merge);
assert_eq!(pass(&mut menu, &mut frames).1, [CommandRef::new("layer.mergeVisible")], "no ⌥: the row's own command");
dequeue(&other(NSEventModifierFlags::Option));
view.performActionForItemAtIndex(merge);
assert_eq!(pass(&mut menu, &mut frames).1, [CommandRef::new("layer.stampVisible")], "⌥-click: the alternate");
// Window ends with the open documents. Opening one rebuilds only the Window menu, which AppKit still knows as
// its Window menu; choosing a row brings that document forward.
menu.sync_with(2, || layout(2));
assert!(Retained::as_ptr(&main) == Retained::as_ptr(&main_menu()), "a new document rebuilt only the Window menu");
let window = submenu(&main_menu(), "Window");
assert!(nsapp.windowsMenu().is_some_and(|w| Retained::as_ptr(&w) == Retained::as_ptr(&window)), "AppKit knows the new Window menu");
let rows = [window.numberOfItems() - 2, window.numberOfItems() - 1];
let shown: Vec<String> = rows.iter().filter_map(|&i| window.itemAtIndex(i)).map(|it| it.title().to_string()).collect();
assert_eq!(shown, ["Untitled-1", "Untitled-2"], "the documents, after Bring All to Front: {:?}", titles(&window));
dequeue(&other(NSEventModifierFlags::empty()));
window.performActionForItemAtIndex(rows[1]);
assert_eq!(pass(&mut menu, &mut frames).1, [CommandRef::new("doc.1")], "choosing the second row brings that document forward");
println!("mac_appkit: ok");
}
#[cfg(not(target_os = "macos"))]
fn main() {}
+3 -2
View File
@@ -37,7 +37,8 @@ reads the platform once and calls it.
### Override
`<PREFIX>_TITLEBAR` wins over the setting. With the default prefix `CRAFT`: `CRAFT_TITLEBAR=app`
`<PREFIX>_TITLEBAR` wins over the setting; `<PREFIX>_CAPTION_STYLE` and `<PREFIX>_CAPTION_LAYOUT` do the
same for the caption buttons' style and layout. With the default prefix `CRAFT`: `CRAFT_TITLEBAR=app`
forces the app's bar (also on tiling compositors), `=system` or `=desktop` forces the native frame.
Apps pass their own prefix (`Prefix::new("PDFCRAFT")` reads `PDFCRAFT_TITLEBAR`).
When `<PREFIX>_TITLEBAR` is unset, `CRAFT_TITLEBAR` applies, so one variable covers every app. `Decision::overridden` reports `Some(true)` or `Some(false)` when the variable decided.
@@ -138,7 +139,7 @@ description: `Bar` of `Menu`s of `Node`s (`Item { id, label, enabled, checked, s
separators, and the platform's own items such as Services and Zoom). `NativeBar::install` makes it the
application's menu bar, `NativeBar::apply` keeps it in step (a changed `structure` key rebuilds, a changed
`windows` key rebuilds only the Windows menu, anything else updates in place), and the `Handler` set with
`NativeBar::set_handler` receives each chosen item's `id` and, for a key equivalent, the modifiers held.
`NativeBar::set_handler` receives each chosen item's `id`, the modifiers held and whether a key press chose it.
`install_app_menu` installs a minimal app menu whose Quit reports to a handler. Off macOS (and without the
feature) every call does nothing, so callers need no platform check. craft-menu lowers its menu model to
this description.
+5 -4
View File
@@ -3,7 +3,7 @@
//! The app describes its menus as a [`Bar`] (titles, items with a unique `id`, labels, check state
//! and key equivalents). [`NativeBar::install`] makes it the application's menu bar and
//! [`NativeBar::apply`] keeps it in step with later descriptions. A chosen item reaches the app's
//! [`Handler`] with the item's `id` and, for a key-down, the modifiers held. Nothing here knows
//! [`Handler`] with the item's `id`, whether a key press chose it and the modifiers held. Nothing here knows
//! what an item runs.
//!
//! Only macOS has an application menu bar (with the `appkit` feature, built on `muda`). On other
@@ -33,8 +33,9 @@ use other as imp;
pub use imp::{hide_app, hide_other_apps, install_app_menu, system_title};
/// Called when an item is chosen: the item's `id` and how it was chosen ([`Chosen`]). The platform calls it between frames from the event that chose the item, on the main
/// thread. An id the app does not know belongs to a platform item (Services, Zoom, …), which the
/// Called when an item is chosen: the item's `id` and how it was chosen ([`Chosen`]: key press or
/// click, and the modifiers held either way). The platform calls it between frames from the event
/// that chose the item, on the main thread. An id the app does not know belongs to a platform item (Services, Zoom, …), which the
/// platform already handled.
pub type Handler = Arc<dyn Fn(&str, Chosen) + Send + Sync>;
@@ -48,7 +49,7 @@ pub struct Chosen {
pub held: Held,
}
/// The modifier keys held with a key-down.
/// The modifier keys held.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Held {
/// Command (⌘).
+14 -12
View File
@@ -6,7 +6,8 @@
//! A change of the windows key rebuilds only the Windows menu: AppKit adds its own items to that
//! menu (window tiling, the window list), so muda can't insert rows there by position.
//! - A chosen item is a click or a key equivalent: AppKit's current event says which, and the
//! handler gets the modifiers held for a key-down (AppKit may match ⌘R to a ⇧⌘R item).
//! handler gets whether a key press chose it and the modifiers held, for a click too (⌥ on a
//! row with an alternate; AppKit may match ⌘R to a ⇧⌘R item).
//! - The process has one muda menu event handler, set by the first [`Installed::set_handler`] or
//! [`install_app_menu`]; each call points it at its own handler.
//! - A check or radio item: AppKit (muda) flips its state when it is chosen. The next `apply` sets
@@ -55,24 +56,25 @@ fn route_events(handler: Handler) {
/// The menu event handler. AppKit calls it on the main thread, from the event that chose the
/// item: a key equivalent is a key-down, a click a mouse-up (or ↩ inside the open menu).
fn handle_event(e: MenuEvent) {
let held = MainThreadMarker::new()
// Without a current event the item was chosen by a call, not by the user: a click, no modifiers.
let chosen = MainThreadMarker::new()
.and_then(|mtm| NSApplication::sharedApplication(mtm).currentEvent())
.filter(|ev| ev.r#type() == NSEventType::KeyDown)
.map(|ev| {
let flags = ev.modifierFlags();
Held {
command: flags.contains(NSEventModifierFlags::Command),
control: flags.contains(NSEventModifierFlags::Control),
option: flags.contains(NSEventModifierFlags::Option),
shift: flags.contains(NSEventModifierFlags::Shift),
Chosen {
key_down: ev.r#type() == NSEventType::KeyDown,
held: Held {
command: flags.contains(NSEventModifierFlags::Command),
control: flags.contains(NSEventModifierFlags::Control),
option: flags.contains(NSEventModifierFlags::Option),
shift: flags.contains(NSEventModifierFlags::Shift),
},
}
});
})
.unwrap_or_default();
// A copy, so nothing is locked while the app's handler runs.
let handler = lock(&ROUTE).clone();
if let Some(handler) = handler {
let mut chosen = Chosen::default(); // P3(top-w1): tp.T6
chosen.key_down = held.is_some();
chosen.held = held.unwrap_or_default();
handler(e.id.as_ref(), chosen);
}
}