diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 20effdb29..8d978dd18 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -11,8 +11,10 @@ #[cfg(feature = "screen-testing")] mod stories; +use craft_host::target::Os; +use craft_i18n::Words; use craft_keymap::{CommandRef, Platform}; -use craft_ui::contract::{MemoProps, MemoView, Show as _, Stateless}; +use craft_ui::contract::{MemoProps, MemoView, Show as _, Stateless, Tracked}; use craft_ui::menu::{MenuBar as Bar, MenuHelp, MenuTitle}; use craft_ui::runtime::env::{Env, Label}; use egui::{Rect, Ui}; @@ -87,7 +89,7 @@ pub type EnglishFn = fn(Labeled<'_>) -> Option; #[derive(craft_ui::contract::Pattern)] #[pattern(probe(MenuBarUi<'static, EnglishFn>))] pub struct MenuBarUi<'a, E = EnglishFn> { - bar: &'a MenuBar, + bar: &'a Tracked, /// The platform set with [`target`](Self::target); the shell's when none is. target: Option, english: Option>, @@ -99,7 +101,7 @@ pub struct MenuBarUi<'a, E = EnglishFn> { /// Every input of the bar's view. #[derive(MemoProps)] struct BarProps<'a, #[memo_props(stateless)] E> { - bar: &'a MenuBar, + bar: &'a Tracked, target: Target, english: Option>, preferred: &'a [(&'a str, char)], @@ -110,7 +112,7 @@ struct BarProps<'a, #[memo_props(stateless)] E> { impl<'a> MenuBarUi<'a> { /// The bar for `bar`, already laid out ([`crate::layout`]), on the shell's platform ([`Target::of_shell`]). - pub fn new(bar: &'a MenuBar) -> MenuBarUi<'a> { + pub fn new(bar: &'a Tracked) -> MenuBarUi<'a> { MenuBarUi { bar, target: None, english: None, preferred: &[], keyboard: None, help_search: false } } } @@ -184,13 +186,32 @@ fn show_bar) -> Option + Copy + 'static>(props: &mut B }); let english: Option<&EnglishHook<'_>> = hook.as_ref().map(|hook| hook as &EnglishHook<'_>); let rows = Rows::new(props.target).english(english).preferred(props.preferred); - let labels = - rows.labels(&props.bar.menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| rows.english_of(Labeled::Title(&menu.title))); - let shared = &rows; - let titles: Vec> = - props.bar.menus.iter().zip(labels).map(|(menu, label)| MenuTitle::new(label, move |ui| shared.show(ui, &menu.children))).collect(); + let env = Env::of(ui); + let os = env.view().shell().os; + // The text of every menu is worked out once for these inputs and kept: a pass that shows an open menu again writes none of it. + let key = LabelKey { + bar: props.bar, + target: props.target, + os, + preferred: props.preferred, + english: props.english, + words: &env.words, + keymap: craft_ui::runtime::commands::keymap_generation(ui.ctx()), + }; + let labels = craft_ui::runtime::derived::derived(ui.ctx(), ui.scope_id().with("menu-labels"), &key, || { + rows.bar_labels(&props.bar.menus, keymap_platform(props.target, os)) + }); + let (shared, labels) = (&rows, &*labels); + let titles: Vec> = props + .bar + .menus + .iter() + .zip(&labels.titles) + .zip(&labels.menus) + .map(|((menu, title), level)| MenuTitle::new(title.clone(), move |ui| shared.show(ui, &menu.children, level))) + .collect(); // Collecting the search's commands walks every row of every menu: the bar does it only while Help is open. - let bar_model = props.bar; + let bar_model: &MenuBar = props.bar; let entries = move || entries_of(bar_model, english); let mut bar = Bar::new(props.label.clone(), titles).keyboard(props.keyboard); if let Some(menu) = props.help { @@ -198,3 +219,16 @@ fn show_bar) -> Option + Copy + 'static>(props: &mut B } MenuBarOutput { titles: bar.show(ui).titles } } + +/// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the mnemonic and English +/// hooks, the language and the keymap. +#[derive(MemoProps)] +struct LabelKey<'a, #[memo_props(stateless)] E> { + bar: &'a Tracked, + target: Target, + os: Os, + preferred: &'a [(&'a str, char)], + english: Option>, + words: &'a Words, + keymap: u64, +} diff --git a/crates/menu/src/bar/stories.rs b/crates/menu/src/bar/stories.rs index a48970a67..b21cde03a 100644 --- a/crates/menu/src/bar/stories.rs +++ b/crates/menu/src/bar/stories.rs @@ -1,11 +1,14 @@ //! Stories of the in-window bar over a small model. +use std::sync::Arc; + +use craft_ui::contract::Tracked; use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story}; use egui::Ui; use crate::{Document, Item, LayoutOptions, Menu, MenuBar, MenuBarUi, MenuRole, Node, Target, layout}; -fn model() -> MenuBar { +fn build() -> MenuBar { let item = |id: &str, label: &str| Item::new(id, label); let bar = MenuBar { menus: vec![ @@ -37,9 +40,15 @@ fn model() -> MenuBar { layout(&bar, Target::Linux, &LayoutOptions::new("Sample")).bar } +/// The story's model, kept in the story's memory: a model made again each pass is a new source, and the bar would run each time. +fn model(ui: &Ui) -> Arc> { + let id = ui.scope_id().with("model"); + ui.data_mut(|data| data.get_temp_mut_or_insert_with(id, || Arc::new(Tracked::new(build()))).clone()) +} + #[story(MenuBarUi<'static>, covers = [Default], drive = Drive::Never)] fn menu_bar_ui(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - MenuBarUi::new(&model()).target(Target::Linux).show(ui); + MenuBarUi::new(&model(ui)).target(Target::Linux).show(ui); StoryOutput::default() } @@ -51,12 +60,12 @@ fn open_window(fixture: &mut Fixture) { #[story(MenuBarUi<'static>, covers = [Open], drive = Drive::Custom(open_window))] fn menu_bar_ui_with_documents(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - MenuBarUi::new(&model()).target(Target::Linux).show(ui); + MenuBarUi::new(&model(ui)).target(Target::Linux).show(ui); StoryOutput::default() } #[story(MenuBarUi<'static>, covers = [], drive = Drive::Never)] fn menu_bar_ui_with_help_search(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - MenuBarUi::new(&model()).target(Target::Linux).help_search(true).show(ui); + MenuBarUi::new(&model(ui)).target(Target::Linux).help_search(true).show(ui); StoryOutput::default() } diff --git a/crates/menu/src/context.rs b/crates/menu/src/context.rs index 7e1dfd667..6f6f3ac28 100644 --- a/crates/menu/src/context.rs +++ b/crates/menu/src/context.rs @@ -26,7 +26,32 @@ use crate::model::{Builtin, Item, ItemKind, Node}; /// 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]) { - Rows::new(Target::of_shell(Env::of(ui).view().shell())).show(ui, nodes); + let rows = Rows::new(Target::of_shell(Env::of(ui).view().shell())); + let labels = rows.level_labels(nodes, rows.platform(ui)); + rows.show(ui, nodes, &labels); +} + +/// The text a menu level shows for its nodes, parallel to them: what [`LevelLabels::build`] works out once for a +/// model, so a pass that shows the menu again writes none of it. +#[derive(Debug, Default, PartialEq)] +pub(crate) struct LevelLabels { + rows: Vec, +} + +/// One node's text: its label as the menu shows it (markers escaped, mnemonic marked), the item's shortcut text, and the +/// text of a submenu's own level. Separators and AppKit's items hold empty text. +#[derive(Debug, Default, PartialEq)] +struct RowLabels { + label: String, + shortcut: Option, + children: LevelLabels, +} + +/// The text of a bar: its titles as the bar shows them and the text of each menu's rows. +#[derive(Debug, PartialEq)] +pub(crate) struct BarLabels { + pub(crate) titles: Vec, + pub(crate) menus: Vec, } /// How the rows of a menu are written: the target that names the shortcuts, the app's English labels and its @@ -120,12 +145,35 @@ impl<'a> Rows<'a> { .collect() } - /// Shows `nodes` as the rows of the menu body `ui` is in. - pub(crate) fn show(&self, ui: &mut Ui, nodes: &[Node]) { + /// The text of `nodes` and of every submenu below them, with shortcuts written for `platform`. + pub(crate) fn level_labels(&self, nodes: &[Node], platform: Platform) -> LevelLabels { let labels = self.node_labels(nodes); - for (node, label) in nodes.iter().zip(labels) { + let rows = nodes + .iter() + .zip(labels) + .map(|(node, label)| match node { + Node::Item(item) => { + RowLabels { label, shortcut: item.shortcut.as_ref().map(|chord| chord.display(platform)), children: LevelLabels::default() } + } + Node::Submenu { children, .. } => RowLabels { label, shortcut: None, children: self.level_labels(children, platform) }, + Node::Separator | Node::Standard { .. } => RowLabels::default(), + }) + .collect(); + LevelLabels { rows } + } + + /// The text of a whole bar: the titles and each menu's rows. + pub(crate) fn bar_labels(&self, menus: &[crate::model::Menu], platform: Platform) -> BarLabels { + let titles = self.labels(menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| self.english_of(Labeled::Title(&menu.title))); + BarLabels { titles, menus: menus.iter().map(|menu| self.level_labels(&menu.children, platform)).collect() } + } + + /// Shows `nodes` as the rows of the menu body `ui` is in, with their `labels`. + pub(crate) fn show(&self, ui: &mut Ui, nodes: &[Node], labels: &LevelLabels) { + for (node, text) in nodes.iter().zip(&labels.rows) { + let label = text.label.clone(); match node { - Node::Item(item) => self.item(ui, item, label), + Node::Item(item) => self.item(ui, item, label, text.shortcut.clone()), Node::Separator => { Divider::horizontal().show(ui); } @@ -133,7 +181,7 @@ impl<'a> Rows<'a> { if is_dead(children) { MenuItem::submenu(label).enabled(false).show(ui); } else { - Menu::submenu_row(ui, label, |ui, _| self.show(ui, children)); + Menu::submenu_row(ui, label, |ui, _| self.show(ui, children, &text.children)); } } Node::Standard { .. } => {} @@ -141,9 +189,7 @@ impl<'a> Rows<'a> { } } - fn item(&self, ui: &mut Ui, item: &Item, label: String) { - let platform = self.platform(ui); - let shortcut = item.shortcut.as_ref().map(|chord| chord.display(platform)); + fn item(&self, ui: &mut Ui, item: &Item, label: String, shortcut: Option) { match Builtin::of(&item.command) { Some(Builtin::Quit) => { if local(ui, item, label, shortcut).ran { @@ -162,7 +208,7 @@ impl<'a> Rows<'a> { } /// The platform whose key names the shortcut column shows. - fn platform(&self, ui: &Ui) -> Platform { + pub(crate) fn platform(&self, ui: &Ui) -> Platform { keymap_platform(self.target, Env::of(ui).view().shell().os) } } diff --git a/crates/menu/src/keymap.rs b/crates/menu/src/keymap.rs index fd6816bfb..896c2d3ee 100644 --- a/crates/menu/src/keymap.rs +++ b/crates/menu/src/keymap.rs @@ -2,8 +2,9 @@ //! enabled and checked update. use craft_keymap::{CommandKind, CommandRef, Keymap}; +use craft_ui::contract::Tracked; -use crate::model::{Builtin, ItemKind, MenuBar}; +use crate::model::{Builtin, Item, ItemKind, MenuBar}; /// Give each item the shortcut its command has in `keymap`, the user's overrides included, and /// make the items of toggle commands (kind [`CommandKind::Toggle`]) check items. @@ -12,14 +13,23 @@ use crate::model::{Builtin, ItemKind, MenuBar}; /// one in its home scope first, so a chord another command wins is not shown. A command with no /// such binding loses its shortcut, and an item whose command the keymap doesn't know keeps its /// own. A toggle's check item keeps its checked state; radio items stay radio items. Call it on -/// the app's bar, before the layout. -pub fn apply_keymap(bar: &mut MenuBar, keymap: &Keymap) { - bar.for_each_item_mut(|it| { - let Some(bindable) = keymap.bindable(&it.command) else { return }; - it.shortcut = keymap.shown_chord(&it.command); - if bindable.kind == CommandKind::Toggle && it.kind == ItemKind::Plain { - it.kind = ItemKind::Check(false); - } +/// the app's bar, before the layout. The bar is written, and its revision moves, only when an item changes. +pub fn apply_keymap(bar: &mut Tracked, keymap: &Keymap) { + let wanted = |it: &Item| { + let bindable = keymap.bindable(&it.command)?; + let kind = if bindable.kind == CommandKind::Toggle && it.kind == ItemKind::Plain { ItemKind::Check(false) } else { it.kind }; + Some((keymap.shown_chord(&it.command), kind)) + }; + if !bar.items().into_iter().any(|it| wanted(it).is_some_and(|(shortcut, kind)| shortcut != it.shortcut || kind != it.kind)) { + return; + } + bar.edit(|bar| { + bar.for_each_item_mut(|it| { + if let Some((shortcut, kind)) = wanted(it) { + it.shortcut = shortcut; + it.kind = kind; + } + }); }); } @@ -56,20 +66,38 @@ impl Default for ItemState { /// Set every item's enabled and checked state from `state`, called once per item of the app's /// commands. `checked: Some(..)` makes a plain item a check item and sets a radio item's -/// selection. The built-in items and the open documents are left alone. -pub fn apply_state(bar: &mut MenuBar, mut state: impl FnMut(&CommandRef) -> ItemState) { - let documents: Vec = bar.documents.iter().map(|d| d.command.clone()).collect(); - bar.for_each_item_mut(|it| { - if Builtin::of(&it.command).is_some() || documents.contains(&it.command) { - return; - } - let s = state(&it.command); - it.enabled = s.enabled; - if let Some(on) = s.checked { - it.kind = match it.kind { - ItemKind::Radio(_) => ItemKind::Radio(on), - ItemKind::Plain | ItemKind::Check(_) => ItemKind::Check(on), +/// selection. The built-in items and the open documents are left alone. The bar is written, and +/// its revision moves, only when an item changes. +pub fn apply_state(bar: &mut Tracked, mut state: impl FnMut(&CommandRef) -> ItemState) { + let skipped = |it: &Item| Builtin::of(&it.command).is_some() || bar.is_document(&it.command); + // One entry per item, depth first, as `for_each_item_mut` walks them. + let wanted: Vec> = bar + .items() + .into_iter() + .map(|it| { + if skipped(it) { + return None; + } + let s = state(&it.command); + let kind = match (s.checked, it.kind) { + (None, kind) => kind, + (Some(on), ItemKind::Radio(_)) => ItemKind::Radio(on), + (Some(on), ItemKind::Plain | ItemKind::Check(_)) => ItemKind::Check(on), }; - } + Some((s.enabled, kind)) + }) + .collect(); + let differs = bar.items().into_iter().zip(&wanted).any(|(it, want)| want.is_some_and(|(enabled, kind)| enabled != it.enabled || kind != it.kind)); + if !differs { + return; + } + bar.edit(|bar| { + let mut wanted = wanted.into_iter(); + bar.for_each_item_mut(|it| { + if let Some((enabled, kind)) = wanted.next().flatten() { + it.enabled = enabled; + it.kind = kind; + } + }); }); } diff --git a/crates/menu/tests/it/from_items.rs b/crates/menu/tests/it/from_items.rs new file mode 100644 index 000000000..7d1783ae5 --- /dev/null +++ b/crates/menu/tests/it/from_items.rs @@ -0,0 +1,116 @@ +//! `from_items` groups flat rows by menu path in one pass; the tree is the one the row-by-row walk made: submenus where their +//! first row is, separators tidied at every depth. + +use craft_menu::{CommandRef, MenuBar, Node, Row, from_items, tidy}; +use craft_ui::testing::trial; + +/// The row-by-row walk `from_items` replaced: every submenu filters all rows of its level again. +fn reference(tops: &[&str], rows: &[Row]) -> MenuBar { + fn level(rows: &[&Row], depth: usize) -> Vec { + let mut out = Vec::new(); + let mut shown: Vec<&str> = Vec::new(); + for it in rows { + if it.path.len() == depth { + out.push(if it.label == "---" { Node::Separator } else { Node::Item(craft_menu::Item::new(it.command.clone(), it.label.clone())) }); + } else if let Some(name) = it.path.get(depth) { + let name = name.as_str(); + if shown.contains(&name) { + continue; + } + shown.push(name); + let child: Vec<&Row> = rows.iter().copied().filter(|c| c.path.get(depth).map(String::as_str) == Some(name)).collect(); + out.push(Node::submenu(name, level(&child, depth + 1))); + } + } + old_tidy(out) + } + let menus = tops + .iter() + .map(|top| { + let rows: Vec<&Row> = rows.iter().filter(|r| r.path.first().map(String::as_str) == Some(*top)).collect(); + craft_menu::Menu::new(*top, level(&rows, 1)) + }) + .collect(); + MenuBar::new(menus) +} + +/// The tidy `from_items` used before it worked in place. +fn old_tidy(nodes: Vec) -> Vec { + let mut out: Vec = Vec::with_capacity(nodes.len()); + for mut n in nodes { + if let Node::Submenu { children, .. } = &mut n { + *children = old_tidy(std::mem::take(children)); + if children.is_empty() { + continue; + } + } + if matches!(n, Node::Separator) && matches!(out.last(), None | Some(Node::Separator)) { + continue; + } + out.push(n); + } + while matches!(out.last(), Some(Node::Separator)) { + out.pop(); + } + out +} + +fn row(path: &[&str], id: &str) -> Row { + Row::new(path, CommandRef::new(id), id) +} + +#[trial] +fn from_items_builds_the_tree_the_row_by_row_walk_built() { + let rows = [ + Row::separator(&["File"]), + row(&["File"], "file.new"), + row(&["File", "Recent"], "file.a"), + Row::separator(&["File"]), + Row::separator(&["File"]), + row(&["File", "Recent", "More"], "file.deep"), + row(&["File", "Recent"], "file.b"), + row(&["File"], "file.save"), + Row::separator(&["File", "Recent"]), + row(&["File", "Export"], "file.png"), + Row::separator(&["File"]), + row(&["Edit"], "edit.undo"), + row(&["Stray"], "stray"), + row(&["Edit", "Find", "In Files"], "edit.find"), + Row::separator(&["Edit"]), + Row::separator(&["Edit", "Empty"]), + ]; + let tops = ["File", "Edit", "View"]; + assert_eq!(from_items(&tops, &rows), reference(&tops, &rows)); + let bar = from_items(&tops, &rows); + assert_eq!(bar.menus.len(), 3, "a top with no rows stays an empty menu"); + assert!(bar.menus[2].children.is_empty()); + let Node::Submenu { label, .. } = &bar.menus[0].children[1] else { panic!("the submenu sits where its first row is") }; + assert_eq!(label, "Recent"); +} + +#[trial] +fn tidy_drops_edge_and_repeated_separators_and_empty_submenus_in_place() { + let mut nodes = vec![ + Node::Separator, + Node::Separator, + Node::Item(craft_menu::Item::new("a", "A")), + Node::submenu("Empty", vec![Node::Separator]), + Node::Separator, + Node::Separator, + Node::submenu("Kept", vec![Node::Separator, Node::Item(craft_menu::Item::new("b", "B")), Node::Separator]), + Node::Separator, + ]; + tidy(&mut nodes); + let labels: Vec<&str> = nodes + .iter() + .map(|n| match n { + Node::Item(it) => it.label.as_str(), + Node::Submenu { label, children, .. } => { + assert_eq!(children.len(), 1, "the submenu's own separators are tidied"); + label.as_str() + } + _ => "-", + }) + .collect(); + assert_eq!(labels, ["A", "-", "Kept"]); +} diff --git a/crates/menu/tests/it/main.rs b/crates/menu/tests/it/main.rs index 0a5fd90c0..97451028e 100644 --- a/crates/menu/tests/it/main.rs +++ b/crates/menu/tests/it/main.rs @@ -2,6 +2,7 @@ #[cfg(target_os = "macos")] mod appkit; +mod from_items; mod keytips; mod layout; mod memo; diff --git a/crates/menu/tests/it/memo.rs b/crates/menu/tests/it/memo.rs index a07bc1b90..04ee82549 100644 --- a/crates/menu/tests/it/memo.rs +++ b/crates/menu/tests/it/memo.rs @@ -3,17 +3,23 @@ use std::cell::RefCell; use std::rc::Rc; +use std::sync::Arc; use craft_host::target::Os; +use craft_keymap::Overrides; use craft_menu::{CommandRef, MenuBar, MenuBarUi, Row, Target, from_items}; -use craft_ui::testing::{Fixture, MemoRun, audit_replays, last_frame_memo_runs, trial}; +use craft_ui::contract::Tracked; +use craft_ui::testing::{Fixture, MemoRun, audit_replays, last_frame_derived_builds, last_frame_memo_runs, trial}; use egui::{Event, Key, Modifiers}; -fn model(title: &str) -> MenuBar { - from_items(&[title, "Edit"], &[Row::new(&[title], CommandRef::new("file.new"), "New"), Row::new(&["Edit"], CommandRef::new("edit.undo"), "Undo")]) +fn model(title: &str) -> Tracked { + Tracked::new(from_items( + &[title, "Edit"], + &[Row::new(&[title], CommandRef::new("file.new"), "New"), Row::new(&["Edit"], CommandRef::new("edit.undo"), "Undo")], + )) } -fn fixture(bar: &Rc>) -> Fixture { +fn fixture(bar: &Rc>>) -> Fixture { let bar = Rc::clone(bar); let mut fixture = Fixture::new(move |ui| { MenuBarUi::new(&bar.borrow()).target(Target::Linux).show(ui); @@ -40,7 +46,7 @@ fn an_idle_menu_bar_replays_and_a_title_rename_runs_it_once() { } assert!(fixture.by_label("File").is_some(), "a replayed bar keeps its titles' nodes"); - *bar.borrow_mut() = model("Document"); + bar.borrow_mut().edit(|bar| *bar = model("Document").into_inner()); fixture.frame(vec![]); assert_eq!(counted(&fixture).0, 1, "a model change runs the bar once in that frame"); assert!(fixture.by_label("Document").is_some(), "and it shows the new title"); @@ -81,3 +87,59 @@ fn an_open_menu_runs_the_bar_and_closing_it_replays_it() { fixture.frame(vec![]); assert_eq!(counted(&fixture), (0, 1), "after the menu closes and the keyboard leaves, the bar replays"); } + +/// The label builds of the last frame. +fn label_builds(fixture: &Fixture) -> u32 { + last_frame_derived_builds(fixture.ctx()).iter().map(|(_, builds)| builds).sum() +} + +#[trial] +fn an_idle_bar_and_an_open_menu_build_no_labels() { + let bar = Rc::new(RefCell::new(model("File"))); + let mut fixture = fixture(&bar); + for _ in 0..3 { + fixture.frame(vec![]); + assert_eq!(label_builds(&fixture), 0, "an idle bar builds no labels"); + } + fixture.key(Key::F, Modifiers::ALT); + fixture.settle(); + assert!(fixture.by_label("New").is_some(), "Alt+F opened File"); + for _ in 0..3 { + fixture.frame(vec![]); + assert!(counted(&fixture).0 > 0, "the bar runs each pass while a menu is open"); + assert_eq!(label_builds(&fixture), 0, "and builds no labels"); + } +} + +#[trial] +fn a_model_edit_builds_the_labels_once() { + let bar = Rc::new(RefCell::new(model("File"))); + let mut fixture = fixture(&bar); + bar.borrow_mut().edit(|bar| *bar = model("Document").into_inner()); + fixture.frame(vec![]); + assert_eq!(label_builds(&fixture), 1, "one edit builds the labels once"); + fixture.frame(vec![]); + assert_eq!(label_builds(&fixture), 0, "and the next frame none"); +} + +#[trial] +fn a_locale_change_builds_the_labels_once() { + let bar = Rc::new(RefCell::new(model("File"))); + let mut fixture = fixture(&bar); + fixture.host(crate::mnemonic::turkish()); + fixture.frame(vec![]); + assert_eq!(label_builds(&fixture), 1, "a language change builds the labels once"); + fixture.frame(vec![]); + assert_eq!(label_builds(&fixture), 0, "and the next frame none"); +} + +#[trial] +fn a_keymap_change_builds_the_labels_once() { + let bar = Rc::new(RefCell::new(model("File"))); + let mut fixture = fixture(&bar); + fixture.overrides(Arc::new(Overrides::default())); + fixture.frame(vec![]); + assert_eq!(label_builds(&fixture), 1, "a new keymap builds the labels once"); + fixture.frame(vec![]); + assert_eq!(label_builds(&fixture), 0, "and the next frame none"); +} diff --git a/crates/menu/tests/it/mnemonic.rs b/crates/menu/tests/it/mnemonic.rs index d8ecfd115..8a43bc0c7 100644 --- a/crates/menu/tests/it/mnemonic.rs +++ b/crates/menu/tests/it/mnemonic.rs @@ -6,12 +6,13 @@ use std::sync::Arc; use craft_host::target::Os; use craft_host::{AppInfo, Host}; use craft_menu::{CommandRef, Labeled, MenuBarUi, Row, from_items}; +use craft_ui::contract::Tracked; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers}; #[trial] fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() { - let bar = from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建")]); + let bar = Tracked::new(from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建")])); 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()), @@ -30,7 +31,7 @@ fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() { } /// A host whose interface language is Turkish, with an empty catalog. -fn turkish() -> Arc { +pub(crate) fn turkish() -> Arc { let (i18n, _) = craft_i18n::I18n::from_owned([("tr".to_owned(), String::new(), String::new())], &["tr"]); let tr = i18n.from_code("tr").unwrap_or_else(|| panic!("tr is offered")); Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).i18n(Arc::new(i18n)).lang(tr).build()) @@ -39,8 +40,10 @@ fn turkish() -> Arc { /// The rows shown after Alt with `key` on a Linux bar titled `ix` and `ı` under a Turkish host: `One` is `ix`'s, `Two` /// is `ı`'s. fn opened_by(key: Key) -> (bool, bool) { - let bar = - from_items(&["ix", "ı"], &[Row::new(&["ix"], CommandRef::new("menu.one"), "One"), Row::new(&["ı"], CommandRef::new("menu.two"), "Two")]); + let bar = Tracked::new(from_items( + &["ix", "ı"], + &[Row::new(&["ix"], CommandRef::new("menu.one"), "One"), Row::new(&["ı"], CommandRef::new("menu.two"), "Two")], + )); let mut fixture = Fixture::new(move |ui| { MenuBarUi::new(&bar).show(ui); }); diff --git a/crates/ui-contract/src/contract/memo.rs b/crates/ui-contract/src/contract/memo.rs index 791e1a7f7..53ff63d0f 100644 --- a/crates/ui-contract/src/contract/memo.rs +++ b/crates/ui-contract/src/contract/memo.rs @@ -1020,6 +1020,13 @@ impl MemoProps for craft_behavior::fit::FitKeep { } } +/// Derived `Hash` (`#[non_exhaustive]`). +impl MemoProps for craft_host::target::Os { + fn key(&self, key: &mut MemoKey) { + key.feed_hash(self); + } +} + /// Derived `Hash` (`#[non_exhaustive]`). impl MemoProps for craft_host::target::WindowKind { fn key(&self, key: &mut MemoKey) { diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index b2165c890..468f22afc 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -298,6 +298,14 @@ impl Fixture { self } + /// Sets the user's binding overrides for every following pass, as an app's `FrameInput.commands` does: the keymap is + /// rebuilt when the `Arc` is another one. + pub fn overrides(&mut self, overrides: std::sync::Arc) -> &mut Self { + self.commands = self.commands.clone().overrides(overrides); + self.frames.commands(self.commands.clone()); + self + } + /// The room the story is shown in. pub fn room(&mut self, room: Vec2) -> &mut Self { self.room = room;