menu: a translated label with no letter of its own shows its English letter only in CJK languages; elsewhere the letter stays as a hidden mnemonic

This commit is contained in:
aiongg
2026-11-24 15:57:34 +00:00
parent f72d25338d
commit a783828e55
13 changed files with 212 additions and 83 deletions
+6
View File
@@ -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.
+28 -3
View File
@@ -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<Option<(char, usize)>> {
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<usize>);
/// [`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<char>], folder: &Folder) -> Vec<Option<(char, Option<usize>)>> {
let turkic = folder.turkic();
let parsed: Vec<(String, Option<Placed>)> = 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<char> = Vec::new();
let mut out: Vec<Option<(char, usize)>> = Vec::with_capacity(parsed.len());
let mut out: Vec<Option<Placed>> = 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<Option<(char, usize)>> {
}
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));
}
}
+5 -3
View File
@@ -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(..)`
+10 -3
View File
@@ -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<MenuBar>,
target: Target,
os: Os,
preferred: &'a [(&'a str, char)],
cjk: bool,
words: &'a Words,
keymap: u64,
}
+65 -27
View File
@@ -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<RowLabels>,
}
/// 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<String>,
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<String>,
pub(crate) titles: Vec<Shown>,
pub(crate) menus: Vec<LevelLabels>,
}
/// 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<char>,
}
/// 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<T>(
&self,
siblings: &[T],
label: impl Fn(&T) -> &str,
key: impl Fn(&T) -> &str,
english: impl Fn(&T) -> Option<String>,
) -> Vec<String> {
) -> Vec<Shown> {
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"));
@@ -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<String> {
pub(crate) fn node_labels(&self, nodes: &[Node]) -> Vec<Shown> {
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<String>) {
fn item(&self, ui: &mut Ui, item: &Item, label: Shown, shortcut: Option<String>) {
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<String>) -> craft_ui::menu::MenuItemOutput {
let mut row = MenuItem::new(label).enabled(item.enabled);
fn local(ui: &mut Ui, item: &Item, label: Shown, shortcut: Option<String>) -> 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<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> {
fn command_row<'a>(ui: &Ui, item: &Item, label: Shown, shortcut: Option<String>) -> 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<String>
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)),
+2 -2
View File
@@ -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();
+1 -1
View File
@@ -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![]);
+34 -10
View File
@@ -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<Host> {
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<Host> {
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);
+22 -7
View File
@@ -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<usize>)>);
/// 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<dyn FnMut(&mut Ui) + 'a>,
holds: Vec<CommandRef>,
/// The letter that opens the menu in place of the bar's own pick.
mnemonic: Option<char>,
}
impl<'a> MenuTitle<'a> {
/// A menu titled `label` (a `&` marks the mnemonic) whose rows `body` shows.
pub fn new(label: impl Into<Label>, body: impl FnMut(&mut Ui) + 'a) -> Self {
MenuTitle { label: label.into(), body: Box::new(body), holds: Vec::new() }
MenuTitle { label: label.into(), body: Box::new(body), holds: Vec::new(), mnemonic: None }
}
/// The letter that opens the menu, in place of the bar's own pick. A letter the title lacks still opens it, with
/// nothing underlined.
#[must_use]
pub fn mnemonic(mut self, letter: char) -> Self {
self.mnemonic = Some(letter);
self
}
/// Records the title's rect for `commands` with `commands::holds` in every pass it is shown.
@@ -353,13 +367,14 @@ impl<'a> MenuBar<'a> {
env.shell().menu() == MenuPlacement::InWindow
}
/// Each title's text without its marker, and its mnemonic: the letter and its character index in the text. A Mac
/// menu has no access letters.
fn texts(&self, env: &EnvView<'_>) -> Vec<(String, Option<(char, usize)>)> {
/// Each 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. A Mac menu has no access letters.
fn texts(&self, env: &EnvView<'_>) -> Vec<TitleText> {
let labels: Vec<Label> = self.titles.iter().map(|title| env.resolve(&title.label)).collect();
let refs: Vec<&str> = labels.iter().map(Label::as_str).collect();
let own: Vec<Option<char>> = self.titles.iter().map(|title| title.mnemonic).collect();
let folder = env.folder();
let marks = if env.shell().os.is_mac() { vec![None; refs.len()] } else { mnemonic::assign(&refs, &folder) };
let marks = if env.shell().os.is_mac() { vec![None; refs.len()] } else { mnemonic::assign_with(&refs, &own, &folder) };
refs.iter().zip(marks).map(|(label, mark)| (mnemonic::marked(label, &folder).0, mark)).collect()
}
@@ -515,7 +530,7 @@ impl Component for MenuBar<'_> {
for key in keys {
match key {
MenuKey::Letter(letter) => {
let held = |(_, mark): &(String, Option<(char, usize)>)| mark.is_some_and(|(held, _)| held == letter);
let held = |(_, mark): &TitleText| mark.is_some_and(|(held, _)| held == letter);
if let Some(at) = texts.iter().take(found.shown).position(held) {
Self::open_only(cx, &slots, found, Open::Title(at));
}
@@ -703,7 +718,7 @@ impl Component for MenuBar<'_> {
// Under the pointer a title is the active row, as it is while its menu is open or the keyboard is on it.
let lit = open || cx.hover_pos(part).is_some() || cx.part_state(part).flags.contains(Flags::FOCUS_VISIBLE);
let mnemonic = match slot {
Open::Title(at) if underlined => texts[at].1.map(|(_, index)| index),
Open::Title(at) if underlined => texts[at].1.and_then(|(_, index)| index),
_ => None,
};
ui.face(part, Self::face(&text, lit, mnemonic));
+1 -1
View File
@@ -88,7 +88,7 @@ impl<'a> MenuIconRow<'a> {
}
fn register(&self, ctx: &Context, level: &MenuLevel, id: Id, label: &str, enabled: bool) {
level.register(ctx.cumulative_pass_nr(), Row { id, text: label.to_owned(), enabled: self.runs(enabled) });
level.register(ctx.cumulative_pass_nr(), Row { id, text: label.to_owned(), own: None, enabled: self.runs(enabled) });
}
}
+4 -16
View File
@@ -37,15 +37,6 @@ const SAMPLES: ColumnKey = ColumnKey::new("menu_samples");
/// 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;
/// `label` with a `&` marker before the first character that is `letter`, so the level's assignment honours a row's
/// own mnemonic; a label without that letter is left as it is.
fn with_marker(label: &str, letter: char) -> String {
match label.char_indices().find(|(_, c)| c.eq_ignore_ascii_case(&letter)) {
Some((at, _)) => format!("{}&{}", &label[..at], &label[at..]),
None => label.to_owned(),
}
}
/// Closes the menus out from the one a picked row runs in. Focus leaves them first, so a command the row fires after
/// this reaches the stop focus returns to. Every row that runs on a pick (`MenuItem`, `MenuIconRow`) closes through
/// this one path.
@@ -253,7 +244,8 @@ pub struct MenuItem<'a> {
/// A radio mark, shown while the value is true; the row reserves the mark column either way.
#[prop]
radio_mark: Option<bool>,
/// The letter that runs the row, in place of the level's own pick.
/// The letter that runs the row, in place of the level's own pick. A letter the label lacks still runs the row,
/// with nothing underlined.
#[prop]
mnemonic: Option<char>,
/// A muted second line under the label, in the caption role: the row is a line taller and as wide as the longer
@@ -431,11 +423,7 @@ impl<'a> MenuItem<'a> {
}
fn register(&self, ctx: &Context, level: &MenuLevel, id: Id, label: &str, enabled: bool) {
let text = match self.mnemonic {
Some(letter) => with_marker(label, letter),
None => label.to_owned(),
};
level.register(ctx.cumulative_pass_nr(), Row { id, text, enabled });
level.register(ctx.cumulative_pass_nr(), Row { id, text: label.to_owned(), own: self.mnemonic, enabled });
}
/// The row's mark and icon columns with the gap after each: as wide as the column group of the menu body gives
@@ -705,7 +693,7 @@ impl Component for MenuItem<'_> {
let icon = if icon.color.is_some() { icon } else { icon.color(ink) };
draw.icon(centred(slot), &icon);
}
let mnemonic = if level.keyboard() || cx.modifiers().alt { level.mnemonic_of(cx.id).map(|(_, at)| at) } else { None };
let mnemonic = if level.keyboard() || cx.modifiers().alt { level.mnemonic_of(cx.id).and_then(|(_, at)| at) } else { None };
let look = self.label_look(cx.style);
let run = TextRun::mnemonic(text.as_str(), mnemonic).elide().role(look.role).color(cx.resolve(&look.color));
// A sample-only row draws no label: the label stays its accessible name and its mnemonic source.
+17 -9
View File
@@ -24,14 +24,16 @@ pub fn heads_toward(from: Pos2, now: Pos2, submenu: Rect) -> bool {
pub(super) struct Row {
pub(super) id: Id,
pub(super) text: String,
/// The letter the row asks for in place of the level's pick, shown or not in its text.
pub(super) own: Option<char>,
pub(super) enabled: bool,
}
/// A row's mnemonic as the level assigned it when the user last saw the rows: the letter and its character index
/// in the row's text.
/// in the row's text, none for a letter the text does not show.
struct Assigned {
id: Id,
mnemonic: Option<(char, usize)>,
mnemonic: Option<(char, Option<usize>)>,
enabled: bool,
}
@@ -41,8 +43,11 @@ struct OpenSubmenu {
rect: Option<Rect>,
}
/// A level's letters (each row's mnemonic, or none) with the folder and labels they were assigned for.
type KeptLetters = (Folder, Vec<String>, Vec<Option<(char, usize)>>);
/// A row's text and own letter, as the level's letters were assigned for it.
type Lettered = (String, Option<char>);
/// A level's letters (each row's mnemonic, or none) with the folder and rows they were assigned for.
type KeptLetters = (Folder, Vec<Lettered>, Vec<Option<(char, Option<usize>)>>);
#[derive(Default)]
struct LevelState {
@@ -76,14 +81,17 @@ struct LevelState {
impl LevelState {
/// The letter of each row of this pass, in order, assigned once for these labels.
fn letters(&mut self, folder: Folder) -> &[Option<(char, usize)>] {
fn letters(&mut self, folder: Folder) -> &[Option<(char, Option<usize>)>] {
let same = self.letters.as_ref().is_some_and(|(kept, labels, _)| {
*kept == folder && labels.len() == self.now.len() && labels.iter().zip(&self.now).all(|(label, row)| *label == row.text)
*kept == folder
&& labels.len() == self.now.len()
&& labels.iter().zip(&self.now).all(|((text, own), row)| *text == row.text && *own == row.own)
});
if !same {
let labels: Vec<&str> = self.now.iter().map(|row| row.text.as_str()).collect();
let assigned = mnemonic::assign(&labels, &folder);
self.letters = Some((folder, self.now.iter().map(|row| row.text.clone()).collect(), assigned));
let own: Vec<Option<char>> = self.now.iter().map(|row| row.own).collect();
let assigned = mnemonic::assign_with(&labels, &own, &folder);
self.letters = Some((folder, self.now.iter().map(|row| (row.text.clone(), row.own)).collect(), assigned));
}
self.letters.as_ref().map_or(&[], |(_, _, assigned)| assigned.as_slice())
}
@@ -201,7 +209,7 @@ impl MenuLevel {
});
}
pub(super) fn mnemonic_of(&self, id: Id) -> Option<(char, usize)> {
pub(super) fn mnemonic_of(&self, id: Id) -> Option<(char, Option<usize>)> {
self.with(|state| {
let folder = state.lettered?;
let at = state.now.iter().position(|row| row.id == id)?;
+17 -1
View File
@@ -337,8 +337,24 @@ impl<'a> Menu<'a> {
/// [`submenu_row`](Menu::submenu_row) with `enabled`: a row with it false draws disabled and does not open (a
/// submenu none of whose rows can run).
pub fn submenu_row_enabled(ui: &mut Ui, label: impl Into<Label>, enabled: bool, body: impl FnMut(&mut Ui, &mut BodyCx<'_>)) -> MenuItemOutput {
Menu::submenu_row_lettered(ui, label, enabled, None, body)
}
/// [`submenu_row_enabled`](Menu::submenu_row_enabled) whose row takes `mnemonic` in place of the level's pick
/// ([`MenuItem::mnemonic`]).
pub fn submenu_row_lettered(
ui: &mut Ui,
label: impl Into<Label>,
enabled: bool,
mnemonic: Option<char>,
body: impl FnMut(&mut Ui, &mut BodyCx<'_>),
) -> MenuItemOutput {
let label = label.into();
let head = MenuItem::submenu(label.clone()).enabled(enabled).show(ui);
let mut head = MenuItem::submenu(label.clone()).enabled(enabled);
if let Some(letter) = mnemonic {
head = head.mnemonic(letter);
}
let head = head.show(ui);
let mut open = head.submenu_open;
let show = |ui: &mut Ui| {
Menu::submenu(label, &head.response)