diff --git a/crates/i18n/src/scripts.rs b/crates/i18n/src/scripts.rs index 75490ecf8..2ce64ae78 100644 --- a/crates/i18n/src/scripts.rs +++ b/crates/i18n/src/scripts.rs @@ -108,6 +108,12 @@ impl Script { pub fn rtl(self) -> bool { matches!(self, Script::Arab | Script::Hebr | Script::Syrc | Script::Thaa) } + + /// Whether the script is one of the CJK scripts (Han, Hiragana, Katakana, Hangul), whose interface labels show + /// the Latin letter of their access key after them: "文件(F)". + pub fn cjk(self) -> bool { + matches!(self, Script::Hani | Script::Hira | Script::Kana | Script::Hang) + } } /// Which way a language's text, and an interface in it, runs. diff --git a/crates/keymap/src/mnemonic.rs b/crates/keymap/src/mnemonic.rs index 22fe163a3..f58ef0a26 100644 --- a/crates/keymap/src/mnemonic.rs +++ b/crates/keymap/src/mnemonic.rs @@ -44,9 +44,34 @@ pub fn marked_at(label: &str, folder: &Folder) -> (String, Option<(char, usize)> /// marker, takes the first letter or digit of its text not yet used, trying the first character of each word before /// the others. pub fn assign(labels: &[&str], folder: &Folder) -> Vec> { - let parsed: Vec<(String, Option<(char, usize)>)> = labels.iter().map(|label| marked_at(label, folder)).collect(); + let own = vec![None; labels.len()]; + assign_with(labels, &own, folder).into_iter().map(|mark| mark.and_then(|(letter, at)| Some((letter, at?)))).collect() +} + +/// A mnemonic letter and its character index in the label's text, none when the text does not show it. +type Placed = (char, Option); + +/// [`assign`] where a label may come with a letter of its own: a label without a `&` marker holds its `own` letter as a +/// marker would, at the first character of its text that types it, or with no index when the text has none (a +/// translated label keeps its English label's key). An own letter that is not a typable key is ignored. +pub fn assign_with(labels: &[&str], own: &[Option], folder: &Folder) -> Vec)>> { + let turkic = folder.turkic(); + let parsed: Vec<(String, Option)> = labels + .iter() + .enumerate() + .map(|(i, label)| { + let (text, mark) = marked_at(label, folder); + let own = own + .get(i) + .copied() + .flatten() + .and_then(|c| letter(c, turkic)) + .map(|key| (key, text.chars().position(|c| letter(c, turkic) == Some(key)))); + (text, mark.map(|(letter, at)| (letter, Some(at))).or(own)) + }) + .collect(); let mut used: Vec = Vec::new(); - let mut out: Vec> = Vec::with_capacity(parsed.len()); + let mut out: Vec> = Vec::with_capacity(parsed.len()); for (_, mark) in &parsed { let held = mark.filter(|(letter, _)| !used.contains(letter)); used.extend(held.map(|(letter, _)| letter)); @@ -54,7 +79,7 @@ pub fn assign(labels: &[&str], folder: &Folder) -> Vec> { } for ((text, _), slot) in parsed.iter().zip(&mut out) { if slot.is_none() { - *slot = first_unused(text, &used, folder.turkic()); + *slot = first_unused(text, &used, turkic).map(|(letter, at)| (letter, Some(at))); used.extend(slot.map(|(letter, _)| letter)); } } diff --git a/crates/menu/README.md b/crates/menu/README.md index 7acfcd98e..3e3f0cabf 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -163,9 +163,11 @@ egui::Panel::top("menu-bar").show(ui, |ui| { and leaves Alt alone; F10 still reaches the in-window bar of a browser. `.keyboard(false)` turns the bar's keys off (a modal dialog or the shortcut recorder has them); on `Target::Mac` they are off unless set. `.mnemonics(&[("View", 'W'), ("file.open", 'P')])` names preferred - letters by title as shown or by command id. A label without an ASCII letter or digit shows its - English label's letter after it, "文件(F)", before a trailing ellipsis ("開く(O)…"), when - the item, submenu or menu carries that English label (`Item::english`, `Node::english`, `Menu::english`). + letters by title as shown or by command id. A label without an ASCII letter or digit takes its + English label's letter when the item, submenu or menu carries that English label + (`Item::english`, `Node::english`, `Menu::english`). In a CJK interface language the letter + shows after the label, "文件(F)", before a trailing ellipsis ("開く(O)…"); in any other script + it is hidden ("Файл" stays as written) and still opens or runs the entry. - **Items:** a command the runtime's gate forbids, or whose state is disabled, is greyed and never fires. A submenu whose items are all disabled is greyed. The shortcut column shows the command's chord, else the item's own shortcut, in the shell's names (⌘ glyphs on a Mac). `.target(..)` diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index d33fed553..618a61fa1 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -173,8 +173,9 @@ impl<'a> MenuBarUi<'a> { /// The bar's view: the titles through [`craft_ui::menu::MenuBar`], each menu's rows as command rows. fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput { - let rows = Rows::new(props.target).preferred(props.preferred).icons(props.icons).compact(props.compact); let env = Env::of(ui); + let cjk = crate::context::cjk(&env); + let rows = Rows::new(props.target).cjk(cjk).preferred(props.preferred).icons(props.icons).compact(props.compact); 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 { @@ -182,6 +183,7 @@ fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput { target: props.target, os, preferred: props.preferred, + cjk, words: &env.words, keymap: craft_ui::runtime::commands::keymap_generation(ui.ctx()), }; @@ -198,7 +200,11 @@ fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput { .map(|((menu, title), level)| { // The commands the title holds, for the palette's callout; a built-in has no command of the app. let held = menu.children.iter().flat_map(node_commands).filter(|command| Builtin::of(command).is_none()).collect(); - MenuTitle::new(title.clone(), move |ui| shared.show(ui, &menu.children, level)).holds(held) + let row = MenuTitle::new(title.label.clone(), move |ui| shared.show(ui, &menu.children, level)).holds(held); + match title.hidden { + Some(letter) => row.mnemonic(letter), + None => row, + } }) .collect(); // Collecting the search's commands walks every row of every menu: the bar does it only while Help is open. @@ -213,13 +219,14 @@ fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput { } /// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the preferred mnemonics, -/// the language and the keymap. The English names are part of the model. +/// the language (its words, and whether it is CJK) and the keymap. The English names are part of the model. #[derive(MemoProps)] struct LabelKey<'a> { bar: &'a Tracked, target: Target, os: Os, preferred: &'a [(&'a str, char)], + cjk: bool, words: &'a Words, keymap: u64, } diff --git a/crates/menu/src/context.rs b/crates/menu/src/context.rs index 07c248c2e..7ca4b0a99 100644 --- a/crates/menu/src/context.rs +++ b/crates/menu/src/context.rs @@ -27,7 +27,8 @@ 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]) { - let rows = Rows::new(Target::of_shell(Env::of(ui).view().shell())); + let env = Env::of(ui); + let rows = Rows::new(Target::of_shell(env.view().shell())).cjk(cjk(&env)); let labels = rows.level_labels(nodes, rows.platform(ui)); rows.show(ui, nodes, &labels); } @@ -39,11 +40,12 @@ 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. +/// One node's text: its label as the menu shows it (markers escaped, mnemonic marked), the letter it takes without +/// showing it, 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, + label: Shown, shortcut: Option, children: LevelLabels, } @@ -51,14 +53,30 @@ struct RowLabels { /// 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) titles: Vec, pub(crate) menus: Vec, } -/// How the rows of a menu are written: the target that names the shortcuts and the app's preferred mnemonic -/// letters. +/// A label as its menu shows it, and the English letter it takes without showing it: a translated label with no +/// letter of its own in a script that writes none after it (Cyrillic, Greek, Arabic…). +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct Shown { + pub(crate) label: String, + pub(crate) hidden: Option, +} + +/// Whether the interface language of `env`'s scope is written in a CJK script. +pub(crate) fn cjk(env: &Env) -> bool { + let code = env.view().host().map_or("en", |host| host.language_code()); + craft_i18n::scripts(code).first().is_some_and(|script| script.cjk()) +} + +/// How the rows of a menu are written: the target that names the shortcuts, the app's preferred mnemonic letters and +/// whether the interface language is CJK. pub(crate) struct Rows<'a> { target: Target, + /// Whether a label with no letter of its own shows its English label's letter after it. + cjk: bool, preferred: &'a [(&'a str, char)], /// Whether rows show their command's icon. icons: bool, @@ -68,7 +86,12 @@ pub(crate) struct Rows<'a> { impl<'a> Rows<'a> { pub(crate) fn new(target: Target) -> Self { - Rows { target, preferred: &[], icons: true, compact: false } + Rows { target, cjk: false, preferred: &[], icons: true, compact: false } + } + + pub(crate) fn cjk(mut self, on: bool) -> Self { + self.cjk = on; + self } pub(crate) fn icons(mut self, on: bool) -> Self { @@ -86,16 +109,17 @@ impl<'a> Rows<'a> { self } - /// The labels of `siblings` as their menu shows them: markers escaped, the app's preferred letter marked, and - /// a label with no letter or digit of its own followed by its English label's letter, "文件(&F)". `key` names - /// each sibling for the preferred letters, `english` asks for its English label. + /// The labels of `siblings` as their menu shows them: markers escaped and the app's preferred letter marked. A + /// label with no letter or digit of its own takes its English label's letter: in a CJK language shown after it, + /// "文件(&F)", the convention there; in any other script hidden, so Alt+F still opens "Файл". `key` names each + /// sibling for the preferred letters, `english` asks for its English label. pub(crate) fn labels( &self, siblings: &[T], label: impl Fn(&T) -> &str, key: impl Fn(&T) -> &str, english: impl Fn(&T) -> Option, - ) -> Vec { + ) -> Vec { let english: Vec = 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")); @@ -106,12 +130,16 @@ impl<'a> Rows<'a> { let text = label(sibling); let escaped = text.replace('&', "&&"); let typed = text.chars().any(|c| c.is_ascii_alphanumeric()); - if let Some((letter, _)) = letter.filter(|_| !typed) { - return with_key(&escaped, letter); - } - match self.preferred_letter(key(sibling)) { - Some(letter) => marked(&escaped, letter), - None => escaped, + match letter.filter(|_| !typed) { + Some((letter, _)) if self.cjk => Shown { label: with_key(&escaped, letter), hidden: None }, + Some((letter, _)) => Shown { label: escaped, hidden: Some(letter) }, + None => { + let label = match self.preferred_letter(key(sibling)) { + Some(letter) => marked(&escaped, letter), + None => escaped, + }; + Shown { label, hidden: None } + } } }) .collect() @@ -122,7 +150,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 { + pub(crate) fn node_labels(&self, nodes: &[Node]) -> Vec { let shown: Vec<&Node> = nodes.iter().filter(|node| !takes_no_letter(node)).collect(); let mut labels = self .labels( @@ -144,7 +172,7 @@ impl<'a> Rows<'a> { }, ) .into_iter(); - nodes.iter().map(|node| if takes_no_letter(node) { String::new() } else { labels.next().unwrap_or_default() }).collect() + nodes.iter().map(|node| if takes_no_letter(node) { Shown::default() } else { labels.next().unwrap_or_default() }).collect() } /// The text of `nodes` and of every submenu below them, with shortcuts written for `platform`. @@ -181,9 +209,13 @@ impl<'a> Rows<'a> { } Node::Submenu { children, enabled, .. } => { if !enabled || is_dead(children) { - MenuItem::submenu(label).enabled(false).show(ui); + let mut row = MenuItem::submenu(label.label).enabled(false); + if let Some(letter) = label.hidden { + row = row.mnemonic(letter); + } + row.show(ui); } else { - Menu::submenu_row(ui, label, |ui, _| self.show(ui, children, &text.children)); + Menu::submenu_row_lettered(ui, label.label, true, label.hidden, |ui, _| self.show(ui, children, &text.children)); } } Node::Heading(text) => { @@ -194,7 +226,7 @@ impl<'a> Rows<'a> { } } - fn item(&self, ui: &mut Ui, item: &Item, label: String, shortcut: Option) { + fn item(&self, ui: &mut Ui, item: &Item, label: Shown, shortcut: Option) { match Builtin::of(&item.command) { Some(Builtin::Quit) => { if local(ui, item, label, shortcut).ran { @@ -219,8 +251,11 @@ impl<'a> Rows<'a> { } /// A local row for a built-in command: the bar runs it itself. -fn local(ui: &mut Ui, item: &Item, label: String, shortcut: Option) -> craft_ui::menu::MenuItemOutput { - let mut row = MenuItem::new(label).enabled(item.enabled); +fn local(ui: &mut Ui, item: &Item, label: Shown, shortcut: Option) -> craft_ui::menu::MenuItemOutput { + let mut row = MenuItem::new(label.label).enabled(item.enabled); + if let Some(letter) = label.hidden { + row = row.mnemonic(letter); + } if let Some(shortcut) = shortcut { row = row.shortcut(shortcut); } @@ -228,7 +263,7 @@ fn local(ui: &mut Ui, item: &Item, label: String, shortcut: Option) -> 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) -> MenuItem<'a> { +fn command_row<'a>(ui: &Ui, item: &Item, label: Shown, shortcut: Option) -> MenuItem<'a> { // 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; @@ -236,7 +271,10 @@ fn command_row<'a>(ui: &Ui, item: &Item, label: String, shortcut: Option 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()); + let mut row = MenuItem::command(command).label(label.label).enabled(item.enabled).id_salt(item.command.key()); + if let Some(letter) = label.hidden { + row = row.mnemonic(letter); + } row = match item.kind { ItemKind::Plain => row, ItemKind::Check(on) => row.check(checked(ui, &item.command).unwrap_or(on)), diff --git a/crates/menu/tests/it/heading.rs b/crates/menu/tests/it/heading.rs index 93c6eaf79..9c598f9d4 100644 --- a/crates/menu/tests/it/heading.rs +++ b/crates/menu/tests/it/heading.rs @@ -39,8 +39,8 @@ fn a_heading_is_structure_and_never_a_command() { let mut fixture = Fixture::new(move |ui| { MenuBarUi::new(&bar).show(ui); }); - // A Mac bar has no letters. - fixture.os(Os::Linux); + // A Mac bar has no letters; a Chinese interface shows the English letters after the labels. + fixture.os(Os::Linux).host(crate::mnemonic::host_in("zh")); fixture.settle(); fixture.key(Key::F, Modifiers::ALT); fixture.settle(); diff --git a/crates/menu/tests/it/memo.rs b/crates/menu/tests/it/memo.rs index 92276ae65..98c071afc 100644 --- a/crates/menu/tests/it/memo.rs +++ b/crates/menu/tests/it/memo.rs @@ -136,7 +136,7 @@ fn a_model_edit_builds_the_labels_once() { 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.host(crate::mnemonic::host_in("tr")); fixture.frame(vec![]); assert_eq!(label_builds(&fixture), 1, "a language change builds the labels once"); fixture.frame(vec![]); diff --git a/crates/menu/tests/it/mnemonic.rs b/crates/menu/tests/it/mnemonic.rs index 63c1dc60b..c2927ef31 100644 --- a/crates/menu/tests/it/mnemonic.rs +++ b/crates/menu/tests/it/mnemonic.rs @@ -1,11 +1,12 @@ -//! A label with no typable letter takes its English label's letter as its mnemonic, shown after it: "文件(F)"; in -//! Turkish the dotless ı takes the I key and the dotted i none. +//! A label with no typable letter takes its English label's letter as its mnemonic: shown after it in a CJK language, +//! "文件(F)", and hidden in any other script, so "Файл" stays as written and Alt+F still opens it. In Turkish the +//! dotless ı takes the I key and the dotted i none. use std::sync::Arc; use craft_host::target::Os; use craft_host::{AppInfo, Host}; -use craft_menu::{CommandRef, LayoutOptions, MenuBarUi, Row, Target, from_items}; +use craft_menu::{CommandRef, Item, LayoutOptions, Menu, MenuBar, MenuBarUi, Node, Row, Target, from_items}; use craft_ui::contract::Tracked; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers}; @@ -19,7 +20,7 @@ fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() { MenuBarUi::new(&bar).show(ui); }); // A Mac bar has no letters. - fixture.os(Os::Linux); + fixture.os(Os::Linux).host(host_in("zh")); fixture.settle(); assert!(fixture.by_label("文件(F)").is_some(), "the title shows the English letter after it"); fixture.key(Key::F, Modifiers::ALT); @@ -27,6 +28,29 @@ fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() { assert!(fixture.by_label("新建(N)").is_some(), "Alt+F opens the title's menu, whose row shows its own English letter"); } +#[trial] +fn a_cyrillic_label_hides_its_english_letter_and_the_letter_still_opens_it() { + let recent = Node::submenu("Последние", vec![Item::new("file.open", "Открыть").english("Open").into()]).english("Open Recent"); + let bar = Tracked::new(MenuBar::new(vec![Menu::new("Файл", vec![recent]).english("File")])); + let mut fixture = Fixture::new(move |ui| { + MenuBarUi::new(&bar).show(ui); + }); + fixture.os(Os::Linux).host(host_in("ru")); + fixture.settle(); + assert!(fixture.by_label("Файл").is_some() && fixture.by_label("Файл(F)").is_none(), "the title shows as written"); + fixture.key(Key::F, Modifiers::ALT); + fixture.settle(); + assert!(fixture.by_label("Последние").is_some(), "Alt+F opens the title by its hidden English letter"); + assert!(fixture.by_label("Последние(O)").is_none(), "the row shows as written"); + fixture.key(Key::Escape, Modifiers::NONE).settle(); + let title = fixture.by_label("Файл").expect("the title"); + fixture.click(&title).settle(); + // The O key on a Russian layout types щ. + fixture.type_key(Key::O, "щ"); + fixture.settle(); + assert!(fixture.by_label("Открыть").is_some(), "O opens the submenu by its hidden English letter"); +} + #[trial] fn help_search_lists_an_item_by_its_english_name_in_a_translated_model() { let bar = from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建").english("New")]); @@ -35,11 +59,11 @@ fn help_search_lists_an_item_by_its_english_name_in_a_translated_model() { assert_eq!(entry.english().map(|label| label.as_str()), Some("New")); } -/// A host whose interface language is Turkish, with an empty catalog. -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()) +/// A host whose interface language is `code`, with an empty catalog. +pub(crate) fn host_in(code: &str) -> Arc { + let (i18n, _) = craft_i18n::I18n::from_owned([(code.to_owned(), String::new(), String::new())], &[code]); + let lang = i18n.from_code(code).unwrap_or_else(|| panic!("{code} is offered")); + Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).i18n(Arc::new(i18n)).lang(lang).build()) } /// The rows shown after Alt with `key` on a Linux bar titled `ix` and `ı` under a Turkish host: `One` is `ix`'s, `Two` @@ -53,7 +77,7 @@ fn opened_by(key: Key) -> (bool, bool) { MenuBarUi::new(&bar).show(ui); }); // A Mac bar has no letters; the host gives the Turkish folder. - fixture.os(Os::Linux).host(turkish()); + fixture.os(Os::Linux).host(host_in("tr")); fixture.settle(); assert!(fixture.by_label("ix").is_some() && fixture.by_label("ı").is_some(), "the titles show as written"); fixture.key(key, Modifiers::ALT); diff --git a/crates/ui-widgets/src/menu/bar.rs b/crates/ui-widgets/src/menu/bar.rs index 7ab92d88e..99e4e86c2 100644 --- a/crates/ui-widgets/src/menu/bar.rs +++ b/crates/ui-widgets/src/menu/bar.rs @@ -187,17 +187,31 @@ pub struct MenuBarStyle { metrics: Metrics, } +/// A title's text without its marker, and its mnemonic: the letter and its character index in the text, none for a +/// letter the text does not show. +type TitleText = (String, Option<(char, Option)>); + /// A menu of the bar: its title and the body that fills the menu when it opens. pub struct MenuTitle<'a> { label: Label, body: Box, holds: Vec, + /// The letter that opens the menu in place of the bar's own pick. + mnemonic: Option, } impl<'a> MenuTitle<'a> { /// A menu titled `label` (a `&` marks the mnemonic) whose rows `body` shows. pub fn new(label: impl Into