From 46bd564b75557e57c0d4f684200f4e005dabdcab Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 15 Nov 2026 04:46:09 +0000 Subject: [PATCH] top-w2: net change of 6 commits - top-w2: written by an agent - top-w2: finished by an agent - top-w2: review fixes (review-1) - top-w2: the menu-letter step of the shortcut trial types its letter as text, which mnemonics read (top run round) - top-w2: typed letters in a menu go to the container of the focused row's level, with a trial for a title-click menu (top run round) - top-w2: a menu row's pick walks out from the menu it runs in, with a trial for Cut from the Help search field's edit menu (top run round) --- crates/i18n/src/fold.rs | 21 +++ crates/keymap/src/chord.rs | 1 - crates/keymap/src/import.rs | 24 ++- crates/keymap/src/import/kys_tests.rs | 86 +++++++++- crates/keymap/src/mnemonic.rs | 27 ++- crates/keymap/tests/import.rs | 83 ++++++++- crates/menu/tests/it/mnemonic.rs | 37 +++- crates/ui-contract/src/runtime/egui/areas.rs | 9 +- crates/ui-contract/src/runtime/keys/route.rs | 43 +++-- crates/ui-contract/src/runtime/pointer.rs | 21 ++- crates/ui-contract/tests/it/runtime/latch.rs | 158 ++++++++++++++++++ crates/ui-contract/tests/it/runtime/mod.rs | 1 + .../src/patterns/panels/modifier_keys.rs | 73 +++++++- .../patterns/panels/modifier_keys/stories.rs | 15 ++ .../ui-widgets/src/buttons/toggle_button.rs | 15 +- crates/ui-widgets/src/menu/bar.rs | 5 +- crates/ui-widgets/src/menu/item.rs | 16 +- crates/ui-widgets/src/menu/level.rs | 6 +- crates/ui-widgets/tests/it/menu/bar.rs | 27 +++ crates/ui-widgets/tests/it/menu/pick_focus.rs | 100 +++++++++++ crates/window/src/desktop.rs | 3 +- crates/window/src/desktop/work_area.rs | 141 +++++++++++++++- 22 files changed, 842 insertions(+), 70 deletions(-) create mode 100644 crates/ui-contract/tests/it/runtime/latch.rs create mode 100644 crates/ui-patterns/src/patterns/panels/modifier_keys/stories.rs diff --git a/crates/i18n/src/fold.rs b/crates/i18n/src/fold.rs index 86222bd1a..ad00bb163 100644 --- a/crates/i18n/src/fold.rs +++ b/crates/i18n/src/fold.rs @@ -352,4 +352,25 @@ mod tests { } } } + + #[test] + fn turkish_and_azerbaijani_keep_the_dotted_and_dotless_i_pairs_apart() { + assert!(!Folder::new("en").turkic()); + for locale in ["tr", "az", "tr-TR", "AZ_az"] { + let f = Folder::new(locale).keep_accents(); + assert!(f.turkic(), "{locale}"); + // Dotless: `I` is the capital of `ı`, not of `i`. + assert_eq!(f.key("I"), f.key("ı"), "{locale}"); + assert_ne!(f.key("I"), f.key("i"), "{locale}"); + assert!(f.contains("IRMAK", "ırmak"), "{locale}"); + assert!(!f.contains("IRMAK", "irmak"), "{locale}"); + // Dotted: `İ`, precomposed or as `I` and a combining dot, is the capital of `i`. + for dotted in ["İ", "I\u{307}"] { + assert_eq!(f.key(dotted), f.key("i"), "{locale} {dotted:?}"); + assert_ne!(f.key(dotted), f.key("ı"), "{locale} {dotted:?}"); + assert!(f.contains(&format!("{dotted}STANBUL"), "istanbul"), "{locale} {dotted:?}"); + assert!(!f.contains(&format!("{dotted}STANBUL"), "ıstanbul"), "{locale} {dotted:?}"); + } + } + } } diff --git a/crates/keymap/src/chord.rs b/crates/keymap/src/chord.rs index 3d0ed1a84..86c410798 100644 --- a/crates/keymap/src/chord.rs +++ b/crates/keymap/src/chord.rs @@ -436,7 +436,6 @@ impl Mods { /// The held modifiers' names for a screen reader, in the platform's order: `Ctrl Option Shift Cmd` on macOS, /// `Ctrl Alt Shift` elsewhere. - // P3(top-w2): tp.T16, `Mods::spoken` public for `ToggleButton::spoken` callers pub fn spoken(self, platform: Platform) -> Vec<&'static str> { let m = self.effective(platform); let table: [(bool, &'static str); 4] = if platform.is_mac() { diff --git a/crates/keymap/src/import.rs b/crates/keymap/src/import.rs index 548900bd6..f318a54c0 100644 --- a/crates/keymap/src/import.rs +++ b/crates/keymap/src/import.rs @@ -1030,6 +1030,9 @@ impl Names { /// The catalog by normalized path and label, for the match steps. struct Index { tool: Vec, + /// Each command's default triggers, for choosing among same-named commands by the keys an + /// entry carries. + defaults: Vec>, /// Whether each command has a default binding, for choosing among same-named commands. has_default: Vec, /// Whether each command has a menu path of its own (not an import-only one). @@ -1047,6 +1050,7 @@ impl Index { fn new(keymap: &Keymap) -> Index { let mut ix = Index { tool: Vec::new(), + defaults: Vec::new(), has_default: Vec::new(), has_menu: Vec::new(), keys: HashMap::new(), @@ -1056,6 +1060,7 @@ impl Index { }; for (i, b) in keymap.catalog().iter().enumerate() { ix.tool.push(matches!(b.kind, CommandKind::Tool { .. })); + ix.defaults.push(b.defaults.iter().map(|d| d.trigger).collect()); ix.has_default.push(!b.defaults.is_empty()); ix.has_menu.push(!b.paths.is_empty()); ix.keys.insert(b.command.key(), i); @@ -1069,11 +1074,20 @@ impl Index { } /// The one command of `list` of the wanted kind. Among several, those with a default binding - /// win over those without, then those with a menu path over those without; the pick is - /// unique only when one is left. Aliases such as `history.undo` thus lose to the command - /// users know from the menu. - fn pick(&self, list: Option<&Vec>, tool: bool) -> Found { + /// that is one of `keys` win first: a source that gives two commands one label still carries + /// the key that tells them apart. Then those with a default binding win over those without, + /// then those with a menu path over those without; the pick is unique only when one is left. + /// Aliases such as `history.undo` thus lose to the command users know from the menu. + fn pick(&self, list: Option<&Vec>, tool: bool, keys: &[ForeignKey]) -> Found { let mut fits: Vec = list.into_iter().flatten().copied().filter(|i| self.tool.get(*i) == Some(&tool)).collect(); + let carried = |i: &usize| { + self.defaults + .get(*i) + .is_some_and(|d| d.iter().any(|t| keys.iter().any(|k| k.trigger.as_ref().is_ok_and(|kt| kt == t)))) + }; + if fits.len() > 1 && fits.iter().any(carried) { + fits.retain(carried); + } for preferred in [&self.has_default, &self.has_menu] { if fits.len() > 1 && fits.iter().any(|i| preferred[*i]) { fits.retain(|i| preferred[*i]); @@ -1111,7 +1125,7 @@ impl Index { let toggle_steps = self.toggles.steps(menu.as_ref(), &toggle_segs, panel); let mut many = false; for (list, by_panel) in steps.into_iter().chain(toggle_steps) { - match self.pick(list, tool) { + match self.pick(list, tool, &entry.keys) { Found::One(i, _) => return Found::One(i, by_panel), Found::Many => many = true, Found::None => {} diff --git a/crates/keymap/src/import/kys_tests.rs b/crates/keymap/src/import/kys_tests.rs index 4c9f14c93..20cec5b36 100644 --- a/crates/keymap/src/import/kys_tests.rs +++ b/crates/keymap/src/import/kys_tests.rs @@ -1,8 +1,8 @@ //! Photoshop .kys sets. use super::kys::{self, KysError, MAX_BYTES}; -use crate::Trigger; -use crate::keymap::Binding; +use crate::keymap::{Binding, CommandDef, CommandKind, Keymap}; +use crate::{CommandRef, ImportOptions, Platform, Scope, Scopes, Trigger, plan}; fn binding(text: &str) -> Binding { Binding::parse(text).unwrap_or_else(|e| panic!("{text}: {e}")) @@ -20,6 +20,23 @@ fn set(rows: &str, filename: &str) -> String { format!("{rows}") } +fn command(id: &str, label: &str, defaults: &[&str]) -> CommandDef { + defaults.iter().fold(CommandDef::new(id, label, Scope::app()), |c, d| c.with_default(binding(d))) +} + +fn tool(id: &str, label: &str, defaults: &[&str]) -> CommandDef { + command(id, label, defaults).with_kind(CommandKind::Tool { group: None }) +} + +fn keymap(catalog: Vec) -> Keymap { + Keymap::new(catalog, Scopes::new(), Platform::Mac) +} + +/// Every entry's id with its keys, in file order. +fn by_id(set: &crate::ForeignSet) -> Vec<(String, Vec)> { + set.entries.iter().map(|e| (e.id.clone().unwrap_or_default(), keys(e))).collect() +} + #[test] // A Mac set's Control+Opt+Cmd+G and a Windows set's Ctrl+Alt+G read as the same chord with Cmd; the set name comes from the filename attribute. fn reads_a_mac_and_a_windows_set() { @@ -60,3 +77,68 @@ fn reads_a_mac_and_a_windows_set() { let refused = std::thread::Builder::new().stack_size(512 * 1024).spawn(move || kys::read(&deep).err()).unwrap().join().unwrap(); assert!(matches!(refused, Some(KysError::NotASet(m)) if m.contains("nested"))); } + +#[test] +// The `+` key spelled alone, or after a modifier as `Cmd++`, is a key and not a separator, both when written and when read. +fn a_bare_plus_key_is_written_and_read() { + let km = keymap(vec![command("view.zoomIn", "Zoom In", &["Cmd++"]), tool("tool.zoom", "Zoom Tool", &["+"])]); + let xml = kys::write("Mine", &km); + assert!(xml.contains("Cmd++"), "{xml}"); + assert!(xml.contains(">+"), "{xml}"); + let back = kys::read(&xml).unwrap(); + assert_eq!(by_id(&back), [("view.zoomIn".to_string(), vec![trigger("Cmd++")]), ("tool.zoom".to_string(), vec![trigger("+")])]); + + // A Windows set: its Ctrl row makes Ctrl the command key, and the `+` row stays the bare key. + let windows = kys::read(&set( + "Ctrl+C+", + "", + )) + .unwrap(); + assert_eq!(keys(&windows.entries[0]), [trigger("Cmd+C")]); + assert_eq!(keys(&windows.entries[1]), [trigger("+")]); +} + +#[test] +// A set the suite writes spells keys as Photoshop's Mac sets do and reads back into the same bindings, matched by id even where the labels differ. +fn a_written_set_reads_back_with_photoshops_key_spelling() { + let km = keymap(vec![ + command("edit.copy", "Copy", &["Cmd+C", "F3"]), + command("filter.blur", "Gaussian Blur…", &["Cmd+Ctrl+Alt+Shift+G"]), + command("edit.unbound", "Unbound", &[]), + tool("tool.move", "Move Tool", &["V"]), + ]); + let xml = kys::write(" My & Set ", &km); + assert!(xml.contains("KeyboardCustomization/My & Set=My & Set"), "{xml}"); + assert!( + xml.contains( + "Control+Opt+Shift+Cmd+G" + ), + "{xml}" + ); + assert!(xml.contains("Cmd+CF3"), "{xml}"); + assert!(!xml.contains("Unbound"), "a command without a key is left out: {xml}"); + + let back = kys::read(&xml).unwrap(); + assert_eq!(back.name.as_deref(), Some("My & Set")); + assert_eq!( + by_id(&back), + [ + ("edit.copy".to_string(), vec![trigger("Cmd+C"), trigger("F3")]), + ("filter.blur".to_string(), vec![trigger("Cmd+Ctrl+Alt+Shift+G")]), + ("tool.move".to_string(), vec![trigger("V")]), + ] + ); + + // Into a keymap whose labels say something else and that has no keys: the ids decide. + let mut fresh = keymap(vec![ + command("edit.copy", "Duplicate To Clipboard", &[]), + command("filter.blur", "Soften", &[]), + command("edit.unbound", "Unbound", &[]), + tool("tool.move", "Arrow", &[]), + ]); + plan(&back, &fresh, &ImportOptions::default()).apply(&mut fresh); + for id in ["edit.copy", "filter.blur", "edit.unbound", "tool.move"] { + let c = CommandRef::new(id); + assert_eq!(fresh.bindings(&c), km.bindings(&c), "{id}"); + } +} diff --git a/crates/keymap/src/mnemonic.rs b/crates/keymap/src/mnemonic.rs index 38c37ea82..ce65cb053 100644 --- a/crates/keymap/src/mnemonic.rs +++ b/crates/keymap/src/mnemonic.rs @@ -15,7 +15,7 @@ pub fn marked(label: &str, folder: &Folder) -> (String, Option) { /// [`marked`] with the character index of the marked letter in the returned text. pub fn marked_at(label: &str, folder: &Folder) -> (String, Option<(char, usize)>) { - let _ = folder; // P3(top-w2): tp.T9 + let turkic = folder.turkic(); let mut text = String::with_capacity(label.len()); let mut mark = None; let mut at = 0; @@ -27,8 +27,11 @@ pub fn marked_at(label: &str, folder: &Folder) -> (String, Option<(char, usize)> continue; } let Some(next) = chars.next() else { break }; - if mark.is_none() && next != '&' && next.is_ascii_alphanumeric() { - mark = Some((next.to_ascii_uppercase(), at)); + if mark.is_none() + && next != '&' + && let Some(key) = letter(next, turkic) + { + mark = Some((key, at)); } text.push(next); at += 1; @@ -51,14 +54,14 @@ 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); + *slot = first_unused(text, &used, folder.turkic()); used.extend(slot.map(|(letter, _)| letter)); } } out } -fn first_unused(text: &str, used: &[char]) -> Option<(char, usize)> { +fn first_unused(text: &str, used: &[char], turkic: bool) -> Option<(char, usize)> { let mut previous_alnum = false; let mut starts = Vec::new(); for (at, c) in text.chars().enumerate() { @@ -71,7 +74,17 @@ fn first_unused(text: &str, used: &[char]) -> Option<(char, usize)> { starts .into_iter() .chain(all) - .filter(|(c, _)| c.is_ascii_alphanumeric()) - .map(|(c, at)| (c.to_ascii_uppercase(), at)) + .filter_map(|(c, at)| Some((letter(c, turkic)?, at))) .find(|(c, _)| !used.contains(c)) } + +/// The key that types `c`, as a mnemonic letter: its upper case, which must be an ASCII letter or digit. In Turkish +/// and Azerbaijani `I` is the capital of `ı`, so `ı` takes the I key, while `i` and `İ` have no key of their own. +fn letter(c: char, turkic: bool) -> Option { + match c { + 'ı' if turkic => Some('I'), + 'i' if turkic => None, + c if c.is_ascii_alphanumeric() => Some(c.to_ascii_uppercase()), + _ => None, + } +} diff --git a/crates/keymap/tests/import.rs b/crates/keymap/tests/import.rs index 3ee7685cd..2df275a03 100644 --- a/crates/keymap/tests/import.rs +++ b/crates/keymap/tests/import.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; use craft_keymap::chord::foreign::{Flavor, ForeignError}; -use craft_keymap::import::{FailedChange, UnmatchedReason}; +use craft_keymap::import::{FailedChange, UnmatchedReason, kys}; use craft_keymap::{ Binding, CommandDef, CommandKind, CommandRef, ContextRule, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportReport, Keymap, MAX_COMMANDS, Overrides, Platform, Scope, Scopes, plan, reserved, @@ -202,3 +202,84 @@ fn a_failed_change_keeps_its_shortcut_when_a_later_change_frees_room() { assert!(r.conflicts_cleared.is_empty(), "{:?}", r.conflicts_cleared); assert_eq!(r.imported, 1); } + +/// A Mac keymap of `catalog` with no reserved chords, for sets read with [`kys::read`]. +fn mac_keymap(catalog: Vec) -> Keymap { + Keymap::new(catalog, Scopes::new(), Platform::Mac) +} + +/// A `.kys` set of `rows`. +fn kys_set(rows: &str) -> ForeignSet { + kys::read(&format!("{rows}")).unwrap_or_else(|e| panic!("{e}")) +} + +/// The command holds exactly the bindings `texts`, in any order. +fn has_all(km: &Keymap, id: &str, texts: &[&str]) { + let got = km.bindings(&CommandRef::new(id)); + let want = bindings(texts); + assert!(got.len() == want.len() && want.iter().all(|w| got.contains(w)), "{id}: {got:?}, wanted {want:?}"); +} + +fn tool(id: &str, label: &str, keys: &[&str]) -> CommandDef { + command(id, label, &[], keys).with_kind(CommandKind::Tool { group: None }) +} + +#[test] +fn a_shared_label_goes_to_the_command_whose_default_key_the_row_carries() { + // Photoshop names a row by its label alone; both commands are `Levels…` and both have a + // default, so only the row's keys tell them apart. + let catalog = vec![command("image.levels", "Levels…", &[], &["Cmd+L"]), command("layer.newLevels", "Levels…", &[], &["Cmd+Alt+L"])]; + let mut km = mac_keymap(catalog); + let set = kys_set( + "Cmd+LF9\ + Opt+Cmd+LF10\ + F11", + ); + let r = plan(&set, &km, &ImportOptions::default()).apply(&mut km); + has_all(&km, "image.levels", &["Cmd+L", "F9"]); + has_all(&km, "layer.newLevels", &["Cmd+Alt+L", "F10"]); + let unmatched: Vec<(&str, &str, UnmatchedReason)> = r.unmatched.iter().map(|u| (u.item.as_str(), u.keys.as_str(), u.reason)).collect(); + assert_eq!(unmatched, [("Levels...", "F11", UnmatchedReason::Ambiguous)], "a row carrying neither default stays ambiguous"); +} + +#[test] +fn a_row_with_a_default_and_a_function_key_keeps_both() { + let mut km = mac_keymap(vec![command("edit.copy", "Copy", &["Edit", "Copy"], &["Cmd+C"])]); + let set = kys_set("F3Cmd+C"); + let r = plan(&set, &km, &ImportOptions::default()).apply(&mut km); + has_all(&km, "edit.copy", &["Cmd+C", "F3"]); + assert!(r.unmatched.is_empty() && r.unreadable.is_empty() && r.failed.is_empty(), "{r:?}"); +} + +#[test] +fn tool_keys_match_by_name_or_id_and_take_one_letter() { + let catalog = vec![ + // A command with a tool's label: a tool row never binds it. + command("edit.move", "Move Tool", &["Edit", "Move Tool"], &[]), + tool("tool.move", "Move Tool", &["M"]), + tool("tool.pencil", "Pencil Tool", &[]), + tool("tool.brush", "Brush Tool", &[]), + tool("tool.lasso", "Lasso Tool", &["L"]), + ]; + let mut km = mac_keymap(catalog); + let set = kys_set( + "Cmd+C\ + V\ + n\ + B\ + Q\ + Shift+L", + ); + let r = plan(&set, &km, &ImportOptions::default()).apply(&mut km); + // By name, ignoring case, and by id whatever the name says. + has(&km, "tool.move", &["V"]); + has(&km, "tool.pencil", &["N"]); + has(&km, "tool.brush", &["B"]); + has(&km, "edit.move", &[]); + // A tool key with a modifier is unreadable and the tool keeps its key. + has(&km, "tool.lasso", &["L"]); + let unreadable: Vec<&str> = r.unreadable.iter().map(|u| u.item.as_str()).collect(); + assert_eq!(unreadable, ["Lasso Tool"]); + let unmatched: Vec<(&str, UnmatchedReason)> = r.unmatched.iter().map(|u| (u.item.as_str(), u.reason)).collect(); + assert_eq!(unmatched, [("Copy", UnmatchedReason::NoMatch), ("Imaginary Tool", UnmatchedReason::NoMatch)]); +} diff --git a/crates/menu/tests/it/mnemonic.rs b/crates/menu/tests/it/mnemonic.rs index b8f599b9e..9696473b9 100644 --- a/crates/menu/tests/it/mnemonic.rs +++ b/crates/menu/tests/it/mnemonic.rs @@ -1,5 +1,10 @@ -//! A label with no typable letter takes its English label's letter as its mnemonic, shown after it: "文件(F)". +//! 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. +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::testing::{Fixture, trial}; use egui::{Key, Modifiers}; @@ -21,3 +26,33 @@ fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() { fixture.settle(); assert!(fixture.by_label("新建(N)").is_some(), "Alt+F opens the title's menu, whose row shows its own English letter"); } + +/// A host whose interface language is Turkish, with an empty catalog. +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()) +} + +/// 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 mut fixture = Fixture::new(move |ui| { + MenuBarUi::new(&bar).show(ui); + }); + // A Mac bar has no letters; the host gives the Turkish folder. + fixture.os(Os::Linux).host(turkish()); + fixture.settle(); + assert!(fixture.by_label("ix").is_some() && fixture.by_label("ı").is_some(), "the titles show as written"); + fixture.key(key, Modifiers::ALT); + fixture.settle(); + (fixture.by_label("One").is_some(), fixture.by_label("Two").is_some()) +} + +#[trial] +fn turkic_labels_keep_dotted_and_dotless_i_apart() { + // ı's capital is I, so ı holds the I key; the dotted i has no key of its own, so ix takes X. + assert_eq!(opened_by(Key::I), (false, true), "Alt+I opens ı"); + assert_eq!(opened_by(Key::X), (true, false), "Alt+X opens ix"); +} diff --git a/crates/ui-contract/src/runtime/egui/areas.rs b/crates/ui-contract/src/runtime/egui/areas.rs index 5caa6de48..41037736e 100644 --- a/crates/ui-contract/src/runtime/egui/areas.rs +++ b/crates/ui-contract/src/runtime/egui/areas.rs @@ -277,9 +277,14 @@ pub(crate) fn layer_rect(ctx: &Context, id: Id) -> Option { ctx.memory(|memory| memory.area_rect(id)) } -/// The viewport's safe rect: the room overlays must stay inside. +/// The viewport's safe rect: the room overlays must stay inside, the part of the content rect the user can see on +/// the monitor and above its taskbar. Without a known monitor size it is the whole content rect. pub(crate) fn safe_rect(ctx: &Context) -> Rect { - ctx.content_rect() + let content = ctx.content_rect(); + ctx.input(|input| { + let viewport = input.viewport(); + craft_window::desktop::visible_part(content, viewport.monitor_size, viewport.inner_rect, craft_window::desktop::WindowState::of(viewport)) + }) } /// Hands egui the whole layer order of the running pass, bottom first. egui consumes it by the end of the pass. diff --git a/crates/ui-contract/src/runtime/keys/route.rs b/crates/ui-contract/src/runtime/keys/route.rs index 54b25c399..db6405f41 100644 --- a/crates/ui-contract/src/runtime/keys/route.rs +++ b/crates/ui-contract/src/runtime/keys/route.rs @@ -166,14 +166,13 @@ pub(crate) fn owner_at(ctx: &Context, target: Option<&StopRec>, scopes: &[Id], b /// The shortcut events the key owner leaves to the app (9.3), and the presses the focused component holds /// (`holds_press`). The owner is the focused component's class, or `Blocked` while a modal layer is stacked above the -/// focus; inside a layer its `Overlay.keys` class ranks with the component's. `Menu` and `Recorder` keep every key; a -/// text field keeps the text its presses typed. `consumed` is what routing did with each press and `taken_texts` whether -/// a component took each text of the pass. +/// focus; inside a layer its `Overlay.keys` class ranks with the component's. A `Recorder` keeps every key and a `Menu` +/// every key but a command chord (`keeps_key`); a text field keeps the text its presses typed. `consumed` is what +/// routing did with each press and `taken_texts` whether a component took each text of the pass. fn owned_shortcuts(ctx: &Context, target: Option<&StopRec>, batch: &Batch, consumed: &[Taken], taken_texts: &[bool]) -> (Shortcuts, Vec) { let scopes = target.map(|rec| focus::scope_chain(ctx, rec)).unwrap_or_default(); let owner = owner_at(ctx, target, &scopes, None); let own = target.map(|rec| rec.stop.keys.owner); - let silent = keeps_every_key(owner); let dialog = owner == KeyOwner::Class(OwnerClass::Dialog); // The focused component keeps its own keys inside a dialog: a text field its typing, a widget its activation. let typing = owner != KeyOwner::Blocked && own == Some(OwnerClass::Text); @@ -183,8 +182,14 @@ fn owned_shortcuts(ctx: &Context, target: Option<&StopRec>, batch: &Batch, consu .zip(consumed) .map(|(press, taken)| holds_press(owner, target, press, *taken == Taken::Yes, press.text.is_some_and(|at| taken_texts[at]))) .collect(); - let keys = - if silent { Vec::new() } else { batch.shortcuts.iter().filter(|shortcut| !shortcut.press.is_some_and(|at| held[at])).copied().collect() }; + // A shortcut without a press of its own (a release, or the clipboard event that stands for ⌘C) follows the owner by + // its modifiers, as its press would. + let keys = batch + .shortcuts + .iter() + .filter(|shortcut| !keeps_key(owner, shortcut.input.mods) && !shortcut.press.is_some_and(|at| held[at])) + .copied() + .collect(); (Shortcuts { keys, typing, dialog, layout: Layout::default() }, held) } @@ -192,12 +197,13 @@ fn owned_shortcuts(ctx: &Context, target: Option<&StopRec>, batch: &Batch, consu /// egui's input, where the app reads its own keys, nor the app's shortcuts. A widget or popup holds the presses its /// routing `taken`, the keys its filter keeps from the key stage, and the presses whose text it took (`typed`: the /// type-ahead of a list). A text field holds the presses whose text it took, its typing; the egui text widget behind it -/// reads the text, not the press, and the editing keys, which stay in egui's input. A menu or a recorder holds every -/// press, except that a text field in a menu (a menu's search field) keeps the text field's rule. +/// reads the text, not the press, and the editing keys, which stay in egui's input. A recorder holds every press and a +/// menu every press but a command chord (`keeps_key`), except that a text field in a menu (a menu's search field) keeps +/// the text field's rule: the editing chords it lists reach it as edits before routing (`Strip::press`). fn holds_press(owner: KeyOwner, target: Option<&StopRec>, press: &Press, taken: bool, typed: bool) -> bool { let Some(keys) = target.map(|rec| &rec.stop.keys) else { return false }; let text = keys.owner == OwnerClass::Text; - if keeps_every_key(owner) && !text { + if keeps_key(owner, press.mods) && !text { return true; } let open = owner != KeyOwner::Blocked; @@ -211,14 +217,21 @@ fn holds_press(owner: KeyOwner, target: Option<&StopRec>, press: &Press, taken: (widget && (taken || typed || kept)) || (open && text && typed) } -/// `Menu` and `Recorder` keep every key (9.3): no press of theirs reaches egui's input or the app's shortcuts. -fn keeps_every_key(owner: KeyOwner) -> bool { - matches!(owner, KeyOwner::Class(OwnerClass::Menu | OwnerClass::Recorder)) +/// Whether the key owner `owner` keeps a press with `mods` held from egui's input and the app's shortcuts (9.3). A +/// `Recorder` keeps every key. A `Menu` keeps every key but a command chord, one with Cmd or Ctrl held: its shortcut +/// runs, and running a command from a key closes the open popups (`overlay::close_popups`), so ⌘⌥P under an open menu +/// works as it does with the menu closed. +fn keeps_key(owner: KeyOwner, mods: Mods) -> bool { + match owner { + KeyOwner::Class(OwnerClass::Recorder) => true, + KeyOwner::Class(OwnerClass::Menu) => !(mods.cmd || mods.ctrl), + _ => false, + } } /// Where the focused stop `rec` sends the typed `text`, and as what: a digits stop takes its digits, and the rest goes -/// to the list `driven` drives, to a text or type-ahead stop, or to the menu around the stop. Empty when no component -/// takes the text. Reads state only, so a query can ask it. +/// to the list `driven` drives, to a text or type-ahead stop, or to the container of the menu level around the stop. +/// Empty when no component takes the text. Reads state only, so a query can ask it. fn text_route(ctx: &Context, rec: &StopRec, driven: Option, text: &str) -> Vec<(Id, Intent)> { let mut route = Vec::new(); let rest; @@ -239,7 +252,7 @@ fn text_route(ctx: &Context, rec: &StopRec, driven: Option, text: &str) } else if matches!(rec.stop.keys.owner, OwnerClass::Text) || (rec.stop.role.type_ahead && letters) { Some(rec.stop.id) } else if letters { - focus::menu_scope(ctx, rec) + focus::menu_level(ctx, rec) } else { None }; diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index baa3bf73a..111df2bfa 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -40,7 +40,8 @@ pub struct PointerFrame { pub press: Option, /// The button released in the pass. pub release: Option, - /// The modifiers held. + /// The modifiers held, with the ones the app latches for the user (a Modifier Keys panel) added: the app holds + /// them down for every press and drag. Key chords read the keyboard's own modifiers instead. pub mods: Mods, /// The pass's time in seconds. pub time: f64, @@ -88,7 +89,8 @@ pub struct PassPointer { #[derive(Default)] pub(crate) struct Memory { - last_press: Option<(Pos2, f64, u32, craft_keymap::Mods)>, + /// The latest primary press: where, when, its click count and the modifiers held with it. + last_press: Option<(Pos2, f64, u32, Mods)>, press_targets: PressTargets, /// A cancel a service requested for the running pass. requested: Option<(u64, PressCancel)>, @@ -116,9 +118,13 @@ pub(crate) struct Shapes { /// The begin hook (H5): converts the pass's pointer input. pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { + let viewport = pass::current_viewport(ctx); let pass_nr = pass::pass_nr(ctx, viewport); let mut read = input::pointer_read(ctx); + // Every pass reads its own input and the frame's latches, so a second pass of a frame builds the same + // modifiers from its own (event-free) input and counts no press twice. + let mods = with_latched(read.mods, latched); // A drag that started in another window reaches this one through the desktop pointer (8.4). if read.pos.is_none() { read.pos = drag::cross_window_pointer(ctx, viewport); @@ -131,8 +137,8 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { let mut events = read.events.clone(); for event in &mut events { if let PointerEvent::Pressed { button: PointerButton::Primary, pos, time, clicks, .. } = event { - *clicks = count_clicks(memory.last_press, *pos, *time, latched, hit.slop); // P3(top-w2): pn.C14 - memory.last_press = Some((*pos, *time, *clicks, latched)); + *clicks = count_clicks(memory.last_press, *pos, *time, mods, hit.slop); + memory.last_press = Some((*pos, *time, *clicks, mods)); } } if read.primary_pressed || other_pressed { @@ -152,7 +158,7 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { buttons: read.buttons, press, release: read.release, - mods: read.mods, + mods, time: read.time, kind: read.kind, sample: read.sample, @@ -176,6 +182,11 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { PerViewport::::with(ctx, viewport, |shapes| shapes.last = std::mem::take(&mut shapes.this)); } +/// The modifiers `held` with the app's `latched` ones added, field by field: `Mods` has no operator for it. +fn with_latched(held: Mods, latched: Mods) -> Mods { + Mods { cmd: held.cmd || latched.cmd, ctrl: held.ctrl || latched.ctrl, alt: held.alt || latched.alt, shift: held.shift || latched.shift } +} + /// The running viewport's pass number. pub(crate) fn pass_of(ctx: &Context) -> u64 { pass::pass_nr(ctx, pass::current_viewport(ctx)) diff --git a/crates/ui-contract/tests/it/runtime/latch.rs b/crates/ui-contract/tests/it/runtime/latch.rs new file mode 100644 index 000000000..978a8723b --- /dev/null +++ b/crates/ui-contract/tests/it/runtime/latch.rs @@ -0,0 +1,158 @@ +//! Latched modifiers (`FrameInput::latched`): the app holds them down for every press, and only for pointer work. + +use craft_behavior::Sense; +use craft_keymap::{Chord, Key as ChordKey, Mods}; +use craft_ui::contract::{Common, Component, Cx, Focus as _, Pointer as _, Props as _, Role, Show as _}; +use craft_ui::runtime::focus::{FocusTarget, KeyUse, request}; +use craft_ui::style::StyleCx; +use craft_ui::testing::input::key_press; +use craft_ui::testing::pointer::{moved, press, release}; +use craft_ui::testing::{Frames, trial}; +use craft_ui_test_kit::contract::PlainStyle; +use egui::{Id, Key, Modifiers, Pos2, Response, Ui}; +use std::cell::{Cell, RefCell}; + +/// The probe claims K plain and with Shift: which one a press of K takes tells the modifiers key routing read. +const CLAIMS: &[Chord] = &[Chord::plain(ChordKey::K), Chord::new(Mods::SHIFT, ChordKey::K)]; + +/// What the probe saw. +#[derive(Default)] +struct Log { + /// The modifiers of each pass's activation. + activations: Vec, + /// The claimed chords the probe took. + claimed: Vec, + /// `pointer::frame(..).mods` of every pass. + pointer: Vec, +} + +/// A focusable button that logs its activations' modifiers and the claimed chords it takes. +#[derive(Component)] +struct LatchProbe<'a> { + #[common] + common: Common, + log: &'a RefCell, +} + +impl Component for LatchProbe<'_> { + const ROLE: Role = Role::BUTTON; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: LatchProbeStyleKey) -> PlainStyle { + PlainStyle::min(egui::vec2(80.0, 30.0)) + } + + fn sense(&self) -> Sense { + Sense::CLICK | Sense::FOCUS + } + + fn keys(&self) -> KeyUse { + Self::KEYS.with_claims(CLAIMS) + } + + fn update(&mut self, cx: &mut Cx<'_, Self>) { + let activation = cx.activation().map(|activation| activation.mods); + let claimed: Vec = CLAIMS.iter().copied().filter(|chord| cx.take_claimed(*chord)).collect(); + let mut log = self.log.borrow_mut(); + log.activations.extend(activation); + log.claimed.extend(claimed); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +/// The probe's frame closure, the probe's id and rect once shown, and a switch that discards the next pass. +struct Rig { + log: RefCell, + shown: Cell>, + discard: Cell, +} + +impl Rig { + fn new() -> Self { + Rig { log: RefCell::new(Log::default()), shown: Cell::new(None), discard: Cell::new(false) } + } + + fn show(&self, ui: &mut Ui) { + let response = LatchProbe { common: Common::new(), log: &self.log }.id_salt("latch").show(ui); + self.shown.set(Some((response.id, response.rect))); + self.log.borrow_mut().pointer.push(craft_ui::runtime::pointer::frame(ui.ctx()).mods); + if self.discard.take() { + ui.ctx().request_discard("the trial reruns the pass"); + } + } + + fn at(&self) -> Pos2 { + self.shown.get().map_or(Pos2::ZERO, |(_, rect)| rect.center()) + } + + fn clear(&self) { + *self.log.borrow_mut() = Log::default(); + } +} + +/// A click on the probe whose release frame runs a second pass; returns that frame's pass count. +fn click_with_rerun(frames: &mut Frames, rig: &Rig) -> usize { + let at = rig.at(); + frames.frame(vec![moved(at)], |ui| rig.show(ui)); + frames.frame(vec![press(at)], |ui| rig.show(ui)); + rig.discard.set(true); + let passes = frames.frame(vec![release(at)], |ui| rig.show(ui)); + frames.idle(1, |ui| rig.show(ui)); + passes +} + +#[trial] +fn a_latched_modifier_reaches_every_press_until_released() { + let rig = Rig::new(); + let mut frames = Frames::new(); + frames.idle(3, |ui| rig.show(ui)); + let id = rig.shown.get().map(|(id, _)| id).expect("the probe showed"); + request(&frames.ctx, FocusTarget::Id(id)); + frames.idle(2, |ui| rig.show(ui)); + + frames.latched(Mods::SHIFT); + rig.clear(); + assert_eq!(click_with_rerun(&mut frames, &rig), 2, "the release frame runs a second pass"); + { + let log = rig.log.borrow(); + assert_eq!(log.activations, [Mods::SHIFT], "one click, one activation, Shift held by the latch, on the rerun pass too"); + assert!(log.pointer.iter().all(|mods| mods.shift), "every pass's pointer frame holds the latch: {:?}", log.pointer); + } + + // A typed key keeps the keyboard's own modifiers: K reaches the plain-K claim, not Shift+K. + rig.clear(); + frames.frame(vec![key_press(Key::K, Modifiers::NONE)], |ui| rig.show(ui)); + frames.idle(1, |ui| rig.show(ui)); + assert_eq!(rig.log.borrow().claimed, [Chord::plain(ChordKey::K)], "no Shift chord fired from a latched Shift"); + + frames.latched(Mods::NONE); + rig.clear(); + click_with_rerun(&mut frames, &rig); + let log = rig.log.borrow(); + assert_eq!(log.activations, [Mods::NONE], "a released latch leaves the click plain"); + assert!(log.pointer.iter().all(|mods| !mods.shift), "{:?}", log.pointer); +} + +#[trial] +fn a_latch_change_adds_no_pass() { + let rig = Rig::new(); + let mut frames = Frames::new(); + frames.idle(3, |ui| rig.show(ui)); + // The pointer rests on the probe, where a change of the held modifiers could matter to it. + let at = rig.at(); + frames.frame(vec![moved(at)], |ui| rig.show(ui)); + frames.idle(2, |ui| rig.show(ui)); + let steady = frames.frame(Vec::new(), |ui| rig.show(ui)); + frames.latched(Mods::SHIFT); + let latched = frames.frame(Vec::new(), |ui| rig.show(ui)); + let held = frames.frame(Vec::new(), |ui| rig.show(ui)); + frames.latched(Mods::NONE); + let released = frames.frame(Vec::new(), |ui| rig.show(ui)); + assert_eq!(latched, steady, "latching runs no extra pass"); + assert_eq!(held, steady); + assert_eq!(released, steady, "releasing runs no extra pass"); +} diff --git a/crates/ui-contract/tests/it/runtime/mod.rs b/crates/ui-contract/tests/it/runtime/mod.rs index c7d1e3f3d..d7e5d979b 100644 --- a/crates/ui-contract/tests/it/runtime/mod.rs +++ b/crates/ui-contract/tests/it/runtime/mod.rs @@ -3,6 +3,7 @@ mod cursor; mod elapsed; mod env; mod frame; +mod latch; mod memory; mod pen; mod pointer; diff --git a/crates/ui-patterns/src/patterns/panels/modifier_keys.rs b/crates/ui-patterns/src/patterns/panels/modifier_keys.rs index d4adc28d2..96e951869 100644 --- a/crates/ui-patterns/src/patterns/panels/modifier_keys.rs +++ b/crates/ui-patterns/src/patterns/panels/modifier_keys.rs @@ -1,10 +1,29 @@ //! `ModifierKeysPanel`: on-screen toggles for the modifier keys, for a touch screen without a keyboard. -use crate::contract::{Bind, Pattern}; -use craft_keymap::Mods; +use crate::buttons::ToggleButton; +use crate::contract::{Bind, Pattern, Props as _, Show as _, ShowContainer as _}; +use crate::layout_components::Row; +use crate::runtime::env::{Env, Label}; +use craft_behavior::{EditEvent, Mixed}; +use craft_keymap::{Mods, Platform}; use egui::{Response, Ui}; +use std::sync::Arc; + +#[cfg(feature = "testing")] +mod stories; + +/// The panel's buttons in their fixed order, each with the one modifier it latches: Shift, the command key (⌘ on +/// macOS, Ctrl elsewhere) and Alt (⌥ on macOS). +const KEYS: [(&str, Mods); 3] = [("shift", Mods::SHIFT), ("command", Mods::CMD), ("alt", Mods::ALT)]; /// A panel of latching modifier-key toggles: a press on one holds that modifier for the next click or key. +/// +/// - Three toggle buttons, Shift, the command key and Alt, over one binding of the latched modifiers. +/// - Each face is the modifier as chord text writes it on the OS (`⇧ ⌘ ⌥` on macOS, `Shift Ctrl Alt` elsewhere), and +/// its accessible name the modifier's spoken name (`Shift`, `Cmd`, `Option` on macOS). +/// - The app hands the binding's value to the runtime as the frame's latched modifiers (`FrameInput::latched`): every +/// press and drag then reads them as held. Key chords read the keyboard's own modifiers. +/// - The panel adds no words: its title is the dock panel's. #[must_use = "show the panel with `show`"] #[derive(Pattern)] pub struct ModifierKeysPanel<'a> { @@ -14,13 +33,55 @@ pub struct ModifierKeysPanel<'a> { impl<'a> ModifierKeysPanel<'a> { /// A panel over the latched modifiers in `latched`. pub fn new(latched: Bind<'a, Mods>) -> Self { - let _ = latched; - todo!("tp.T16") + ModifierKeysPanel { latched } } /// Shows the panel. pub fn show(self, ui: &mut Ui) -> Response { - let _ = (ui, &self.latched); - todo!("tp.T16") + let ModifierKeysPanel { mut latched } = self; + let os = Env::of(ui).view().shell().os; + Row::new() + .show(ui, |ui, row| { + let held = latched.reborrow().read(row).and_then(|held| held.same().copied()).unwrap_or_default(); + // Off macOS a held Ctrl is the command key: the buttons show and edit the modifiers as the OS reads them. + let before = held.effective(os); + let mut now = before; + for (salt, key) in KEYS { + let mut on = holds(now, key); + ToggleButton::new(face(key, os), Bind::bound(&mut on)).spoken(Label::from(spoken(key, os))).id_salt(salt).show(ui); + now = set(now, key, on); + } + if now != before { + let toggled = KEYS.iter().find(|(_, key)| holds(now, *key) != holds(before, *key)).map_or(Mods::NONE, |(_, key)| *key); + let name: Arc = Arc::from(spoken(toggled, os).as_str()); + let _ = latched.reborrow().write(row, &EditEvent::set(Mixed::Same(held), now, name, None)); + } + }) + .output + } +} + +/// The face of the button for the one-modifier `key`: its symbol on macOS, its name elsewhere. +fn face(key: Mods, os: Platform) -> String { + key.parts(os).concat() +} + +/// The name a screen reader says for the one-modifier `key`. +fn spoken(key: Mods, os: Platform) -> String { + key.spoken(os).join(" ") +} + +/// Whether `mods` holds the one modifier of `key`. +fn holds(mods: Mods, key: Mods) -> bool { + (key.shift && mods.shift) || (key.cmd && mods.cmd) || (key.alt && mods.alt) +} + +/// `mods` with the one modifier of `key` held or released. +fn set(mods: Mods, key: Mods, on: bool) -> Mods { + Mods { + shift: if key.shift { on } else { mods.shift }, + cmd: if key.cmd { on } else { mods.cmd }, + alt: if key.alt { on } else { mods.alt }, + ctrl: mods.ctrl, } } diff --git a/crates/ui-patterns/src/patterns/panels/modifier_keys/stories.rs b/crates/ui-patterns/src/patterns/panels/modifier_keys/stories.rs new file mode 100644 index 000000000..7c65a0230 --- /dev/null +++ b/crates/ui-patterns/src/patterns/panels/modifier_keys/stories.rs @@ -0,0 +1,15 @@ +//! Stories of `ModifierKeysPanel`. + +use super::ModifierKeysPanel; +use crate::contract::Bind; +use crate::testing::{Drive, StoryData, StoryOutput, story}; +use craft_keymap::Mods; +use egui::Ui; + +#[story(ModifierKeysPanel<'static>, covers = [], drive = Drive::Never, title = "Shift latched")] +fn modifier_keys_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let latched = data.value("latched", Mods::SHIFT); + ModifierKeysPanel::new(Bind::bound(&mut *latched)).show(ui); + let readout = format!("{latched:?}"); + StoryOutput::default().readout(readout) +} diff --git a/crates/ui-widgets/src/buttons/toggle_button.rs b/crates/ui-widgets/src/buttons/toggle_button.rs index 7b1f8124e..bf4ee21b0 100644 --- a/crates/ui-widgets/src/buttons/toggle_button.rs +++ b/crates/ui-widgets/src/buttons/toggle_button.rs @@ -1,7 +1,9 @@ //! `ToggleButton`: a button that stays pressed while on. use super::face::{self, FaceLook, FaceSpec}; -use crate::contract::{Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, PaintUi, Pointer as _, Props, Role}; +use crate::contract::{ + Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Name, PaintUi, Pointer as _, Props, Role, +}; use crate::primitives::IconSpec; use crate::runtime::commands::CommandRef; use crate::runtime::env::Label; @@ -65,7 +67,6 @@ pub struct ToggleButton<'a> { #[prop(flag)] escape_disarms: bool, /// The name a screen reader hears when it differs from the face (a modifier key's symbol face). - // P3(top-w2): tp.T16 decision, the `spoken` prop #[prop] spoken: Option