From d6c7b45350f7a4352b845c9fdd2e63913d1af27d Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 03:52:23 +0000 Subject: [PATCH 01/32] keymap: shared keyboard bindings, scopes, overrides and shortcut-set import craft-keymap holds the data and logic for keyboard bindings: egui-free chords with one canonical text form, bindings to commands with params, several bindings per command, scopes, tool groups, conflicts, overrides kept in a craft-settings type, an import pipeline for other applications' shortcut sets, and an optional egui dispatcher. Apps keep their command catalogue, file readers and UI. --- Cargo.lock | 11 + Cargo.toml | 1 + README.md | 4 + crates/keymap/Cargo.toml | 23 + crates/keymap/README.md | 183 +++++ crates/keymap/src/chord.rs | 585 ++++++++++++++++ crates/keymap/src/chord/foreign.rs | 195 ++++++ crates/keymap/src/command.rs | 127 ++++ crates/keymap/src/egui.rs | 340 +++++++++ crates/keymap/src/import.rs | 837 +++++++++++++++++++++++ crates/keymap/src/import/namematch.rs | 351 ++++++++++ crates/keymap/src/keymap.rs | 947 ++++++++++++++++++++++++++ crates/keymap/src/keymap/overrides.rs | 337 +++++++++ crates/keymap/src/lib.rs | 146 ++++ crates/keymap/src/reserved.rs | 36 + crates/keymap/src/scope.rs | 205 ++++++ crates/keymap/tests/chord.rs | 178 +++++ crates/keymap/tests/egui.rs | 290 ++++++++ crates/keymap/tests/import.rs | 546 +++++++++++++++ crates/keymap/tests/keymap.rs | 523 ++++++++++++++ crates/keymap/tests/settings.rs | 122 ++++ 21 files changed, 5987 insertions(+) create mode 100644 crates/keymap/Cargo.toml create mode 100644 crates/keymap/README.md create mode 100644 crates/keymap/src/chord.rs create mode 100644 crates/keymap/src/chord/foreign.rs create mode 100644 crates/keymap/src/command.rs create mode 100644 crates/keymap/src/egui.rs create mode 100644 crates/keymap/src/import.rs create mode 100644 crates/keymap/src/import/namematch.rs create mode 100644 crates/keymap/src/keymap.rs create mode 100644 crates/keymap/src/keymap/overrides.rs create mode 100644 crates/keymap/src/lib.rs create mode 100644 crates/keymap/src/reserved.rs create mode 100644 crates/keymap/src/scope.rs create mode 100644 crates/keymap/tests/chord.rs create mode 100644 crates/keymap/tests/egui.rs create mode 100644 crates/keymap/tests/import.rs create mode 100644 crates/keymap/tests/keymap.rs create mode 100644 crates/keymap/tests/settings.rs diff --git a/Cargo.lock b/Cargo.lock index 6471411f0..7ae3ad373 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -618,6 +618,17 @@ dependencies = [ "unic-langid", ] +[[package]] +name = "craft-keymap" +version = "0.1.0" +dependencies = [ + "craft-settings", + "egui", + "serde", + "serde_json", + "tempfile", +] + [[package]] name = "craft-pdf" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 868e568dd..c9def5c7f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ craft-atomic = { path = "crates/atomic" } craft-cms = { path = "crates/cms" } craft-docpath = { path = "crates/docpath" } craft-i18n = { path = "crates/i18n" } +craft-keymap = { path = "crates/keymap" } craft-print = { path = "crates/print" } craft-quit = { path = "crates/quit" } craft-settings = { path = "crates/settings" } diff --git a/README.md b/README.md index 78b243407..166c3b9e2 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,10 @@ craft- = { git = "https://github.com/storytold/craft-libs", rev = "" = [keys] }` also loads; there a single +text counts as a one-item list, and `""` means no shortcut, as in apps that store one text per +command. + +Texts the keymap cannot use (a key name from a newer version, an unknown scope, a reserved chord) +stay in the entry when the command is edited, unless the edit leaves it without bindings. +`Keymap::problems` lists them. + +```rust +use craft_keymap::{Binding, Keymap, Overrides, Platform, Policy, Scopes}; +use craft_settings::{Location, Settings, SettingsStore}; +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Default, Clone, PartialEq)] +#[serde(default)] +struct Prefs { + shortcuts: Overrides, +} + +impl Settings for Prefs { + const APP_ID: &'static str = "acmecraft"; + const SCHEMA_VERSION: u32 = 1; +} + +// `catalogue` is the app's Vec. +let (mut store, _report) = SettingsStore::::open(Location::Auto); +let mut keymap = Keymap::new(catalogue, Scopes::new(), Platform::current()).with_overrides(store.get().shortcuts.clone()); +// Entries for unknown commands and texts that do not parse are kept and listed here. +let _problems = keymap.problems(); + +// After each change in the shortcut editor: +keymap.assign(&"file.save".into(), Binding::parse("Cmd+Alt+S").unwrap(), Policy::Steal).ok(); +store.update(|p| p.shortcuts = keymap.overrides().clone()); +``` + +## Importing a shortcut set + +The app's reader turns a file (an InDesign Show Set, an Illustrator `.kys`) into an +[`import::ForeignSet`](src/import.rs): entries with a menu, a path and keys read by +`ForeignKey::read`. `import::plan` matches each entry to one command and changes nothing; +`ImportPlan::apply` applies the plan and returns an `ImportReport` (serde, camelCase). Report +rows carry the entry's `item` (its path) and `line`. + +```rust +use craft_keymap::{Bindable, Binding, ContextRule, Flavor, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, Keymap, Platform}; +use craft_keymap::{Scope, Scopes, plan}; + +let save = Bindable::new("file.save", "Save", Scope::app()) + .with_path(vec!["File".into(), "Save".into()]) + .with_default(Binding::parse("Cmd+S").unwrap()); +let mut keymap = Keymap::new(vec![save], Scopes::new(), Platform::Windows); + +let read = |text: &str| ForeignKey::read(Some("Default"), text, Flavor::Windows); +let set = ForeignSet { + name: Some("My Set".into()), + entries: vec![ + ForeignEntry::new(Some("File"), ["Save"]).with_key(read("Ctrl+Alt+S")).at_line(12), + ForeignEntry::new(Some("File"), ["Frobnicate"]).with_key(read("Ctrl+F")).at_line(13), + ], +}; +let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], ..ImportOptions::default() }; +let planned = plan(&set, &keymap, &options); +// A review UI can show planned.commands and planned.report here. +let report = planned.apply(&mut keymap); +assert_eq!(report.changed[0].to, ["Cmd+Alt+S"]); +assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File > Frobnicate", Some(13))); +``` + +- Matching, most specific first, each step needing exactly one command: the user's remembered + answers, the full menu path, the joined submenu segments as a label in that menu, the label in + that menu, the label or an alias anywhere. Labels are compared after `import::normalize_label`. + Tool entries match only tools. +- `ImportOptions.contexts` says what each source context becomes (home scope, another scope, the + home scope only without a home entry, or skipped). +- The set wins: a chord it gives to a command is taken from commands outside it (except twins + sharing it as a default), a later entry takes a chord from an earlier one (as when the entries + are applied in file order; the earlier key is listed in `skipped`), and an entry without keys + can clear its command. +- Keys read approximately (a numeric keypad key bound as the main key) are listed in + `approximated`. +- With `ImportOptions.suggest`, unmatched entries get fuzzy candidates (`import::namematch`); + they are reported, never applied. Only the first 200 unmatched entries get them, and only the + first 200 characters of a name are compared. + +## Features + +- `egui`: conversions to and from egui keys and modifiers; `egui::matches`, which accepts the + shifted key egui reports for a Shift binding (`Shift+;` matches `:`); and `egui::Dispatcher`, + which runs a frame's key presses against the keymap: + + ```rust,ignore + let hits = ctx.input_mut(|i| dispatcher.dispatch(i, &keymap, &active)); + for hit in hits { + app.run(&hit.command); + } + ``` + + A press that runs a command is removed from egui's events, with the text it typed, so widgets + do not see it too. egui's Copy, Cut and Paste events count as Cmd+C, Cmd+X and Cmd+V outside + text fields. While a text field has the keyboard, clipboard events, clipboard key presses, + presses followed by text, and off macOS Ctrl+Alt with a letter, digit, punctuation or Space + stay with it: AltGr arrives as Ctrl+Alt on Windows and some Linux setups, and egui-winit sends + no text while Ctrl is held. + `Dispatcher::new().with_repeat(true)` also runs commands on key repeats (held arrows). diff --git a/crates/keymap/src/chord.rs b/crates/keymap/src/chord.rs new file mode 100644 index 000000000..740ccf211 --- /dev/null +++ b/crates/keymap/src/chord.rs @@ -0,0 +1,585 @@ +//! Keys, modifiers, chords and their text forms. +//! +//! Canonical text is `Cmd+Ctrl+Alt+Shift+Key`, written by [`Chord`]'s `Display` and read back by +//! [`Chord::parse`]. A double press is the chord twice, separated by a space: `A A`. + +use std::fmt; + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +pub mod foreign; + +/// The longest chord or trigger text [`Chord::parse`] and [`Trigger::parse`] accept, in bytes. +pub const MAX_CHORD_TEXT: usize = 64; + +/// The platform a keymap is used on. It decides display text and whether `ctrl` folds into `cmd`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Platform { + Mac, + Windows, + Linux, +} + +impl Platform { + /// The platform this build runs on. Web builds count as Linux. + pub const fn current() -> Platform { + if cfg!(target_os = "macos") { + Platform::Mac + } else if cfg!(target_os = "windows") { + Platform::Windows + } else { + Platform::Linux + } + } + + pub const fn is_mac(self) -> bool { + matches!(self, Platform::Mac) + } +} + +macro_rules! keys { + ($($variant:ident => $name:literal),* $(,)?) => { + /// A key on the keyboard, independent of any UI toolkit. + /// + /// Digits are the main row; numeric keypad keys map to the same keys. + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] + pub enum Key { + $($variant),* + } + + impl Key { + /// Every key, in declaration order. + pub const ALL: &'static [Key] = &[$(Key::$variant),*]; + + /// The canonical name: `K`, `5`, `F5`, `PageUp`, `;`. + pub const fn name(self) -> &'static str { + match self { + $(Key::$variant => $name),* + } + } + + // The Rust variant name, which is also egui's `Key` variant name except for arrows. + const fn variant_name(self) -> &'static str { + match self { + $(Key::$variant => stringify!($variant)),* + } + } + } + }; +} + +keys! { + A => "A", B => "B", C => "C", D => "D", E => "E", F => "F", G => "G", H => "H", I => "I", + J => "J", K => "K", L => "L", M => "M", N => "N", O => "O", P => "P", Q => "Q", R => "R", + S => "S", T => "T", U => "U", V => "V", W => "W", X => "X", Y => "Y", Z => "Z", + Num0 => "0", Num1 => "1", Num2 => "2", Num3 => "3", Num4 => "4", + Num5 => "5", Num6 => "6", Num7 => "7", Num8 => "8", Num9 => "9", + F1 => "F1", F2 => "F2", F3 => "F3", F4 => "F4", F5 => "F5", F6 => "F6", F7 => "F7", + F8 => "F8", F9 => "F9", F10 => "F10", F11 => "F11", F12 => "F12", F13 => "F13", + F14 => "F14", F15 => "F15", F16 => "F16", F17 => "F17", F18 => "F18", F19 => "F19", + F20 => "F20", F21 => "F21", F22 => "F22", F23 => "F23", F24 => "F24", F25 => "F25", + F26 => "F26", F27 => "F27", F28 => "F28", F29 => "F29", F30 => "F30", F31 => "F31", + F32 => "F32", F33 => "F33", F34 => "F34", F35 => "F35", + Escape => "Escape", Tab => "Tab", Backspace => "Backspace", Enter => "Enter", + Space => "Space", Insert => "Insert", Delete => "Delete", Home => "Home", End => "End", + PageUp => "PageUp", PageDown => "PageDown", + Up => "Up", Down => "Down", Left => "Left", Right => "Right", + Minus => "-", Equals => "=", Plus => "+", OpenBracket => "[", CloseBracket => "]", + Backslash => "\\", Semicolon => ";", Quote => "'", Backtick => "`", + Comma => ",", Period => ".", Slash => "/", + Colon => ":", Pipe => "|", Questionmark => "?", Exclamationmark => "!", + OpenCurlyBracket => "{", CloseCurlyBracket => "}", +} + +/// Key aliases beyond the canonical and egui variant names. Matched without regard to ASCII case. +const KEY_ALIASES: &[(&str, Key)] = &[ + ("esc", Key::Escape), + ("⎋", Key::Escape), + ("return", Key::Enter), + ("⏎", Key::Enter), + ("↩", Key::Enter), + ("del", Key::Delete), + ("⌦", Key::Delete), + ("⌫", Key::Backspace), + ("⇥", Key::Tab), + ("pgup", Key::PageUp), + ("pgdn", Key::PageDown), + ("page up", Key::PageUp), + ("page down", Key::PageDown), + ("arrowup", Key::Up), + ("arrowdown", Key::Down), + ("arrowleft", Key::Left), + ("arrowright", Key::Right), + ("↑", Key::Up), + ("↓", Key::Down), + ("←", Key::Left), + ("→", Key::Right), + ("spacebar", Key::Space), + ("ins", Key::Insert), + ("equal", Key::Equals), + ("grave", Key::Backtick), + ("backquote", Key::Backtick), + ("apostrophe", Key::Quote), +]; + +impl Key { + /// Reads a key name: canonical (`K`, `PageUp`, `;`), egui variant names (`ArrowUp`, `Num5`, + /// `Semicolon`) and the aliases `esc`, `return`, `del`, `pgup`, `pgdn`, `spacebar`, `ins`, + /// and the Mac key glyphs. Case does not matter. + pub fn parse(name: &str) -> Option { + Key::ALL + .iter() + .copied() + .find(|k| k.name().eq_ignore_ascii_case(name) || k.variant_name().eq_ignore_ascii_case(name)) + .or_else(|| KEY_ALIASES.iter().find(|(alias, _)| alias.eq_ignore_ascii_case(name)).map(|&(_, k)| k)) + } + + /// `F1` to `F35`. + pub const fn is_function_key(self) -> bool { + matches!( + self, + Key::F1 + | Key::F2 + | Key::F3 + | Key::F4 + | Key::F5 + | Key::F6 + | Key::F7 + | Key::F8 + | Key::F9 + | Key::F10 + | Key::F11 + | Key::F12 + | Key::F13 + | Key::F14 + | Key::F15 + | Key::F16 + | Key::F17 + | Key::F18 + | Key::F19 + | Key::F20 + | Key::F21 + | Key::F22 + | Key::F23 + | Key::F24 + | Key::F25 + | Key::F26 + | Key::F27 + | Key::F28 + | Key::F29 + | Key::F30 + | Key::F31 + | Key::F32 + | Key::F33 + | Key::F34 + | Key::F35 + ) + } + + /// The key as macOS menus show it: arrows and editing keys as glyphs. + fn mac_symbol(self) -> &'static str { + match self { + Key::Up => "↑", + Key::Down => "↓", + Key::Left => "←", + Key::Right => "→", + Key::Enter => "⏎", + Key::Backspace => "⌫", + Key::Delete => "⌦", + Key::Escape => "⎋", + Key::Tab => "⇥", + k => k.text_name(), + } + } + + /// The key as Windows and Linux show it. + fn text_name(self) -> &'static str { + match self { + Key::PageUp => "Page Up", + Key::PageDown => "Page Down", + k => k.name(), + } + } +} + +impl fmt::Display for Key { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +impl Serialize for Key { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.name()) + } +} + +impl<'de> Deserialize<'de> for Key { + fn deserialize>(deserializer: D) -> Result { + let text = >::deserialize(deserializer)?; + if text.len() > MAX_CHORD_TEXT { + return Err(serde::de::Error::custom(ParseError::TooLong)); + } + Key::parse(&text).ok_or_else(|| serde::de::Error::custom(ParseError::UnknownKey(text.into_owned()))) + } +} + +/// Modifier keys held with a chord's key. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct Mods { + /// The command modifier: ⌘ on macOS, Ctrl on Windows and Linux. + pub cmd: bool, + /// The Control key on macOS. Off macOS it folds into `cmd`. + pub ctrl: bool, + /// Alt, Option on macOS. + pub alt: bool, + pub shift: bool, +} + +impl Mods { + pub const NONE: Mods = Mods { cmd: false, ctrl: false, alt: false, shift: false }; + pub const CMD: Mods = Mods { cmd: true, ctrl: false, alt: false, shift: false }; + pub const CTRL: Mods = Mods { cmd: false, ctrl: true, alt: false, shift: false }; + pub const ALT: Mods = Mods { cmd: false, ctrl: false, alt: true, shift: false }; + pub const SHIFT: Mods = Mods { cmd: false, ctrl: false, alt: false, shift: true }; + + pub const fn is_none(self) -> bool { + !(self.cmd || self.ctrl || self.alt || self.shift) + } + + /// The modifiers as `platform` sees them: off macOS `ctrl` becomes `cmd`. + pub const fn effective(self, platform: Platform) -> Mods { + if platform.is_mac() || !self.ctrl { self } else { Mods { cmd: true, ctrl: false, ..self } } + } +} + +/// A key with modifiers. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Chord { + pub mods: Mods, + pub key: Key, +} + +/// Why chord or trigger text was refused. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ParseError { + Empty, + /// Longer than [`MAX_CHORD_TEXT`]. + TooLong, + /// Modifiers with no key, or a trailing `+`. + MissingKey, + UnknownKey(String), + UnknownModifier(String), + DuplicateModifier(String), + /// Two different chords: key sequences are not supported. + Sequence, +} + +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ParseError::Empty => f.write_str("empty shortcut"), + ParseError::TooLong => write!(f, "shortcut longer than {MAX_CHORD_TEXT} bytes"), + ParseError::MissingKey => f.write_str("shortcut has no key"), + ParseError::UnknownKey(k) => write!(f, "unknown key `{k}`"), + ParseError::UnknownModifier(m) => write!(f, "unknown modifier `{m}`"), + ParseError::DuplicateModifier(m) => write!(f, "modifier `{m}` given twice"), + ParseError::Sequence => f.write_str("key sequences are not supported"), + } + } +} + +impl std::error::Error for ParseError {} + +#[derive(Clone, Copy)] +enum Modifier { + Cmd, + Ctrl, + Alt, + Shift, +} + +fn modifier_named(name: &str) -> Option { + const NAMES: &[(&str, Modifier)] = &[ + ("cmd", Modifier::Cmd), + ("command", Modifier::Cmd), + ("meta", Modifier::Cmd), + ("super", Modifier::Cmd), + ("mod", Modifier::Cmd), + ("⌘", Modifier::Cmd), + ("ctrl", Modifier::Ctrl), + ("control", Modifier::Ctrl), + ("ctl", Modifier::Ctrl), + ("⌃", Modifier::Ctrl), + ("alt", Modifier::Alt), + ("opt", Modifier::Alt), + ("option", Modifier::Alt), + ("⌥", Modifier::Alt), + ("shift", Modifier::Shift), + ("⇧", Modifier::Shift), + ]; + NAMES.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|&(_, m)| m) +} + +/// A modifier glyph at the start of `text`, and the text after it. +fn strip_glyph(text: &str) -> Option<(Modifier, &str)> { + let mut chars = text.chars(); + let m = match chars.next()? { + '⌘' => Modifier::Cmd, + '⌃' => Modifier::Ctrl, + '⌥' => Modifier::Alt, + '⇧' => Modifier::Shift, + _ => return None, + }; + Some((m, chars.as_str())) +} + +fn add_modifier(mods: &mut Mods, m: Modifier, written: &str) -> Result<(), ParseError> { + let slot = match m { + Modifier::Cmd => &mut mods.cmd, + Modifier::Ctrl => &mut mods.ctrl, + Modifier::Alt => &mut mods.alt, + Modifier::Shift => &mut mods.shift, + }; + if *slot { + return Err(ParseError::DuplicateModifier(written.to_owned())); + } + *slot = true; + Ok(()) +} + +impl Chord { + pub const fn new(mods: Mods, key: Key) -> Chord { + Chord { mods, key } + } + + /// The key with no modifiers. + pub const fn plain(key: Key) -> Chord { + Chord { mods: Mods::NONE, key } + } + + /// Reads canonical text (`Cmd+Shift+Z`) and the common aliases: modifier words in any order + /// and case (`cmd command meta super mod`, `ctrl control ctl`, `alt opt option`, `shift`), + /// Mac glyphs, glued (`⇧⌘Z`) or with `+`, and the key names [`Key::parse`] reads. `Cmd++` is + /// Cmd with the Plus key. + pub fn parse(text: &str) -> Result { + if text.len() > MAX_CHORD_TEXT { + return Err(ParseError::TooLong); + } + let mut rest = text.trim(); + if rest.is_empty() { + return Err(ParseError::Empty); + } + let mut mods = Mods::NONE; + // Each pass consumes at least one byte, so the loop ends within MAX_CHORD_TEXT passes. + loop { + if let Some((m, after)) = strip_glyph(rest) { + add_modifier(&mut mods, m, rest.get(..rest.len() - after.len()).unwrap_or_default())?; + // `⌘+K` and `⌘K` are the same; in `⌘+` the `+` is the key. + rest = match after.strip_prefix('+') { + Some(r) if !r.is_empty() => r, + _ => after, + }; + if rest.trim().is_empty() { + return Err(ParseError::MissingKey); + } + continue; + } + // A `+` in first position is the Plus key, never a separator. + let first = rest.chars().next().map_or(0, char::len_utf8); + let separator = rest.get(first..).and_then(|r| r.find('+')).map(|i| i + first); + match separator { + Some(i) => { + let token = rest.get(..i).unwrap_or_default().trim(); + let after = rest.get(i + 1..).unwrap_or_default(); + if after.trim().is_empty() { + return Err(ParseError::MissingKey); + } + let m = modifier_named(token).ok_or_else(|| ParseError::UnknownModifier(token.to_owned()))?; + add_modifier(&mut mods, m, token)?; + rest = after; + } + None => { + let token = rest.trim(); + if modifier_named(token).is_some() { + return Err(ParseError::MissingKey); + } + let key = Key::parse(token).ok_or_else(|| ParseError::UnknownKey(token.to_owned()))?; + return Ok(Chord { mods, key }); + } + } + } + } + + /// Canonical text, the same as `to_string()`: `Cmd+Ctrl+Alt+Shift+Key`. + pub fn portable(&self) -> String { + self.to_string() + } + + /// The chord as `platform` sees it: off macOS `ctrl` folds into `cmd`. Lookups and conflict + /// checks compare effective chords. + pub const fn effective(self, platform: Platform) -> Chord { + Chord { mods: self.mods.effective(platform), key: self.key } + } + + /// Text for menus and settings: `⌃⌥⇧⌘K` on macOS, `Ctrl+Alt+Shift+K` elsewhere. + pub fn display(&self, platform: Platform) -> String { + let m = self.mods.effective(platform); + let mut s = String::new(); + if platform.is_mac() { + for (on, glyph) in [(m.ctrl, "⌃"), (m.alt, "⌥"), (m.shift, "⇧"), (m.cmd, "⌘")] { + if on { + s.push_str(glyph); + } + } + s.push_str(self.key.mac_symbol()); + } else { + for (on, name) in [(m.cmd, "Ctrl+"), (m.alt, "Alt+"), (m.shift, "Shift+")] { + if on { + s.push_str(name); + } + } + s.push_str(self.key.text_name()); + } + s + } + + pub const fn is_function_key(&self) -> bool { + self.key.is_function_key() + } + + /// No cmd, ctrl or alt. Shift alone still counts as plain: such chords are tool keys that + /// typing in a text field would trigger. + pub const fn is_plain(&self) -> bool { + !(self.mods.cmd || self.mods.ctrl || self.mods.alt) + } + + /// Holds the command modifier: cmd, or ctrl (Control on macOS, folded into cmd elsewhere). + pub const fn has_command(&self) -> bool { + self.mods.cmd || self.mods.ctrl + } +} + +impl From for Chord { + fn from(key: Key) -> Chord { + Chord::plain(key) + } +} + +impl fmt::Display for Chord { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for (on, name) in [(self.mods.cmd, "Cmd+"), (self.mods.ctrl, "Ctrl+"), (self.mods.alt, "Alt+"), (self.mods.shift, "Shift+")] { + if on { + f.write_str(name)?; + } + } + f.write_str(self.key.name()) + } +} + +impl std::str::FromStr for Chord { + type Err = ParseError; + fn from_str(s: &str) -> Result { + Chord::parse(s) + } +} + +impl Serialize for Chord { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_str(self) + } +} + +impl<'de> Deserialize<'de> for Chord { + fn deserialize>(deserializer: D) -> Result { + let text = >::deserialize(deserializer)?; + Chord::parse(&text).map_err(serde::de::Error::custom) + } +} + +/// What starts a command: a chord, pressed once or twice in a row. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Trigger { + pub chord: Chord, + /// The chord pressed twice. + pub double: bool, +} + +impl Trigger { + pub const fn single(chord: Chord) -> Trigger { + Trigger { chord, double: false } + } + + pub const fn double(chord: Chord) -> Trigger { + Trigger { chord, double: true } + } + + /// Reads a chord as [`Chord::parse`] does, or the same chord twice separated by whitespace + /// (`A A`) as a double press. Two different chords are [`ParseError::Sequence`]. + pub fn parse(text: &str) -> Result { + if text.len() > MAX_CHORD_TEXT { + return Err(ParseError::TooLong); + } + let single = match Chord::parse(text) { + Ok(chord) => return Ok(Trigger::single(chord)), + Err(e) => e, + }; + let mut parts = text.split_whitespace(); + match (parts.next(), parts.next(), parts.next()) { + (Some(first), Some(second), None) => { + let (first, second) = (Chord::parse(first)?, Chord::parse(second)?); + if first == second { Ok(Trigger::double(first)) } else { Err(ParseError::Sequence) } + } + _ => Err(single), + } + } + + /// Canonical text, the same as `to_string()`. + pub fn portable(&self) -> String { + self.to_string() + } + + pub const fn effective(self, platform: Platform) -> Trigger { + Trigger { chord: self.chord.effective(platform), double: self.double } + } + + /// [`Chord::display`], twice with a space between for a double press. + pub fn display(&self, platform: Platform) -> String { + let one = self.chord.display(platform); + if self.double { format!("{one} {one}") } else { one } + } +} + +impl From for Trigger { + fn from(chord: Chord) -> Trigger { + Trigger::single(chord) + } +} + +impl fmt::Display for Trigger { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.double { write!(f, "{0} {0}", self.chord) } else { write!(f, "{}", self.chord) } + } +} + +impl std::str::FromStr for Trigger { + type Err = ParseError; + fn from_str(s: &str) -> Result { + Trigger::parse(s) + } +} + +impl Serialize for Trigger { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_str(self) + } +} + +impl<'de> Deserialize<'de> for Trigger { + fn deserialize>(deserializer: D) -> Result { + let text = >::deserialize(deserializer)?; + Trigger::parse(&text).map_err(serde::de::Error::custom) + } +} diff --git a/crates/keymap/src/chord/foreign.rs b/crates/keymap/src/chord/foreign.rs new file mode 100644 index 000000000..b7e58a358 --- /dev/null +++ b/crates/keymap/src/chord/foreign.rs @@ -0,0 +1,195 @@ +//! Key text as other applications write it in their shortcut files and menus. +//! +//! Windows sets name the command modifier `Ctrl`; Mac sets name it `Cmd` and use `Ctrl` for the +//! Control key. [`read_foreign`] reads either into a [`Trigger`], tolerating separators +//! (`+`, `-`, space), spelled-out key names (`Page Down`, `Up Arrow`) and numeric keypad keys. + +use serde::{Deserialize, Serialize}; + +use super::{Chord, Key, MAX_CHORD_TEXT, Mods, Trigger}; + +/// Which modifier naming a shortcut set uses. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Flavor { + /// `Ctrl` is the command modifier. + Windows, + /// `Cmd` is the command modifier and `Ctrl` the Control key. + Mac, +} + +impl Flavor { + /// Mac when any text names cmd, command, opt or option, or uses ⌘ or ⌥; Windows otherwise. + pub fn detect(texts: I) -> Flavor + where + I: IntoIterator, + S: AsRef, + { + let mac = texts.into_iter().any(|t| { + let t = t.as_ref(); + t.contains(['⌘', '⌥']) || { + let lower = t.to_ascii_lowercase(); + lower.contains("cmd") || lower.contains("command") || lower.contains("opt") + } + }); + if mac { Flavor::Mac } else { Flavor::Windows } + } +} + +/// Something [`read_foreign`] changed while reading that an import report may mention. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub enum ReadNote { + /// A numeric keypad key was read as the main key of the same name. + Numpad, +} + +/// Why foreign key text could not be read. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ForeignError { + Empty, + /// Longer than [`MAX_CHORD_TEXT`]. + TooLong, + UnknownKey(String), + /// A modifier with no counterpart here, such as the Windows key. + UnsupportedModifier(String), +} + +impl std::fmt::Display for ForeignError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ForeignError::Empty => f.write_str("empty shortcut"), + ForeignError::TooLong => write!(f, "shortcut longer than {MAX_CHORD_TEXT} bytes"), + ForeignError::UnknownKey(k) => write!(f, "unknown key `{k}`"), + ForeignError::UnsupportedModifier(m) => write!(f, "unsupported modifier `{m}`"), + } + } +} + +impl std::error::Error for ForeignError {} + +#[derive(Clone, Copy)] +enum Word { + Command, + Control, + Alt, + Shift, + Unsupported, +} + +const GLYPHS: &[(char, Word)] = &[('⌘', Word::Command), ('⌃', Word::Control), ('⌥', Word::Alt), ('⇧', Word::Shift)]; + +// Longer words first where one is a prefix of another. +const WORDS: &[(&str, Word)] = &[ + ("command", Word::Command), + ("cmd", Word::Command), + ("control", Word::Control), + ("ctrl", Word::Control), + ("option", Word::Alt), + ("opt", Word::Alt), + ("alt", Word::Alt), + ("shift", Word::Shift), + ("windows", Word::Unsupported), + ("win", Word::Unsupported), + ("meta", Word::Unsupported), + ("super", Word::Unsupported), +]; + +/// Key names some applications use that [`Key::parse`] does not read. Compared after removing +/// whitespace and lower-casing. +const FOREIGN_KEYS: &[(&str, Key)] = &[ + ("uparrow", Key::Up), + ("downarrow", Key::Down), + ("leftarrow", Key::Left), + ("rightarrow", Key::Right), + ("pageup", Key::PageUp), + ("pagedown", Key::PageDown), + ("⇞", Key::PageUp), + ("⇟", Key::PageDown), + ("↖", Key::Home), + ("↘", Key::End), + ("⌤", Key::Enter), + ("forwarddelete", Key::Delete), + ("help", Key::Insert), +]; + +/// Reads one shortcut as another application writes it: `Shift+Ctrl+S`, `Ctrl+Num 5`, +/// `Page Down`, `⇧⌘S`, `Opt-Left`. `flavor` decides what `Ctrl` means. The notes say what was +/// approximated. +pub fn read_foreign(text: &str, flavor: Flavor) -> Result<(Trigger, Vec), ForeignError> { + if text.len() > MAX_CHORD_TEXT { + return Err(ForeignError::TooLong); + } + let mut rest = text.trim(); + if rest.is_empty() { + return Err(ForeignError::Empty); + } + let mut mods = Mods::NONE; + // Each pass consumes at least one byte. + 'strip: loop { + for &(glyph, word) in GLYPHS { + if let Some(after) = rest.strip_prefix(glyph) { + apply(&mut mods, word, flavor, rest.get(..glyph.len_utf8()).unwrap_or_default())?; + let after = after.trim_start(); + rest = match after.strip_prefix('+') { + Some(r) if !r.trim().is_empty() => r.trim_start(), + _ => after, + }; + continue 'strip; + } + } + for &(name, word) in WORDS { + let (Some(head), Some(after)) = (rest.get(..name.len()), rest.get(name.len()..)) else { continue }; + // A modifier word needs a separator and a key after it: `Alt` alone is a key name. + let mut chars = after.chars(); + if head.eq_ignore_ascii_case(name) && matches!(chars.next(), Some('+' | '-' | ' ')) && !chars.as_str().trim().is_empty() { + apply(&mut mods, word, flavor, head)?; + rest = after_separator(chars.as_str()); + continue 'strip; + } + } + break; + } + let (key, numpad) = foreign_key(rest).ok_or_else(|| ForeignError::UnknownKey(rest.trim().to_owned()))?; + let notes = if numpad { vec![ReadNote::Numpad] } else { Vec::new() }; + Ok((Trigger::single(Chord::new(mods, key)), notes)) +} + +/// The text after a modifier word and its first separator; `Ctrl + S` reads like `Ctrl+S`. +fn after_separator(after: &str) -> &str { + let after = after.trim_start(); + match after.strip_prefix(['+', '-']) { + Some(r) if !r.trim().is_empty() => r.trim_start(), + _ => after, + } +} + +fn apply(mods: &mut Mods, word: Word, flavor: Flavor, written: &str) -> Result<(), ForeignError> { + match word { + Word::Command => mods.cmd = true, + Word::Control if flavor == Flavor::Mac => mods.ctrl = true, + Word::Control => mods.cmd = true, + Word::Alt => mods.alt = true, + Word::Shift => mods.shift = true, + Word::Unsupported => return Err(ForeignError::UnsupportedModifier(written.to_owned())), + } + Ok(()) +} + +/// The key a foreign key name stands for, and whether it was on the numeric keypad. +fn foreign_key(name: &str) -> Option<(Key, bool)> { + let squashed: String = name.chars().filter(|c| !c.is_whitespace()).collect::().to_ascii_lowercase(); + if squashed.is_empty() { + return None; + } + // egui reports keypad keys as the main keys, so `Num 5` binds `5`. + let keypad = squashed.strip_prefix("numpad").or_else(|| squashed.strip_prefix("num")).filter(|r| !r.is_empty() && *r != "lock"); + let (n, numpad) = match keypad { + Some(r) => (r, true), + None => (squashed.as_str(), false), + }; + let key = FOREIGN_KEYS.iter().find(|(alias, _)| *alias == n).map(|&(_, k)| k).or_else(|| Key::parse(n))?; + Some((key, numpad)) +} diff --git a/crates/keymap/src/command.rs b/crates/keymap/src/command.rs new file mode 100644 index 000000000..d297e7bc7 --- /dev/null +++ b/crates/keymap/src/command.rs @@ -0,0 +1,127 @@ +//! Commands with parameters and their binding keys. + +use std::fmt; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// Longest binding key [`CommandRef::parse_key`] accepts, in bytes. +pub const MAX_KEY: usize = 256; + +/// A command id with the parameters a binding runs it with. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CommandRef { + pub id: String, + /// `Null` for no parameters. + #[serde(default)] + pub params: Value, +} + +impl CommandRef { + /// A command without parameters. + pub fn new(id: impl Into) -> CommandRef { + CommandRef { id: id.into(), params: Value::Null } + } + + pub fn with_params(id: impl Into, params: Value) -> CommandRef { + CommandRef { id: id.into(), params } + } + + /// The binding key: the id, or `id {json}` with object keys sorted and no spaces. `Null` and + /// an empty object give the bare id. + pub fn key(&self) -> String { + match &self.params { + Value::Null => self.id.clone(), + Value::Object(m) if m.is_empty() => self.id.clone(), + p => { + let mut out = String::with_capacity(self.id.len() + 16); + out.push_str(&self.id); + out.push(' '); + write_canonical(p, &mut out); + out + } + } + } + + /// Reads a binding key: the id up to the first space, then JSON parameters. `None` for an + /// empty id, a key over [`MAX_KEY`] bytes or parameters that are not JSON. + pub fn parse_key(key: &str) -> Option { + if key.len() > MAX_KEY { + return None; + } + let (id, params) = match key.split_once(' ') { + Some((id, rest)) => (id, serde_json::from_str(rest).ok()?), + None => (key, Value::Null), + }; + if id.is_empty() || id.chars().any(char::is_whitespace) { + return None; + } + Some(CommandRef { id: id.to_string(), params }) + } +} + +impl fmt::Display for CommandRef { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.key()) + } +} + +impl From<&str> for CommandRef { + fn from(id: &str) -> CommandRef { + CommandRef::new(id) + } +} + +// Written by hand so the key does not depend on serde_json's map order: an app's dependency graph +// may turn on `preserve_order`. +fn write_canonical(v: &Value, out: &mut String) { + match v { + Value::Null => out.push_str("null"), + Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }), + Value::Number(n) => out.push_str(&n.to_string()), + Value::String(s) => write_string(s, out), + Value::Array(items) => { + out.push('['); + for (i, item) in items.iter().enumerate() { + if i > 0 { + out.push(','); + } + write_canonical(item, out); + } + out.push(']'); + } + Value::Object(map) => { + let mut keys: Vec<&String> = map.keys().collect(); + keys.sort(); + out.push('{'); + for (i, k) in keys.into_iter().enumerate() { + if i > 0 { + out.push(','); + } + write_string(k, out); + out.push(':'); + if let Some(item) = map.get(k) { + write_canonical(item, out); + } + } + out.push('}'); + } + } +} + +fn write_string(s: &str, out: &mut String) { + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); +} diff --git a/crates/keymap/src/egui.rs b/crates/keymap/src/egui.rs new file mode 100644 index 000000000..2d783839a --- /dev/null +++ b/crates/keymap/src/egui.rs @@ -0,0 +1,340 @@ +//! Conversions between the crate's keys and egui's, matching egui key presses to chords, and a +//! [`Dispatcher`] that turns a frame's key events into the commands they run. + +use ::egui::{Event, InputState, Key as EguiKey, KeyboardShortcut, Modifiers}; + +use crate::chord::{Chord, Key, Mods, Platform}; +use crate::command::CommandRef; +use crate::keymap::{Keymap, Lookup}; +use crate::scope::Active; + +// Both matches are generated from one list so that a key added to `Key` without an egui +// counterpart fails to compile. +macro_rules! egui_keys { + ($($ours:ident = $theirs:ident),* ; $($same:ident),* $(,)?) => { + impl Key { + /// The key for an egui key. `None` for modifier keys, Copy, Cut, Paste, BrowserBack + /// and IntlBackslash. + pub fn from_egui(key: EguiKey) -> Option { + match key { + $(EguiKey::$theirs => Some(Key::$ours),)* + $(EguiKey::$same => Some(Key::$same),)* + _ => None, + } + } + + pub fn to_egui(self) -> EguiKey { + match self { + $(Key::$ours => EguiKey::$theirs,)* + $(Key::$same => EguiKey::$same,)* + } + } + } + }; +} + +egui_keys! { + Up = ArrowUp, Down = ArrowDown, Left = ArrowLeft, Right = ArrowRight; + A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, + Num0, Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, + F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, + F21, F22, F23, F24, F25, F26, F27, F28, F29, F30, F31, F32, F33, F34, F35, + Escape, Tab, Backspace, Enter, Space, Insert, Delete, Home, End, PageUp, PageDown, + Minus, Equals, Plus, OpenBracket, CloseBracket, Backslash, Semicolon, Quote, Backtick, + Comma, Period, Slash, Colon, Pipe, Questionmark, Exclamationmark, OpenCurlyBracket, CloseCurlyBracket, +} + +impl Mods { + /// The modifiers egui reports, read for `platform`. On macOS cmd is ⌘ and ctrl the Control + /// key; elsewhere Ctrl is cmd and ctrl stays false. + pub fn from_egui(mods: &Modifiers, platform: Platform) -> Mods { + if platform.is_mac() { + // egui sets `command` together with `mac_cmd` on macOS; synthetic events may set + // only one of them. + Mods { cmd: mods.mac_cmd || mods.command, ctrl: mods.ctrl, alt: mods.alt, shift: mods.shift } + } else { + Mods { cmd: mods.ctrl || mods.command, ctrl: false, alt: mods.alt, shift: mods.shift } + } + } +} + +impl Chord { + /// The egui shortcut for this chord, for egui's own shortcut text and `consume_shortcut`. + /// cmd becomes egui's `command` and ctrl its `ctrl`, which egui folds the same way off + /// macOS. + pub fn to_egui_shortcut(&self) -> KeyboardShortcut { + let m = self.mods; + KeyboardShortcut::new(Modifiers { alt: m.alt, ctrl: m.ctrl, shift: m.shift, mac_cmd: false, command: m.cmd }, self.key.to_egui()) + } +} + +/// Base keys and the key egui reports for them with Shift held on a US layout. +const SHIFTED: &[(Key, Key)] = &[ + (Key::Semicolon, Key::Colon), + (Key::Slash, Key::Questionmark), + (Key::Backslash, Key::Pipe), + (Key::OpenBracket, Key::OpenCurlyBracket), + (Key::CloseBracket, Key::CloseCurlyBracket), + (Key::Equals, Key::Plus), + (Key::Num1, Key::Exclamationmark), +]; + +fn without_shift(m: Mods) -> Mods { + Mods { shift: false, ..m } +} + +/// Whether a key press egui reported triggers `binding` on `platform`. +/// +/// Besides an exact match: +/// - Shift with a base key matches the shifted key egui reports (`Shift+;` matches `:`). +/// - A shifted symbol bound without Shift matches when Shift is held to type it (`?`). +/// - A binding on `=` matches `+` with or without Shift, and a binding on `+` matches +/// `Shift+=`, so zoom keys work with and without Shift. +pub fn matches(binding: &Chord, key: EguiKey, mods: &Modifiers, platform: Platform) -> bool { + let Some(pressed) = Key::from_egui(key) else { return false }; + matches_press(binding, pressed, Mods::from_egui(mods, platform), platform) +} + +fn matches_press(binding: &Chord, pressed: Key, held: Mods, platform: Platform) -> bool { + let want = binding.effective(platform); + if pressed == want.key && held == want.mods { + return true; + } + let same_but_shift = without_shift(held) == without_shift(want.mods); + if !same_but_shift { + return false; + } + let shifted_of = |base: Key| SHIFTED.iter().find(|(b, _)| *b == base).map(|&(_, s)| s); + let is_shifted_symbol = SHIFTED.iter().any(|&(_, s)| s == want.key); + match (want.key, pressed) { + (Key::Equals, Key::Plus) => !want.mods.shift || held.shift, + (Key::Plus, Key::Equals) => held.shift && !want.mods.shift, + (w, p) if w == p => is_shifted_symbol && !want.mods.shift && held.shift, + (w, p) => want.mods.shift && held.shift && shifted_of(w) == Some(p), + } +} + +/// The chords a press can stand for, most specific first: the press itself, then those that keep +/// Shift (`Shift+;` for `:`), then those without it (`=` for `+`). Each one [`matches`] the press. +fn candidates(pressed: Key, held: Mods, platform: Platform) -> Vec { + let base = SHIFTED.iter().find(|&&(_, s)| s == pressed).map(|&(b, _)| b); + let swap = match pressed { + Key::Plus => Some(Key::Equals), + Key::Equals => Some(Key::Plus), + _ => None, + }; + let mut out = Vec::with_capacity(6); + for mods in [held, without_shift(held)] { + for key in [Some(pressed), base, swap].into_iter().flatten() { + let chord = Chord::new(mods, key); + if !out.contains(&chord) && matches_press(&chord, pressed, held, platform) { + out.push(chord); + } + } + } + out +} + +/// A command a key press runs. +/// Seconds within which a second press of the same chord counts as a double press. +pub const DOUBLE_PRESS: f64 = 0.6; + +#[derive(Clone, Debug, PartialEq)] +pub struct Hit { + /// The command to run; for tools sharing the chord, the first of `cycle`. + pub command: CommandRef, + /// Tools of one group sharing the chord, in catalogue order (the app picks the next one); + /// empty for a plain command. + pub cycle: Vec, +} + +impl Hit { + fn from_lookup(lookup: Lookup) -> Option { + match lookup { + Lookup::None => None, + Lookup::Run(command) => Some(Hit { command, cycle: Vec::new() }), + Lookup::Cycle(cycle) => Some(Hit { command: cycle.first()?.clone(), cycle }), + } + } +} + +#[derive(Clone, Copy, Debug)] +struct LastPress { + chord: Chord, + at: f64, + ran_double: bool, +} + +/// Runs a keymap against egui's input, one call per frame before the UI reads its keys. +/// +/// It reads key presses (repeats only when [`with_repeat`](Self::with_repeat) is on) and egui's +/// Copy, Cut and Paste events, which egui-winit sends in place of the Cmd+C, Cmd+X and Cmd+V +/// presses. A press that runs a command is removed from the events, together with the text it +/// typed when it has no command modifier, so no widget sees it too. Other events stay. +/// +/// While [`Active::typing`], the text field keeps, without lookup: +/// - clipboard events, and the clipboard key presses the web build sends with them (Cmd+C, Cmd+X, +/// Cmd+V, Shift+Delete, Shift+Insert, Ctrl+Insert); +/// - a press followed by a Text event before the next press, since it typed that text (the web +/// build's text agent can send these); +/// - off macOS, a printable key (letter, digit, punctuation, Space) pressed with Ctrl and Alt. +/// Windows and some Linux setups report AltGr as Ctrl+Alt, so AltGr+Q (`@` on a German layout) +/// arrives as Ctrl+Alt+Q, and egui-winit sends no Text event while Ctrl is held, so the press +/// cannot be told from a command chord. Ctrl+Alt with other keys (F-keys, arrows) still runs. +#[derive(Clone, Debug, Default)] +pub struct Dispatcher { + last: Option, + repeat: bool, +} + +impl Dispatcher { + pub fn new() -> Dispatcher { + Dispatcher::default() + } + + /// Whether held keys run their command again on each repeat (off by default), so a held + /// arrow can nudge. Repeats never count toward a double press. + pub fn with_repeat(mut self, on: bool) -> Dispatcher { + self.repeat = on; + self + } + + /// The commands this frame's key presses run with `active` focus, in press order. + /// + /// A chord pressed again within [`DOUBLE_PRESS`] runs its double binding when it has one; + /// the first press has already run the single binding. The press after a double starts over. + pub fn dispatch(&mut self, input: &mut InputState, keymap: &Keymap, active: &Active) -> Vec { + let platform = keymap.platform(); + let now = input.time; + let frame_mods = Mods::from_egui(&input.modifiers, platform); + let mut hits = Vec::new(); + let mut kept = Vec::with_capacity(input.events.len()); + // The Text event egui sends after a key press belongs to that press. + let mut drop_text = false; + // The web build sends both the Cmd+C key press and the Copy event it causes. + let mut clipboard_key = None; + let events = std::mem::take(&mut input.events); + let typed = if active.typing { typed_text(&events) } else { Vec::new() }; + for (i, event) in events.into_iter().enumerate() { + match &event { + Event::Key { key, pressed: true, repeat, modifiers, .. } if !*repeat || self.repeat => { + drop_text = false; + let held = Mods::from_egui(modifiers, platform); + if let Some(key) = Key::from_egui(*key) { + if active.typing && (typed.get(i) == Some(&true) || is_clipboard_press(key, held) || may_be_alt_gr(key, held, platform)) { + kept.push(event); + continue; + } + if held.cmd && matches!(key, Key::C | Key::X | Key::V) { + clipboard_key = Some(key); + } + if let Some(hit) = self.press(key, held, *repeat, now, keymap, active) { + hits.push(hit); + drop_text = !(held.cmd || held.ctrl); + continue; + } + } + } + Event::Text(_) if drop_text => { + drop_text = false; + continue; + } + // A focused text field copies and pastes on these events itself. + Event::Copy | Event::Cut | Event::Paste(_) if !active.typing => { + let (key, held) = clipboard_chord(&event, frame_mods); + if clipboard_key == Some(key) { + clipboard_key = None; + } else if let Some(hit) = self.press(key, held, false, now, keymap, active) { + hits.push(hit); + continue; + } + } + _ => {} + } + kept.push(event); + } + input.events = kept; + hits + } + + fn press(&mut self, key: Key, held: Mods, repeat: bool, now: f64, keymap: &Keymap, active: &Active) -> Option { + let chords = candidates(key, held, keymap.platform()); + let first = *chords.first()?; + let find = |double: bool| chords.iter().find_map(|c| Hit::from_lookup(keymap.lookup(c, double, active))); + if repeat { + return find(false); + } + let again = self.last.is_some_and(|l| l.chord == first && !l.ran_double && now >= l.at && now - l.at < DOUBLE_PRESS); + let double = if again { find(true) } else { None }; + self.last = Some(LastPress { chord: first, at: now, ran_double: double.is_some() }); + double.or_else(|| find(false)) + } +} + +/// For each event, whether it is a key press followed by a Text event before the next press. +fn typed_text(events: &[Event]) -> Vec { + let mut out = vec![false; events.len()]; + let mut text_ahead = false; + for (event, typed) in events.iter().zip(out.iter_mut()).rev() { + match event { + Event::Text(t) if !t.is_empty() => text_ahead = true, + Event::Key { pressed: true, .. } => { + *typed = text_ahead; + text_ahead = false; + } + _ => {} + } + } + out +} + +/// Whether a press could be AltGr typing a character: Ctrl+Alt off macOS on a key that types. +fn may_be_alt_gr(key: Key, held: Mods, platform: Platform) -> bool { + !platform.is_mac() && held.cmd && held.alt && types_text(key) +} + +/// Letters, digits, punctuation and Space. +fn types_text(key: Key) -> bool { + !key.is_function_key() + && !matches!( + key, + Key::Escape + | Key::Tab + | Key::Backspace + | Key::Enter + | Key::Insert + | Key::Delete + | Key::Home + | Key::End + | Key::PageUp + | Key::PageDown + | Key::Up + | Key::Down + | Key::Left + | Key::Right + ) +} + +/// Whether a press is one a backend turns into a Copy, Cut or Paste event. +fn is_clipboard_press(key: Key, held: Mods) -> bool { + match key { + Key::C | Key::X | Key::V => held.cmd, + Key::Delete => held.shift, + Key::Insert => held.shift || held.cmd || held.ctrl, + _ => false, + } +} + +/// The press a clipboard event stands for, with the modifiers held. Off macOS egui-winit also +/// sends Cut for Shift+Delete and Paste for Shift+Insert. +fn clipboard_chord(event: &Event, held: Mods) -> (Key, Mods) { + let with_cmd = Mods { cmd: true, ..held }; + let shift_only = held.shift && !held.cmd; + match event { + Event::Cut if shift_only => (Key::Delete, held), + Event::Cut => (Key::X, with_cmd), + Event::Paste(_) if shift_only => (Key::Insert, held), + Event::Paste(_) => (Key::V, with_cmd), + _ => (Key::C, with_cmd), + } +} diff --git a/crates/keymap/src/import.rs b/crates/keymap/src/import.rs new file mode 100644 index 000000000..2af0ed4a5 --- /dev/null +++ b/crates/keymap/src/import.rs @@ -0,0 +1,837 @@ +//! Importing another application's shortcut set. +//! +//! The app's reader turns a file into a [`ForeignSet`]. [`plan`] matches its entries to the +//! keymap's commands without changing anything, and [`ImportPlan::apply`] applies the plan and +//! returns an [`ImportReport`]. Matching and the apply rules are ported from the DesignCraft +//! InDesign importer (#1180). + +pub mod namematch; + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use serde::{Deserialize, Serialize}; + +use crate::chord::Trigger; +use crate::chord::foreign::{Flavor, ForeignError, ReadNote, read_foreign}; +use crate::command::CommandRef; +use crate::keymap::{Bindable, Binding, Keymap, Kind, MAX_BINDINGS, Policy}; +use crate::scope::Scope; + +/// Most entries of a set read; the rest are ignored and counted in [`ImportReport::truncated`]. +pub const MAX_IMPORT_ENTRIES: usize = 20_000; +/// Most keys read per entry. +pub const MAX_KEYS_PER_ENTRY: usize = 64; +/// Longest text field read, in chars; longer ones are cut. +pub const MAX_IMPORT_TEXT: usize = 1024; +/// Most path segments read per entry; the label (last segment) is always kept. +pub const MAX_PATH_SEGMENTS: usize = 32; +/// Most unmatched entries [`ImportOptions::suggest`] looks for commands for; the rest are counted +/// in [`ImportReport::truncated`]. +pub const MAX_SUGGESTIONS: usize = 200; + +/// A shortcut set as an app's reader found it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ForeignSet { + pub name: Option, + pub entries: Vec, +} + +/// One item of a foreign set. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ForeignEntry { + /// The top menu or product area as the source names it, without decoration such as a + /// trailing " Menu". + pub menu: Option, + /// Submenu segments and the item label; the label is last. + pub path: Vec, + /// Empty when the source says the item has no shortcut. + pub keys: Vec, + pub line: Option, + /// The item selects a tool. + pub is_tool: bool, +} + +impl ForeignEntry { + /// An entry without keys. + pub fn new>(menu: Option<&str>, path: impl IntoIterator) -> ForeignEntry { + ForeignEntry { menu: menu.map(str::to_string), path: path.into_iter().map(Into::into).collect(), ..ForeignEntry::default() } + } + + /// Marks the entry as selecting a tool. + pub fn tool(mut self) -> ForeignEntry { + self.is_tool = true; + self + } + + /// Adds a key after the others. + pub fn with_key(mut self, key: ForeignKey) -> ForeignEntry { + self.keys.push(key); + self + } + + /// The entry's line in the source file. + pub fn at_line(mut self, line: usize) -> ForeignEntry { + self.line = Some(line); + self + } + + /// The source's own path, menu first, joined with ` > `: the `item` of report rows. + pub fn item(&self) -> String { + self.menu.iter().chain(&self.path).map(String::as_str).collect::>().join(" > ") + } + + /// The key of [`ImportOptions::remembered`] for this entry: the normalised menu and path + /// joined by U+001F. + pub fn remember_key(&self) -> String { + self.menu.iter().chain(&self.path).map(|s| normalize_label(s)).collect::>().join("\u{1f}") + } +} + +/// One shortcut of an entry. +#[derive(Clone, Debug, PartialEq)] +pub struct ForeignKey { + /// The context the source gives (InDesign's `Default`, `Text`, …); `None` reads as a + /// [`ContextRule::Home`] context. + pub context: Option, + /// The key text as written, for reports. + pub text: String, + pub trigger: Result, + /// What reading the text approximated, reported in [`ImportReport::approximated`]. + pub notes: Vec, +} + +impl ForeignKey { + /// Reads `text` with [`read_foreign`]. + pub fn read(context: Option<&str>, text: &str, flavor: Flavor) -> ForeignKey { + let (trigger, notes) = match read_foreign(text, flavor) { + Ok((t, notes)) => (Ok(t), notes), + Err(e) => (Err(e), Vec::new()), + }; + ForeignKey { context: context.map(str::to_string), text: text.to_string(), trigger, notes } + } +} + +/// What keys in a source context become. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ContextRule { + /// Bindings in the command's home scope. + Home, + /// Bindings in this scope. + Scope(Scope), + /// Bindings in the home scope, only when the entry has no key in a [`ContextRule::Home`] + /// context (DesignCraft reads InDesign's `Text` context this way). + HomeWithoutHomeEntry, + /// Ignored without a report row. + Skip, +} + +/// What an import starts from. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Start { + /// The keymap's bindings as they are. + #[default] + Current, + /// Every command's defaults; other overrides are dropped. + Defaults, +} + +/// What an entry without keys does to its command. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum NoneDefined { + /// The command loses its shortcuts. + #[default] + Clear, + /// The command keeps its shortcuts. + Keep, +} + +/// How [`plan`] reads a set and how [`ImportPlan::apply`] applies it. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct ImportOptions { + /// Source contexts by name, compared case-insensitively. Keys in other contexts are reported + /// as [`UnmatchedReason::Context`]. + pub contexts: Vec<(String, ContextRule)>, + /// Earlier answers of the user, by [`ForeignEntry::remember_key`]. They are tried first. + pub remembered: BTreeMap, + pub start: Start, + pub none_defined: NoneDefined, + /// Look for likely commands for unmatched entries ([`ImportReport::suggestions`]). + pub suggest: bool, +} + +/// One planned binding, with the entry it came from. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PlannedBinding { + pub binding: Binding, + pub item: String, + pub line: Option, + /// The entry's position in the set: a later entry takes a chord from an earlier one. + pub order: usize, +} + +/// What the set says about one command, over every entry matched to it. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Planned { + pub command: CommandRef, + /// The first entry matched to it, and its line. + pub item: String, + pub line: Option, + pub bindings: Vec, + /// Every matched entry had no keys. + pub none_defined: bool, +} + +/// The result of [`plan`]: what would change, and the report rows known before applying. +/// +/// Serializable for a review UI; it does not deserialize, so every plan applied comes from +/// [`plan`] and keeps its caps. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ImportPlan { + /// In the order of their first entry. + pub commands: Vec, + pub start: Start, + pub none_defined: NoneDefined, + /// `unmatched`, `unreadable`, `approximated`, `suggestions` and the counts; + /// [`ImportPlan::apply`] adds the rest. + pub report: ImportReport, +} + +/// A command whose bindings the import changed. Shortcuts are binding texts. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Changed { + pub command: CommandRef, + pub label: String, + /// The first entry matched to the command, and its line. + pub item: String, + pub line: Option, + pub from: Vec, + pub to: Vec, +} + +/// A binding taken from a command outside the set. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Cleared { + pub command: CommandRef, + pub label: String, + pub shortcut: String, +} + +/// Why a key of the set was not bound. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SkipReason { + /// A later entry of the set takes the chord. + Taken, + /// The system takes the chord. + Reserved, + /// The binding's scope ([`ContextRule::Scope`]) is not one the keymap knows + /// ([`Keymap::knows_scope`]). + UnknownScope, +} + +/// A key of the set that was not bound. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Skipped { + pub command: CommandRef, + pub item: String, + pub line: Option, + pub shortcut: String, + /// The command of the later entry that takes the chord ([`SkipReason::Taken`]). + pub kept_by: Option, + pub reason: SkipReason, +} + +/// A change [`ImportPlan::apply`] could not make, so the command keeps the bindings it had. The +/// overrides had no room for another changed command ([`AssignError::Full`]), or the keymap lacks +/// the command (a plan applied to a keymap it was not made from). +/// +/// [`AssignError::Full`]: crate::AssignError::Full +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Failed { + pub command: CommandRef, + pub label: String, + pub change: FailedChange, + /// The set's shortcuts for [`FailedChange::Bind`], the one left on the command for + /// [`FailedChange::Unbind`]; empty for [`FailedChange::Clear`]. + pub shortcuts: Vec, +} + +/// What a [`Failed`] change was. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum FailedChange { + /// Giving the command the set's bindings. + Bind, + /// Leaving the command without shortcuts: the set has it without keys and + /// [`NoneDefined::Clear`] applies. + Clear, + /// Taking a chord the set gives to another command; both commands keep it. + Unbind, +} + +/// Why keys of an entry were not used. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum UnmatchedReason { + NoMatch, + /// Several commands fit and no match step picked one. + Ambiguous, + /// The keys are in contexts [`ImportOptions::contexts`] does not list. + Context, + /// Only a command of the other kind fits: a tool entry naming a command, or the other way round. + Tool, +} + +/// An entry with keys that was not used, or keys of a matched entry in unlisted contexts. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Unmatched { + pub item: String, + pub line: Option, + /// The keys as written, `: ` joined with `, `. + pub keys: String, + pub reason: UnmatchedReason, +} + +/// Keys of a matched entry that could not be read. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Unreadable { + pub item: String, + pub line: Option, + pub keys: String, + /// Why the first of them could not be read. + pub reason: ForeignError, +} + +/// Likely commands for an unmatched entry, best first. Never applied. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Suggestion { + pub item: String, + pub line: Option, + pub candidates: Vec, +} + +/// Keys of a matched entry that were read approximately, such as a numeric keypad key bound as +/// the main key of the same name. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Approximated { + pub item: String, + pub line: Option, + /// The keys with this note, as written: `: ` joined with `, `. + pub keys: String, + pub note: ReadNote, +} + +/// What an import did. Shortcuts are canonical binding texts; `item` is the source's path and +/// `line` the entry's [`ForeignEntry::line`]. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ImportReport { + pub set: Option, + /// Commands of the set whose bindings changed. + pub imported: usize, + pub changed: Vec, + pub conflicts_cleared: Vec, + pub skipped: Vec, + #[serde(default)] + pub failed: Vec, + pub unmatched: Vec, + /// Entries without keys that matched no command. + pub unmatched_without_shortcut: usize, + pub unreadable: Vec, + pub approximated: Vec, + pub suggestions: Vec, + /// Entries, keys, path segments, bindings and text fields cut at the caps, and unmatched + /// entries past [`MAX_SUGGESTIONS`] that got no suggestion. + pub truncated: usize, +} + +/// The matching form of a label or menu name: lower case, no `…`, `...` or `&`, single spaces, +/// and no leading `show/hide `, `show ` or `hide ` when something remains (sources name a toggle +/// by what choosing it does now). +pub fn normalize_label(s: &str) -> String { + let s = s.replace('…', "").replace("...", "").replace('&', ""); + let s = s.split_whitespace().collect::>().join(" ").to_lowercase(); + ["show/hide ", "show ", "hide "].iter().find_map(|p| s.strip_prefix(p).filter(|r| !r.is_empty())).map_or_else(|| s.clone(), str::to_string) +} + +/// Matches `set` to the keymap's commands. Pure: the keymap is not changed. +pub fn plan(set: &ForeignSet, keymap: &Keymap, options: &ImportOptions) -> ImportPlan { + let mut cut = 0usize; + let mut report = ImportReport { set: set.name.as_deref().map(|n| cap_text(n, &mut cut)), ..ImportReport::default() }; + cut += set.entries.len().saturating_sub(MAX_IMPORT_ENTRIES); + let index = Index::new(keymap); + let contexts: Vec<(String, &ContextRule)> = options.contexts.iter().map(|(n, r)| (n.to_lowercase(), r)).collect(); + let mut commands: Vec = Vec::new(); + let mut planned_at: HashMap = HashMap::new(); + let mut to_suggest: Vec = Vec::new(); + + for (order, raw) in set.entries.iter().take(MAX_IMPORT_ENTRIES).enumerate() { + let entry = capped(raw, &mut cut); + let item = entry.item(); + let found = index.find(&entry, entry.is_tool, &options.remembered); + let Found::One(i) = found else { + if entry.keys.is_empty() { + report.unmatched_without_shortcut += 1; + continue; + } + let reason = match found { + Found::Many => UnmatchedReason::Ambiguous, + _ if matches!(index.find(&entry, !entry.is_tool, &BTreeMap::new()), Found::One(_)) => UnmatchedReason::Tool, + _ => UnmatchedReason::NoMatch, + }; + if options.suggest && reason != UnmatchedReason::Tool { + if to_suggest.len() < MAX_SUGGESTIONS { + let label = entry.path.last().cloned().unwrap_or_default(); + to_suggest.push(ToSuggest { item: item.clone(), line: entry.line, label, tool: entry.is_tool }); + } else { + cut += 1; + } + } + report.unmatched.push(Unmatched { item, line: entry.line, keys: keys_text(entry.keys.iter()), reason }); + continue; + }; + + let rule_of = |k: &ForeignKey| -> Option<&ContextRule> { + match &k.context { + None => Some(&ContextRule::Home), + Some(c) => { + let c = c.to_lowercase(); + contexts.iter().find(|(n, _)| *n == c).map(|(_, r)| *r) + } + } + }; + let has_home = entry.keys.iter().any(|k| rule_of(k) == Some(&ContextRule::Home)); + let mut unlisted = Vec::new(); + let mut unreadable = Vec::new(); + let mut approximated: Vec<(ReadNote, Vec<&ForeignKey>)> = Vec::new(); + let mut bindings = Vec::new(); + for k in &entry.keys { + let scope = match rule_of(k) { + None => { + unlisted.push(k); + continue; + } + Some(ContextRule::Skip) => continue, + Some(ContextRule::HomeWithoutHomeEntry) if has_home => continue, + Some(ContextRule::Home | ContextRule::HomeWithoutHomeEntry) => None, + Some(ContextRule::Scope(s)) => Some(s.clone()), + }; + match &k.trigger { + Ok(t) => bindings.push(Binding { trigger: *t, scope }), + Err(e) => unreadable.push((k, e)), + } + for ¬e in &k.notes { + match approximated.iter_mut().find(|(n, _)| *n == note) { + Some((_, keys)) => keys.push(k), + None => approximated.push((note, vec![k])), + } + } + } + let line = entry.line; + if !unlisted.is_empty() { + report.unmatched.push(Unmatched { item: item.clone(), line, keys: keys_text(unlisted.into_iter()), reason: UnmatchedReason::Context }); + } + if let Some((_, e)) = unreadable.first() { + let reason = (*e).clone(); + report.unreadable.push(Unreadable { item: item.clone(), line, keys: keys_text(unreadable.iter().map(|(k, _)| *k)), reason }); + } + for (note, keys) in approximated { + report.approximated.push(Approximated { item: item.clone(), line, keys: keys_text(keys.into_iter()), note }); + } + + let at = *planned_at.entry(i).or_insert_with(|| { + let command = keymap.catalogue().get(i).map(|b| b.command.clone()).unwrap_or_else(|| CommandRef::new("")); + commands.push(Planned { command, item: item.clone(), line, bindings: Vec::new(), none_defined: true }); + commands.len() - 1 + }); + let Some(p) = commands.get_mut(at) else { continue }; + p.none_defined &= entry.keys.is_empty(); + for binding in bindings { + if p.bindings.iter().any(|b| b.binding == binding) { + continue; + } + if p.bindings.len() >= MAX_BINDINGS { + cut += 1; + continue; + } + p.bindings.push(PlannedBinding { binding, item: item.clone(), line, order }); + } + } + + if !to_suggest.is_empty() { + report.suggestions = suggest(keymap, &to_suggest); + } + report.truncated = cut; + ImportPlan { commands, start: options.start, none_defined: options.none_defined, report } +} + +impl ImportPlan { + /// Applies the plan to `keymap`, which should be the one it was made from. The set wins: a + /// chord it gives to a command is taken from other commands (except twins sharing it as a + /// default). Within the set, a later entry takes a chord from an earlier one, as when the + /// entries are applied in file order; the earlier entry's key is reported in + /// [`ImportReport::skipped`]. + /// + /// A change that finds the overrides full is left out and reported in + /// [`ImportReport::failed`]; the others still apply. With [`Start::Defaults`] that cannot + /// happen. + pub fn apply(&self, keymap: &mut Keymap) -> ImportReport { + let mut report = self.report.clone(); + let before: Vec> = self.commands.iter().map(|p| keymap.bindings(&p.command)).collect(); + // Dropping every entry leaves room for all of them: each catalogue command takes at most one + // entry, and the catalogue holds at most `MAX_COMMANDS`. + if self.start == Start::Defaults { + keymap.reset_all(); + } + let home_of = |km: &Keymap, c: &CommandRef| km.bindable(c).map_or_else(Scope::app, |b| b.scope.clone()); + + let mut claims: Vec<(usize, &PlannedBinding)> = + self.commands.iter().enumerate().flat_map(|(c, p)| p.bindings.iter().map(move |b| (c, b))).collect(); + claims.sort_by_key(|(_, b)| b.order); + let platform = keymap.platform(); + let mut taken: HashMap> = HashMap::new(); + let mut accepted: Vec> = vec![Vec::new(); self.commands.len()]; + for (c, pb) in claims { + let Some(p) = self.commands.get(c) else { continue }; + let shortcut = || pb.binding.text(&home_of(keymap, &p.command)); + let skip = + |reason| Skipped { command: p.command.clone(), item: pb.item.clone(), line: pb.line, shortcut: shortcut(), kept_by: None, reason }; + if keymap.is_reserved(&pb.binding.trigger.chord) { + report.skipped.push(skip(SkipReason::Reserved)); + continue; + } + if pb.binding.scope.as_ref().is_some_and(|s| !keymap.knows_scope(s)) { + report.skipped.push(skip(SkipReason::UnknownScope)); + continue; + } + let effective = pb.binding.trigger.effective(platform); + let (scope, tools) = match keymap.bindable(&p.command) { + Some(b) => (pb.binding.scope_or(&b.scope).clone(), if let Kind::Tool { group } = &b.kind { Some(group.clone()) } else { None }), + None => (pb.binding.scope.clone().unwrap_or_else(Scope::app), None), + }; + let groups = taken.entry(effective).or_default(); + let mut lost: Vec<(usize, &PlannedBinding)> = Vec::new(); + for g in groups.iter_mut().filter(|g| !(tools.is_some() && g.tools == tools) && keymap.scopes().relation(&g.scope, &scope) == Some(true)) + { + g.holders.retain(|&(k, earlier)| { + let clash = + self.commands.get(k).is_some_and(|other| keymap.pair_clashes(&other.command, &earlier.binding, &p.command, &pb.binding)); + if clash { + lost.push((k, earlier)); + } + !clash + }); + } + for (k, earlier) in lost { + if let Some(list) = accepted.get_mut(k) { + list.retain(|b| !std::ptr::eq(*b, earlier)); + } + let Some(other) = self.commands.get(k) else { continue }; + report.skipped.push(Skipped { + command: other.command.clone(), + item: earlier.item.clone(), + line: earlier.line, + shortcut: earlier.binding.text(&home_of(keymap, &other.command)), + kept_by: Some(p.command.clone()), + reason: SkipReason::Taken, + }); + } + match groups.iter_mut().find(|g| g.scope == scope && g.tools == tools) { + Some(g) => g.holders.push((c, pb)), + None => groups.push(TakenGroup { scope, tools, holders: vec![(c, pb)] }), + } + if let Some(list) = accepted.get_mut(c) { + list.push(pb); + } + } + let accepted: Vec> = accepted.into_iter().map(|l| l.into_iter().map(|b| b.binding.clone()).collect()).collect(); + + let label_of = |km: &Keymap, c: &CommandRef| km.bindable(c).map(|b| b.label.clone()).unwrap_or_default(); + let mut decided: HashSet = HashSet::new(); + for (p, list) in self.commands.iter().zip(&accepted) { + let failed = |km: &Keymap, change, shortcuts| Failed { command: p.command.clone(), label: label_of(km, &p.command), change, shortcuts }; + if !list.is_empty() { + let list = in_default_order(keymap, &p.command, list); + if keymap.set_bindings(&p.command, list.clone(), Policy::Keep).is_err() { + let home = home_of(keymap, &p.command); + report.failed.push(failed(keymap, FailedChange::Bind, list.iter().map(|b| b.text(&home)).collect())); + continue; + } + } else if p.none_defined && self.none_defined == NoneDefined::Clear { + if !keymap.clear(&p.command) { + report.failed.push(failed(keymap, FailedChange::Clear, Vec::new())); + continue; + } + } else { + continue; + } + decided.insert(p.command.key()); + } + + for (p, list) in self.commands.iter().zip(&accepted) { + if list.is_empty() || !decided.contains(&p.command.key()) { + continue; + } + for h in keymap.clashing(&p.command, list) { + if decided.contains(&h.command.key()) { + continue; + } + let home = home_of(keymap, &h.command); + let label = label_of(keymap, &h.command); + let shortcut = h.binding.text(&home); + if keymap.remove(&h.command, &h.binding) { + report.conflicts_cleared.push(Cleared { command: h.command, label, shortcut }); + } else { + report.failed.push(Failed { command: h.command, label, change: FailedChange::Unbind, shortcuts: vec![shortcut] }); + } + } + } + + for (p, from) in self.commands.iter().zip(before) { + if !decided.contains(&p.command.key()) { + continue; + } + let to = keymap.bindings(&p.command); + if to == from { + continue; + } + let home = home_of(keymap, &p.command); + let texts = |l: &[Binding]| l.iter().map(|b| b.text(&home)).collect::>(); + report.changed.push(Changed { + command: p.command.clone(), + label: label_of(keymap, &p.command), + item: p.item.clone(), + line: p.line, + from: texts(&from), + to: texts(&to), + }); + } + report.imported = report.changed.len(); + report + } +} + +/// Claims of one chord that [`ImportPlan::apply`] accepted, with one scope and tool group (as +/// [`Keymap::conflicts`] groups them), so a claim is compared only with groups it can clash with. +struct TakenGroup<'a> { + scope: Scope, + /// The tool group, for tools. + tools: Option>, + /// Plan command index and claim. + holders: Vec<(usize, &'a PlannedBinding)>, +} + +/// `list` in the order of the command's defaults when it holds the same bindings, so an import +/// equal to the defaults leaves no override. +fn in_default_order(keymap: &Keymap, command: &CommandRef, list: &[Binding]) -> Vec { + let Some(home) = keymap.bindable(command).map(|b| b.scope.clone()) else { return list.to_vec() }; + let key = |b: &Binding| (b.trigger, b.scope_or(&home).clone()); + let defaults = keymap.default_bindings(command); + let mut a: Vec<_> = list.iter().map(key).collect(); + let mut d: Vec<_> = defaults.iter().map(key).collect(); + a.sort(); + d.sort(); + if a == d { defaults } else { list.to_vec() } +} + +fn keys_text<'a>(keys: impl Iterator) -> String { + keys.map(|k| match &k.context { + Some(c) => format!("{c}: {}", k.text), + None => k.text.clone(), + }) + .collect::>() + .join(", ") +} + +/// `s` cut to [`MAX_IMPORT_TEXT`] chars, counting a cut in `cut`. +fn cap_text(s: &str, cut: &mut usize) -> String { + match s.char_indices().nth(MAX_IMPORT_TEXT) { + Some((end, _)) => { + *cut += 1; + s.get(..end).unwrap_or_default().to_string() + } + None => s.to_string(), + } +} + +/// A copy of `e` within the caps. +fn capped(e: &ForeignEntry, cut: &mut usize) -> ForeignEntry { + let mut path: Vec = e.path.iter().take(MAX_PATH_SEGMENTS.saturating_sub(1)).map(|s| cap_text(s, cut)).collect(); + if e.path.len() > MAX_PATH_SEGMENTS { + *cut += e.path.len() - MAX_PATH_SEGMENTS; + } + if let Some(last) = e.path.get(path.len()..).and_then(<[String]>::last) { + path.push(cap_text(last, cut)); + } + *cut += e.keys.len().saturating_sub(MAX_KEYS_PER_ENTRY); + let keys = e + .keys + .iter() + .take(MAX_KEYS_PER_ENTRY) + .map(|k| ForeignKey { + context: k.context.as_deref().map(|c| cap_text(c, cut)), + text: cap_text(&k.text, cut), + trigger: match &k.trigger { + Ok(t) => Ok(*t), + Err(ForeignError::UnknownKey(s)) => Err(ForeignError::UnknownKey(cap_text(s, cut))), + Err(ForeignError::UnsupportedModifier(s)) => Err(ForeignError::UnsupportedModifier(cap_text(s, cut))), + Err(other) => Err(other.clone()), + }, + notes: k.notes.iter().fold(Vec::new(), |mut notes, n| { + if !notes.contains(n) { + notes.push(*n); + } + notes + }), + }) + .collect(); + ForeignEntry { menu: e.menu.as_deref().map(|m| cap_text(m, cut)), path, keys, line: e.line, is_tool: e.is_tool } +} + +enum Found { + One(usize), + Many, + None, +} + +/// The catalogue by normalised path and label, for the match steps. +struct Index { + tool: Vec, + /// Binding keys, for remembered answers. + keys: HashMap, + /// Normalised paths joined by U+001F. + paths: HashMap>, + /// (top menu, label) at any depth of that menu. + in_menu: HashMap<(String, String), Vec>, + /// Labels, aliases and path labels anywhere. + anywhere: HashMap>, +} + +fn add(map: &mut HashMap>, key: K, i: usize) { + let list = map.entry(key).or_default(); + if list.last() != Some(&i) { + list.push(i); + } +} + +impl Index { + fn new(keymap: &Keymap) -> Index { + let mut ix = Index { tool: Vec::new(), keys: HashMap::new(), paths: HashMap::new(), in_menu: HashMap::new(), anywhere: HashMap::new() }; + for (i, b) in keymap.catalogue().iter().enumerate() { + ix.tool.push(matches!(b.kind, Kind::Tool { .. })); + ix.keys.insert(b.command.key(), i); + let label = normalize_label(&b.label); + add(&mut ix.anywhere, label.clone(), i); + for a in &b.aliases { + add(&mut ix.anywhere, normalize_label(a), i); + } + for path in &b.paths { + let segs: Vec = path.iter().map(|s| normalize_label(s)).collect(); + add(&mut ix.paths, segs.join("\u{1f}"), i); + let Some(top) = segs.first() else { continue }; + add(&mut ix.in_menu, (top.clone(), label.clone()), i); + if let [_, .., last] = segs.as_slice() { + add(&mut ix.in_menu, (top.clone(), last.clone()), i); + add(&mut ix.anywhere, last.clone(), i); + } + } + } + ix + } + + fn pick(&self, list: Option<&Vec>, tool: bool) -> Found { + let mut fits = list.into_iter().flatten().filter(|i| self.tool.get(**i) == Some(&tool)); + match (fits.next(), fits.next()) { + (Some(i), None) => Found::One(*i), + (Some(_), Some(_)) => Found::Many, + _ => Found::None, + } + } + + /// The match steps in order; the first that finds exactly one command decides. + fn find(&self, entry: &ForeignEntry, tool: bool, remembered: &BTreeMap) -> Found { + if let Some(c) = remembered.get(&entry.remember_key()) + && let Some(&i) = self.keys.get(&c.key()) + && self.tool.get(i) == Some(&tool) + { + return Found::One(i); + } + let segs: Vec = entry.path.iter().map(|s| normalize_label(s)).collect(); + let Some(last) = segs.last() else { return Found::None }; + let menu = entry.menu.as_deref().map(normalize_label); + let full = menu.iter().chain(&segs).map(String::as_str).collect::>().join("\u{1f}"); + let mut steps = vec![self.paths.get(&full)]; + if let Some(m) = &menu { + if segs.len() > 1 { + steps.push(self.in_menu.get(&(m.clone(), segs.join(" ")))); + } + steps.push(self.in_menu.get(&(m.clone(), last.clone()))); + } + if menu.is_some() || segs.len() == 1 { + steps.push(self.anywhere.get(last)); + } + let mut many = false; + for list in steps { + match self.pick(list, tool) { + Found::One(i) => return Found::One(i), + Found::Many => many = true, + Found::None => {} + } + } + if many { Found::Many } else { Found::None } + } +} + +/// An unmatched entry to look for likely commands for. +struct ToSuggest { + item: String, + line: Option, + label: String, + tool: bool, +} + +/// Fuzzy candidates for unmatched entries, among commands of the same kind. +fn suggest(keymap: &Keymap, entries: &[ToSuggest]) -> Vec { + let pool = |tool: bool| -> Vec<&Bindable> { keymap.catalogue().iter().filter(|b| matches!(b.kind, Kind::Tool { .. }) == tool).collect() }; + let matcher = |pool: &[&Bindable]| { + let candidates: Vec = pool + .iter() + .map(|b| { + let labels = std::iter::once(&b.label).chain(&b.aliases).chain(b.paths.iter().filter_map(|p| p.last())).cloned().collect(); + namematch::Candidate { id: b.command.id.clone(), labels } + }) + .collect(); + namematch::Matcher::new(&candidates) + }; + let pools = [pool(false), pool(true)]; + let mut matchers: [Option; 2] = [None, None]; + let mut out = Vec::new(); + for ToSuggest { item, line, label, tool } in entries { + let k = usize::from(*tool); + let (Some(pool), Some(slot)) = (pools.get(k), matchers.get_mut(k)) else { continue }; + let picks = match slot.get_or_insert_with(|| matcher(pool)).propose(label) { + namematch::Proposal::Match(i, _) => vec![i], + namematch::Proposal::Choice(v) => v, + }; + let candidates: Vec = picks.iter().filter_map(|i| pool.get(*i)).map(|b| b.command.clone()).collect(); + if !candidates.is_empty() { + out.push(Suggestion { item: item.clone(), line: *line, candidates }); + } + } + out +} diff --git a/crates/keymap/src/import/namematch.rs b/crates/keymap/src/import/namematch.rs new file mode 100644 index 000000000..e889d1188 --- /dev/null +++ b/crates/keymap/src/import/namematch.rs @@ -0,0 +1,351 @@ +//! Fuzzy matching of a name another application's file writes (a shortcut set's item label) +//! against an app's commands, by their ids and labels only. A match is proposed when one candidate +//! scores well and clearly ahead of the next; otherwise the best few are offered to choose from. +//! +//! From VectorCraft `crates/engine/src/namematch.rs`: Dice coefficients over words and over +//! character pairs. + +use std::collections::HashMap; + +/// A command a name can stand for. +#[derive(Clone, Debug)] +pub struct Candidate { + /// A command id such as `select.all`; a `tool:` or `panel:` prefix is ignored. + pub id: String, + /// Its labels: the English one, the one in the interface language, other names. + pub labels: Vec, +} + +/// What a name stands for, as far as [`propose`] can tell. +#[derive(Clone, Debug, PartialEq)] +pub enum Proposal { + /// The candidate at this index of the list, with its score (0 to 1). + Match(usize, f64), + /// The best candidates, best first, when none stands out. + Choice(Vec), +} + +/// The lowest score [`Proposal::Match`] proposes. +pub const THRESHOLD: f64 = 0.6; +/// How far the best score must lead the next one to be proposed. +pub const MARGIN: f64 = 0.1; +/// The most candidates a [`Proposal::Choice`] lists. +pub const CHOICES: usize = 5; +/// The lowest score a [`Proposal::Choice`] lists. +pub const CHOICE_FLOOR: f64 = 0.3; +/// How many characters of a name or label are compared; the rest is ignored, so a long name +/// costs no more than this. +pub const MAX_NAME_CHARS: usize = 200; + +/// The first [`MAX_NAME_CHARS`] characters of `s`. +fn head(s: &str) -> &str { + s.char_indices().nth(MAX_NAME_CHARS).and_then(|(end, _)| s.get(..end)).unwrap_or(s) +} + +/// `s` with only its letters and digits, lowercased. +fn folded(s: &str) -> String { + s.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect() +} + +/// The words of `s`, lowercased: runs of letters and digits, split where a lowercase letter or a digit +/// meets an uppercase one (`selectAll`: `select`, `all`). +fn words(s: &str) -> Vec { + let mut out = vec![]; + let mut word = String::new(); + let mut prev_lower = false; + for c in s.chars() { + if !c.is_alphanumeric() { + if !word.is_empty() { + out.push(std::mem::take(&mut word)); + } + prev_lower = false; + continue; + } + if c.is_uppercase() && prev_lower && !word.is_empty() { + out.push(std::mem::take(&mut word)); + } + prev_lower = c.is_lowercase() || c.is_ascii_digit(); + word.extend(c.to_lowercase()); + } + if !word.is_empty() { + out.push(word); + } + out +} + +/// The words of a candidate's id: its segments after any `tool:` or `panel:`, split as [`words`]. +fn id_words(id: &str) -> Vec { + let id = id.strip_prefix("tool:").or_else(|| id.strip_prefix("panel:")).unwrap_or(id); + id.split('.').flat_map(words).collect() +} + +/// How many words `a` and `b` share, each word counted once, as a Dice coefficient (0 to 1). +fn word_overlap(a: &[String], b: &[String]) -> f64 { + if a.is_empty() || b.is_empty() { + return 0.0; + } + let mut rest: Vec<&String> = b.iter().collect(); + let mut shared = 0usize; + for w in a { + if let Some(i) = rest.iter().position(|x| *x == w) { + rest.swap_remove(i); + shared += 1; + } + } + (2 * shared) as f64 / (a.len() + b.len()) as f64 +} + +/// The pairs of neighboring characters in `s`. +fn pairs(s: &str) -> Vec<(char, char)> { + let c: Vec = s.chars().collect(); + c.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?))).collect() +} + +/// How many character pairs `a` and `b` (each sorted) share, as a Dice coefficient (0 to 1): for +/// names written without spaces. Linear in their lengths, so long names in a file stay quick. +fn pair_similarity(a: &[(char, char)], b: &[(char, char)]) -> f64 { + if a.is_empty() || b.is_empty() { + return 0.0; + } + let (mut i, mut j, mut shared) = (0usize, 0usize, 0usize); + while let (Some(p), Some(q)) = (a.get(i), b.get(j)) { + match p.cmp(q) { + std::cmp::Ordering::Less => i += 1, + std::cmp::Ordering::Greater => j += 1, + std::cmp::Ordering::Equal => { + shared += 1; + i += 1; + j += 1; + } + } + } + (2 * shared) as f64 / (a.len() + b.len()) as f64 +} + +/// A name or label as the scores compare it: its letters and digits (lowercased), its words and the +/// character pairs of the former (sorted). +struct Text { + folded: String, + words: Vec, + pairs: Vec<(char, char)>, +} + +impl Text { + fn of(s: &str) -> Self { + let s = head(s); + let folded = folded(s); + let mut pairs = pairs(&folded); + pairs.sort_unstable(); + Self { pairs, words: words(s), folded } + } +} + +/// A candidate as the scores compare it. +struct Prepared { + /// Its id's words, and those joined. + id_words: Vec, + id: String, + labels: Vec, +} + +impl Prepared { + fn of(c: &Candidate) -> Self { + let id_words = id_words(&c.id); + Self { id: id_words.concat(), id_words, labels: c.labels.iter().map(|l| Text::of(l)).collect() } + } + + /// See [`score`]. + fn score(&self, name: &Text) -> f64 { + if name.folded.is_empty() { + return 0.0; + } + if name.folded == self.id || self.labels.iter().any(|l| l.folded == name.folded) { + return 1.0; + } + let by_words = self.labels.iter().map(|l| word_overlap(&name.words, &l.words)).fold(word_overlap(&name.words, &self.id_words), f64::max); + let by_pairs = self.labels.iter().map(|l| pair_similarity(&name.pairs, &l.pairs)).fold(0.0, f64::max); + by_words.max(by_pairs * 0.9) + } +} + +/// How well `name` fits `candidate` (0 to 1): 1 when it equals a label or the id, its letters and +/// digits compared without case; else the best of word overlap and character-pair similarity, the +/// latter counted a little lower. Only the first [`MAX_NAME_CHARS`] characters of the name and +/// of each label count. +pub fn score(name: &str, candidate: &Candidate) -> f64 { + Prepared::of(candidate).score(&Text::of(name)) +} + +/// The candidate `name` stands for, when one scores at least 0.6 and 0.1 ahead of every other; else +/// the best five that score at least 0.3, to choose from. +pub fn propose(name: &str, candidates: &[Candidate]) -> Proposal { + Matcher::new(candidates).propose(name) +} + +/// [`propose`] for many names against the same candidates: each candidate's words and character +/// pairs are worked out once, and a name is scored only against the candidates that share a word or +/// a character pair with it (the others score 0). +pub struct Matcher { + prepared: Vec, + /// Candidates by their joined id words and their labels' letters and digits. + exact: HashMap>, + /// Candidates by a word of their id or labels. + by_word: HashMap>, + /// Candidates by a character pair of their labels. + by_pair: HashMap<(char, char), Vec>, +} + +impl Matcher { + /// Prepares `candidates` once for many [`Matcher::propose`] calls. + pub fn new(candidates: &[Candidate]) -> Self { + let prepared: Vec = candidates.iter().map(Prepared::of).collect(); + let (mut exact, mut by_word, mut by_pair) = (HashMap::new(), HashMap::new(), HashMap::new()); + fn add(map: &mut HashMap>, key: K, i: usize) { + let list = map.entry(key).or_default(); + if list.last() != Some(&i) { + list.push(i); + } + } + for (i, p) in prepared.iter().enumerate() { + add(&mut exact, p.id.clone(), i); + for l in &p.labels { + add(&mut exact, l.folded.clone(), i); + } + for w in p.id_words.iter().chain(p.labels.iter().flat_map(|l| &l.words)) { + add(&mut by_word, w.clone(), i); + } + for pair in p.labels.iter().flat_map(|l| &l.pairs) { + add(&mut by_pair, *pair, i); + } + } + Self { prepared, exact, by_word, by_pair } + } + + /// See [`propose`]. + pub fn propose(&self, name: &str) -> Proposal { + let text = Text::of(name); + let mut seen = vec![false; self.prepared.len()]; + let lists = self + .exact + .get(&text.folded) + .into_iter() + .chain(text.words.iter().filter_map(|w| self.by_word.get(w))) + // Each pair looked up once (they are sorted). + .chain(text.pairs.chunk_by(|a, b| a == b).filter_map(|c| self.by_pair.get(c.first()?))); + let mut scored: Vec<(usize, f64)> = vec![]; + for &i in lists.flatten() { + if let Some(s) = seen.get_mut(i) + && !*s + { + *s = true; + let score = self.prepared.get(i).map_or(0.0, |p| p.score(&text)); + if score >= CHOICE_FLOOR { + scored.push((i, score)); + } + } + } + scored.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0))); + match (scored.first(), scored.get(1)) { + (Some(&(i, best)), next) if best >= THRESHOLD && next.is_none_or(|n| best - n.1 >= MARGIN) => Proposal::Match(i, best), + _ => Proposal::Choice(scored.iter().take(CHOICES).map(|(i, _)| *i).collect()), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn candidates(list: &[(&str, &str)]) -> Vec { + list.iter().map(|(id, label)| Candidate { id: id.to_string(), labels: vec![label.to_string()] }).collect() + } + + fn proposed<'a>(name: &str, list: &'a [Candidate]) -> Option<&'a str> { + match propose(name, list) { + Proposal::Match(i, _) => list.get(i).map(|c| c.id.as_str()), + Proposal::Choice(_) => None, + } + } + + #[test] + fn extra_words_still_find_the_tool() { + let tools = candidates(&[ + ("tool:rectangle", "Rectangle Tool"), + ("tool:roundedRectangle", "Rounded Rectangle Tool"), + ("tool:rectangularGrid", "Rectangular Grid Tool"), + ("tool:ellipse", "Ellipse Tool"), + ]); + assert_eq!(proposed("Acme Rectangle Tool", &tools), Some("tool:rectangle")); + assert_eq!(proposed("Rounded Rectangle", &tools), Some("tool:roundedRectangle")); + assert_eq!(proposed("ellipse tool", &tools), Some("tool:ellipse"), "case aside, the label itself"); + } + + #[test] + fn letters_only_names_match_ids() { + let commands = candidates(&[("acme.copyAll", "Everything"), ("acme.copyAllOnPage", "Everything on This Page"), ("acme.clear", "Clear Out")]); + assert_eq!(proposed("acmecopyall", &commands), Some("acme.copyAll")); + assert_eq!(proposed("Acme Copy All On Page", &commands), Some("acme.copyAllOnPage")); + assert_eq!(proposed("clear out", &commands), Some("acme.clear")); + } + + #[test] + fn ties_need_a_choice() { + let tools = candidates(&[("tool:rectangle", "Rectangle Tool"), ("tool:ellipse", "Ellipse Tool"), ("tool:star", "Star Tool")]); + assert_eq!(propose("Tool", &tools), Proposal::Choice(vec![0, 1, 2])); + assert_eq!(propose("Nothing Alike", &tools), Proposal::Choice(vec![])); + assert_eq!(propose("", &tools), Proposal::Choice(vec![])); + } + + #[test] + fn names_without_spaces_match_by_character_pairs() { + let list = vec![ + Candidate { id: "tool:rectangle".into(), labels: vec!["Rectangle Tool".into(), "長方形ツール".into()] }, + Candidate { id: "tool:ellipse".into(), labels: vec!["Ellipse Tool".into(), "楕円形ツール".into()] }, + ]; + assert_eq!(proposed("長方形ツール", &list), Some("tool:rectangle")); + assert_eq!(proposed("楕円形 ツール", &list), Some("tool:ellipse"), "spaces and punctuation aside"); + assert_eq!(proposed("楕円形ツール2", &list), Some("tool:ellipse"), "most character pairs shared"); + } + + #[test] + fn the_index_finds_what_scoring_every_candidate_finds() { + let list = candidates(&[ + ("tool:rectangle", "Rectangle Tool"), + ("tool:roundedRectangle", "Rounded Rectangle Tool"), + ("tool:ellipse", "Ellipse Tool"), + ("select.all", "All"), + ("select.none", "Deselect"), + ("edit.undo", "Undo"), + ("foo.bar", "Zzz"), + ("panel:layers", "Layers"), + ]); + let matcher = Matcher::new(&list); + for name in ["Acme Rectangle Tool", "rounded", "acmecopyall", "foobar", "zz", "Lay", "Undo Redo", "ツール", "", "e"] { + let mut scored: Vec<(usize, f64)> = + list.iter().enumerate().map(|(i, c)| (i, score(name, c))).filter(|(_, s)| *s >= CHOICE_FLOOR).collect(); + scored.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0))); + let every = match (scored.first(), scored.get(1)) { + (Some(&(i, best)), next) if best >= THRESHOLD && next.is_none_or(|n| best - n.1 >= MARGIN) => Proposal::Match(i, best), + _ => Proposal::Choice(scored.iter().take(CHOICES).map(|(i, _)| *i).collect()), + }; + assert_eq!(matcher.propose(name), every, "{name}"); + } + assert_eq!(proposed("foobar", &list), Some("foo.bar"), "the id alone, sharing no word or pair with the label"); + } + + #[test] + fn only_the_head_of_a_long_name_counts() { + let label: String = "ä€𝄞b".repeat(50); + let candidate = Candidate { id: "acme.long".into(), labels: vec![label.clone()] }; + assert_eq!(head(&label).chars().count(), MAX_NAME_CHARS); + assert_eq!(score(&format!("{label}and more words after the head"), &candidate), 1.0); + assert_eq!(head("short"), "short"); + } + + #[test] + fn words_split_camel_case_and_separators() { + assert_eq!(words("selectAll_onArtboard 2x"), ["select", "all", "on", "artboard", "2x"]); + assert_eq!(words("Acme\u{a0}Lasso-Tool"), ["acme", "lasso", "tool"]); + assert_eq!(id_words("tool:roundedRectangle"), ["rounded", "rectangle"]); + } +} diff --git a/crates/keymap/src/keymap.rs b/crates/keymap/src/keymap.rs new file mode 100644 index 000000000..6281868ee --- /dev/null +++ b/crates/keymap/src/keymap.rs @@ -0,0 +1,947 @@ +//! A command catalogue with default bindings, the user's overrides, dispatch and conflicts. + +pub(crate) mod overrides; + +use std::collections::{BTreeSet, HashMap, HashSet}; +use std::fmt; + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +use crate::chord::{Chord, ParseError, Platform, Trigger}; +use crate::command::{CommandRef, MAX_KEY}; +use crate::scope::{Active, Scope, ScopeKind, Scopes}; + +pub use overrides::Overrides; + +/// Most commands a catalogue or an [`Overrides`] holds. +pub const MAX_COMMANDS: usize = 4096; +/// Most bindings per command. +pub const MAX_BINDINGS: usize = 16; +/// Longest binding text, in bytes. +pub const MAX_BINDING_TEXT: usize = 128; +/// Most entries [`Keymap::conflicts`] returns. +pub const MAX_CONFLICTS: usize = 4096; + +/// What a binding does when pressed. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Kind { + #[default] + Command, + /// Selects a tool. Tools of one group share keys and cycle; tools without a group name form one + /// group together. + Tool { group: Option }, +} + +/// A trigger in a scope. `scope: None` is the command's home scope. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Binding { + pub trigger: Trigger, + pub scope: Option, +} + +/// Why binding text was refused. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BindingError { + TooLong, + /// The part before `": "` is not a scope name. + Scope, + Trigger(ParseError), +} + +impl fmt::Display for BindingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + BindingError::TooLong => write!(f, "binding text over {MAX_BINDING_TEXT} bytes"), + BindingError::Scope => f.write_str("bad scope name"), + BindingError::Trigger(e) => e.fmt(f), + } + } +} + +impl std::error::Error for BindingError {} + +impl Binding { + /// A binding in the command's home scope. + pub fn new(trigger: impl Into) -> Binding { + Binding { trigger: trigger.into(), scope: None } + } + + pub fn in_scope(trigger: impl Into, scope: Scope) -> Binding { + Binding { trigger: trigger.into(), scope: Some(scope) } + } + + /// Reads `` or `: `. The whole text is tried as a trigger first, so + /// `Cmd+: Cmd+:` is the Colon chord pressed twice; otherwise it is split at the first `": "`. + pub fn parse(text: &str) -> Result { + if text.len() > MAX_BINDING_TEXT { + return Err(BindingError::TooLong); + } + let whole = match Trigger::parse(text.trim()) { + Ok(trigger) => return Ok(Binding::new(trigger)), + Err(e) => e, + }; + match text.split_once(": ") { + Some((scope, trigger)) => { + let scope = Scope::new(scope.trim()).ok_or(BindingError::Scope)?; + let trigger = Trigger::parse(trigger.trim()).map_err(BindingError::Trigger)?; + Ok(Binding::in_scope(trigger, scope)) + } + None => Err(BindingError::Trigger(whole)), + } + } + + /// The binding text for a command whose home scope is `home`: the scope is written only when + /// it differs. + pub fn text(&self, home: &Scope) -> String { + match &self.scope { + Some(s) if s != home => format!("{s}: {}", self.trigger), + _ => self.trigger.to_string(), + } + } + + /// The scope, `home` when unset. + pub fn scope_or<'a>(&'a self, home: &'a Scope) -> &'a Scope { + self.scope.as_ref().unwrap_or(home) + } +} + +impl fmt::Display for Binding { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.scope { + Some(s) => write!(f, "{s}: {}", self.trigger), + None => write!(f, "{}", self.trigger), + } + } +} + +impl Serialize for Binding { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_str(self) + } +} + +impl<'de> Deserialize<'de> for Binding { + fn deserialize>(deserializer: D) -> Result { + let text = >::deserialize(deserializer)?; + Binding::parse(&text).map_err(serde::de::Error::custom) + } +} + +/// A command the user can bind, as the app describes it. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Bindable { + pub command: CommandRef, + pub label: String, + /// Menu paths, the main one first; used by search and import. + #[serde(default)] + pub paths: Vec>, + /// Other names: labels in other UI languages, older names. + #[serde(default)] + pub aliases: Vec, + /// Home scope. + pub scope: Scope, + #[serde(default)] + pub kind: Kind, + #[serde(default)] + pub defaults: Vec, +} + +impl Bindable { + /// A command in `scope` without default bindings. + pub fn new(command: impl Into, label: impl Into, scope: Scope) -> Bindable { + Bindable { + command: command.into(), + label: label.into(), + paths: Vec::new(), + aliases: Vec::new(), + scope, + kind: Kind::Command, + defaults: Vec::new(), + } + } + + pub fn with_kind(mut self, kind: Kind) -> Bindable { + self.kind = kind; + self + } + + pub fn with_default(mut self, binding: Binding) -> Bindable { + self.defaults.push(binding); + self + } + + pub fn with_path(mut self, path: Vec) -> Bindable { + self.paths.push(path); + self + } + + pub fn with_alias(mut self, alias: impl Into) -> Bindable { + self.aliases.push(alias.into()); + self + } +} + +/// Which chords work while a text field has the keyboard. Bindings in an active context always +/// work: a `Text: Cmd+B` binding is meant for typing. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum TypingRule { + /// Plain chords (no cmd, ctrl or alt) go to the text; function keys still fire. + #[default] + PlainKeysWait, + /// Only chords with the command modifier and function keys fire. + CommandKeysOnly, + /// Nothing fires. + AllWait, +} + +impl TypingRule { + /// Whether `chord` may fire while typing. + pub fn fires(self, chord: &Chord) -> bool { + match self { + TypingRule::PlainKeysWait => !chord.is_plain() || chord.is_function_key(), + TypingRule::CommandKeysOnly => chord.has_command() || chord.is_function_key(), + TypingRule::AllWait => false, + } + } +} + +/// What a key press runs. +#[derive(Clone, Debug, PartialEq)] +pub enum Lookup { + None, + Run(CommandRef), + /// Tools of one group share the chord: the app picks the next one (catalogue order). + Cycle(Vec), +} + +/// What to do with other commands that hold a chord being assigned. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Policy { + /// Remove the chord from them. + #[default] + Steal, + /// Assign anyway; both keep it. + Keep, + /// Do not assign. + Refuse, +} + +/// A command's binding. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Holder { + pub command: CommandRef, + pub binding: Binding, +} + +/// The result of an assignment. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Assigned { + /// Bindings removed from other commands ([`Policy::Steal`]). + pub taken_from: Vec, + /// Bindings of other commands that now clash ([`Policy::Keep`]). + pub clashes: Vec, +} + +/// Why an assignment was refused. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum AssignError { + UnknownCommand, + /// The system takes this chord. + Reserved(Trigger), + /// More than [`MAX_BINDINGS`] bindings. + TooMany, + /// Other commands hold the chord ([`Policy::Refuse`]). + Taken(Vec), + /// A scope that is neither registered in [`Scopes`] nor used by the catalogue. + UnknownScope(Scope), + /// The change needs a new [`Overrides`] entry and it already holds [`MAX_COMMANDS`]. + Full, +} + +impl fmt::Display for AssignError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + AssignError::UnknownCommand => f.write_str("unknown command"), + AssignError::Reserved(t) => write!(f, "{t} is reserved by the system"), + AssignError::TooMany => write!(f, "more than {MAX_BINDINGS} bindings"), + AssignError::Taken(h) => write!(f, "in use by {} other command(s)", h.len()), + AssignError::UnknownScope(s) => write!(f, "unknown scope {s}"), + AssignError::Full => write!(f, "more than {MAX_COMMANDS} changed commands"), + } + } +} + +impl std::error::Error for AssignError {} + +/// Why loading dropped part of an [`Overrides`] entry. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum DropReason { + KeyTooLong, + /// The value is not a list of texts. + NotAList, + /// Items of the list that are not text. + NotText, + TextTooLong, + /// Texts past [`MAX_BINDINGS`]. + TooManyBindings, +} + +/// Something wrong in the stored overrides. Load reports these instead of failing. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Problem { + /// No command in the catalogue has this key; the entry is kept. + UnknownCommand { key: String }, + /// A text that does not parse; the entry keeps it. + BadBinding { key: String, text: String, error: BindingError }, + /// A reserved chord; not bound. + Reserved { key: String, text: String }, + /// A scope that is neither registered in [`Scopes`] nor used by the catalogue; not bound. + UnknownScope { key: String, text: String }, + /// Another entry names the same command; this one is ignored. + DuplicateKey { key: String }, + /// Part of an entry dropped while loading. + Dropped { key: String, reason: DropReason }, + /// Entries past [`MAX_COMMANDS`] dropped while loading. + TooManyCommands { ignored: usize }, +} + +/// How two bindings on one chord relate. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ConflictKind { + /// Only one of the two can run. + Clash, + /// Both work: the nearer scope runs where it applies, the other elsewhere. + Shadow, +} + +/// Two commands on one chord. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Conflict { + /// The effective trigger on the keymap's platform. + pub chord: Trigger, + pub a: (CommandRef, Binding), + pub b: (CommandRef, Binding), + pub kind: ConflictKind, + /// Both bindings are defaults. + pub in_defaults: bool, +} + +/// A binding with its scope resolved. +type Bound = (Trigger, Scope); + +/// A command's bindings on one chord grouped by scope and tool group, for [`Keymap::conflicts`]. +struct Group<'a> { + scope: &'a Scope, + /// The tool group for tools, `None` for other commands. + tools: Option<&'a Option>, + /// (position in the chord's list, command, binding). + items: Vec<(usize, usize, &'a Bound)>, +} + +/// Two holders of one chord: their positions in the chord's list, whether they clash, and each +/// one's command and binding. +type Pair<'a> = (usize, usize, bool, (usize, &'a Bound), (usize, &'a Bound)); + +/// The catalogue, the scope registry, the platform and the user's overrides. +#[derive(Clone, Debug)] +pub struct Keymap { + catalogue: Vec, + keys: Vec, + index: HashMap, + defaults: Vec>, + current: Vec>, + /// Effective trigger → (command, position in its `current` list), kept in step with `current`. + by_trigger: HashMap>, + /// The overrides entry each command reads, when it has one. + stored: Vec>, + /// Home and default scopes of the catalogue. + catalogue_scopes: HashSet, + scopes: Scopes, + platform: Platform, + typing: TypingRule, + reserved: Vec, + overrides: Overrides, +} + +impl Keymap { + /// A keymap with default bindings. Entries past [`MAX_COMMANDS`], with a key over + /// [`MAX_KEY`] bytes, or repeating an earlier key are left out. + pub fn new(catalogue: Vec, scopes: Scopes, platform: Platform) -> Keymap { + let mut km = Keymap { + catalogue: Vec::new(), + keys: Vec::new(), + index: HashMap::new(), + defaults: Vec::new(), + current: Vec::new(), + by_trigger: HashMap::new(), + stored: Vec::new(), + catalogue_scopes: HashSet::new(), + scopes, + platform, + typing: TypingRule::default(), + reserved: Vec::new(), + overrides: Overrides::new(), + }; + for b in catalogue { + let key = b.command.key(); + if km.catalogue.len() >= MAX_COMMANDS || key.len() > MAX_KEY || km.index.contains_key(&key) { + continue; + } + let defaults = km.normalize(b.defaults.iter().cloned(), &b.scope); + km.catalogue_scopes.insert(b.scope.clone()); + km.catalogue_scopes.extend(defaults.iter().map(|(_, s)| s.clone())); + km.index.insert(key.clone(), km.catalogue.len()); + km.keys.push(key); + km.current.push(defaults.clone()); + km.defaults.push(defaults); + km.stored.push(None); + km.catalogue.push(b); + } + km.rebuild_index(); + km + } + + pub fn with_typing_rule(mut self, rule: TypingRule) -> Keymap { + self.typing = rule; + self + } + + /// Chords that cannot be assigned, e.g. [`reserved::system`](crate::reserved::system). + pub fn with_reserved(mut self, chords: Vec) -> Keymap { + self.reserved = chords; + self.reload(); + self + } + + pub fn with_overrides(mut self, overrides: Overrides) -> Keymap { + self.set_overrides(overrides); + self + } + + pub fn set_overrides(&mut self, overrides: Overrides) { + self.overrides = overrides; + self.reload(); + } + + pub fn overrides(&self) -> &Overrides { + &self.overrides + } + + pub fn platform(&self) -> Platform { + self.platform + } + + pub fn scopes(&self) -> &Scopes { + &self.scopes + } + + pub fn typing_rule(&self) -> TypingRule { + self.typing + } + + pub fn catalogue(&self) -> &[Bindable] { + &self.catalogue + } + + pub fn bindable(&self, command: &CommandRef) -> Option<&Bindable> { + self.find(command).map(|i| &self.catalogue[i]) + } + + /// The effective bindings of a command; empty for an unknown one. + pub fn bindings(&self, command: &CommandRef) -> Vec { + self.find(command).map(|i| self.current[i].iter().map(|b| self.public(i, b)).collect()).unwrap_or_default() + } + + /// The default bindings of a command; empty for an unknown one. + pub fn default_bindings(&self, command: &CommandRef) -> Vec { + self.find(command).map(|i| self.defaults[i].iter().map(|b| self.public(i, b)).collect()).unwrap_or_default() + } + + pub fn is_reserved(&self, chord: &Chord) -> bool { + let c = chord.effective(self.platform); + self.reserved.iter().any(|r| r.effective(self.platform) == c) + } + + /// Whether bindings may use `scope`: the application, a scope registered in [`Scopes`], or a + /// home or default scope of the catalogue. + pub fn knows_scope(&self, scope: &Scope) -> bool { + scope.is_app() || self.scopes.knows(scope) || self.catalogue_scopes.contains(scope) + } + + /// The command `chord` (pressed twice when `double`) runs with `active` focus. + pub fn lookup(&self, chord: &Chord, double: bool, active: &Active) -> Lookup { + let want = Trigger { chord: chord.effective(self.platform), double }; + let held = active.typing && !self.typing.fires(&want.chord); + let Some(holders) = self.by_trigger.get(&want) else { return Lookup::None }; + // Each command's nearest rank; `holders` is in catalogue order. + let mut ranks: Vec<(usize, u8)> = Vec::new(); + for &(i, k) in holders { + let Some(r) = self.at(i, k).and_then(|(_, s)| self.scopes.rank(s, active)) else { continue }; + // The typing rule holds back everything except bindings of an active context (rank 0). + if held && r != 0 { + continue; + } + match ranks.last_mut() { + Some((j, best)) if *j == i => *best = (*best).min(r), + _ => ranks.push((i, r)), + } + } + let Some(best) = ranks.iter().map(|(_, r)| *r).min() else { return Lookup::None }; + let winners: Vec = ranks.iter().filter(|(_, r)| *r == best).map(|(i, _)| *i).collect(); + match winners.as_slice() { + [] => Lookup::None, + [i] => Lookup::Run(self.catalogue[*i].command.clone()), + [first, rest @ ..] => { + if rest.iter().all(|j| self.same_group(*first, *j)) { + Lookup::Cycle(winners.iter().map(|i| self.catalogue[*i].command.clone()).collect()) + } else { + Lookup::Run(self.catalogue[*first].command.clone()) + } + } + } + } + + /// Adds a binding to a command. + pub fn assign(&mut self, command: &CommandRef, binding: Binding, policy: Policy) -> Result { + let i = self.find(command).ok_or(AssignError::UnknownCommand)?; + let new = self.bound(i, &binding); + if self.current[i].iter().any(|b| self.same(b, &new)) { + return Ok(Assigned::default()); + } + let mut list = self.current[i].clone(); + list.push(new.clone()); + self.apply(i, list, &[new], policy) + } + + /// Replaces all bindings of a command. + pub fn set_bindings(&mut self, command: &CommandRef, bindings: Vec, policy: Policy) -> Result { + let i = self.find(command).ok_or(AssignError::UnknownCommand)?; + if bindings.len() > MAX_BINDINGS { + return Err(AssignError::TooMany); + } + let home = self.catalogue[i].scope.clone(); + let list = self.normalize(bindings, &home); + let new: Vec = list.iter().filter(|b| !self.current[i].iter().any(|c| self.same(c, b))).cloned().collect(); + self.apply(i, list, &new, policy) + } + + /// Removes one binding (matched by effective trigger and scope). `false` when the command does + /// not have it, or when the change needs a new [`Overrides`] entry and the overrides are full + /// ([`AssignError::Full`]); nothing changes then. + pub fn remove(&mut self, command: &CommandRef, binding: &Binding) -> bool { + let Some(i) = self.find(command) else { return false }; + let gone = self.bound(i, binding); + let before = self.current[i].len(); + let list: Vec = self.current[i].iter().filter(|b| !self.same(b, &gone)).cloned().collect(); + list.len() != before && self.commit(vec![(i, list)]).is_ok() + } + + /// Leaves a command without shortcuts, in every scope. `false` for an unknown command, or when + /// the overrides are full as for [`Keymap::remove`]. + pub fn clear(&mut self, command: &CommandRef) -> bool { + let Some(i) = self.find(command) else { return false }; + self.commit(vec![(i, Vec::new())]).is_ok() + } + + /// Gives a command its default bindings back. + pub fn reset(&mut self, command: &CommandRef) -> bool { + let Some(i) = self.find(command) else { return false }; + // The whole entry goes, texts this build cannot use included. + if let Some(old) = self.stored[i].take() { + self.overrides.remove(&old); + } + self.set_current(i, self.defaults[i].clone()); + true + } + + /// Every command gets its defaults; unknown entries go too. + pub fn reset_all(&mut self) { + self.overrides.clear(); + self.reload(); + } + + /// Pairs of commands on one chord, at most [`MAX_CONFLICTS`], in chord order, then in + /// catalogue order. Tools of one group and bindings of panels that are never active together + /// are left out; with panel fallthrough two unrelated panels on one chord tie in a third panel, + /// which is reported as a [`ConflictKind::Shadow`]. + /// + /// When the cap cuts a chord's pairs, the pairs kept are the first found comparing the + /// chord's holders grouped by scope and tool group, group by group in the order each group + /// first appears in the catalogue; the kept pairs are still returned in chord order, then + /// catalogue order. + pub fn conflicts(&self) -> Vec { + let mut chords: Vec<(&Trigger, &BTreeSet<(usize, usize)>)> = self.by_trigger.iter().filter(|(_, h)| h.len() > 1).collect(); + chords.sort_by_key(|(t, _)| **t); + let mut out = Vec::new(); + for (chord, holders) in chords { + if !self.chord_conflicts(*chord, holders, &mut out) { + break; + } + } + out + } + + /// What is wrong with the stored overrides: load notes, unknown commands, texts that do not + /// parse, reserved chords, unknown scopes, duplicate entries. + pub fn problems(&self) -> Vec { + let mut out = self.overrides.load_notes().to_vec(); + for (key, texts) in self.overrides.iter() { + let Some(i) = self.resolve_key(key) else { + out.push(Problem::UnknownCommand { key: key.to_string() }); + continue; + }; + if self.stored[i].as_deref() != Some(key) { + out.push(Problem::DuplicateKey { key: key.to_string() }); + continue; + } + let home = &self.catalogue[i].scope; + for text in texts { + let (key, text) = (key.to_string(), text.clone()); + match Binding::parse(&text) { + Err(error) => out.push(Problem::BadBinding { key, text, error }), + Ok(b) if self.is_reserved(&b.trigger.chord) => out.push(Problem::Reserved { key, text }), + Ok(b) if !self.usable_scope(b.scope_or(home), home) => out.push(Problem::UnknownScope { key, text }), + Ok(_) => {} + } + } + } + out + } + + /// Bindings of other commands that only one of them and `bindings` on `command` could run, + /// leaving out tools of the same group and twins (as [`Policy::Steal`] does). + pub(crate) fn clashing(&self, command: &CommandRef, bindings: &[Binding]) -> Vec { + let Some(i) = self.find(command) else { return Vec::new() }; + let new: Vec = bindings.iter().map(|b| self.bound(i, b)).collect(); + self.clashes(i, &new).into_iter().map(|(j, b)| Holder { command: self.catalogue[j].command.clone(), binding: self.public(j, &b) }).collect() + } + + /// Whether binding `x` of command `a` and binding `y` of another command `b` clash, by the + /// rules of [`Keymap::clashing`]. + pub(crate) fn pair_clashes(&self, a: &CommandRef, x: &Binding, b: &CommandRef, y: &Binding) -> bool { + let (Some(i), Some(j)) = (self.find(a), self.find(b)) else { return false }; + if i == j || self.same_group(i, j) { + return false; + } + let (bx, by) = (self.bound(i, x), self.bound(j, y)); + let t = bx.0.effective(self.platform); + t == by.0.effective(self.platform) && !self.twins(i, j, t) && self.scopes.relation(&bx.1, &by.1) == Some(true) + } + + fn find(&self, command: &CommandRef) -> Option { + self.index.get(&command.key()).copied() + } + + fn resolve_key(&self, key: &str) -> Option { + self.index.get(key).or_else(|| CommandRef::parse_key(key).and_then(|c| self.index.get(&c.key()))).copied() + } + + fn at(&self, i: usize, k: usize) -> Option<&Bound> { + self.current.get(i).and_then(|l| l.get(k)) + } + + fn bound(&self, i: usize, binding: &Binding) -> Bound { + (binding.trigger, binding.scope_or(&self.catalogue[i].scope).clone()) + } + + fn public(&self, i: usize, (trigger, scope): &Bound) -> Binding { + let scope = (*scope != self.catalogue[i].scope).then(|| scope.clone()); + Binding { trigger: *trigger, scope } + } + + fn same(&self, a: &Bound, b: &Bound) -> bool { + a.1 == b.1 && a.0.effective(self.platform) == b.0.effective(self.platform) + } + + /// Whether a stored binding of a command with home scope `home` may use `scope`. + fn usable_scope(&self, scope: &Scope, home: &Scope) -> bool { + scope == home || self.knows_scope(scope) + } + + /// Resolves scopes, drops repeats and caps the count. + fn normalize(&self, bindings: impl IntoIterator, home: &Scope) -> Vec { + let mut out: Vec = Vec::new(); + for b in bindings { + let bound = (b.trigger, b.scope_or(home).clone()); + if out.len() < MAX_BINDINGS && !out.contains(&bound) { + out.push(bound); + } + } + out + } + + fn same_group(&self, i: usize, j: usize) -> bool { + match (&self.catalogue[i].kind, &self.catalogue[j].kind) { + (Kind::Tool { group: a }, Kind::Tool { group: b }) => a == b, + _ => false, + } + } + + /// Both commands have `trigger` among their defaults: they share it by design. + fn twins(&self, i: usize, j: usize, trigger: Trigger) -> bool { + let has = |k: usize| self.defaults[k].iter().any(|(t, _)| t.effective(self.platform) == trigger); + has(i) && has(j) + } + + /// Bindings of other commands that only one of `new` and them could run. + fn clashes(&self, i: usize, new: &[Bound]) -> Vec<(usize, Bound)> { + let mut out = Vec::new(); + let mut seen: HashSet<(usize, usize)> = HashSet::new(); + for (t, s) in new { + let t = t.effective(self.platform); + let Some(holders) = self.by_trigger.get(&t) else { continue }; + for &(j, k) in holders { + if j == i || self.same_group(i, j) || self.twins(i, j, t) { + continue; + } + let Some(b) = self.at(j, k) else { continue }; + if self.scopes.relation(s, &b.1) == Some(true) && seen.insert((j, k)) { + out.push((j, b.clone())); + } + } + } + out + } + + /// How two scopes on one chord relate for [`Keymap::conflicts`]: [`Scopes::relation`], and with + /// panel fallthrough two unrelated panels shadow (they tie in any third panel). + fn conflict_relation(&self, a: &Scope, b: &Scope) -> Option { + self.scopes.relation(a, b).or_else(|| { + let panels = self.scopes.kind(a) == ScopeKind::Panel && self.scopes.kind(b) == ScopeKind::Panel; + (panels && self.scopes.panel_fallthrough()).then_some(false) + }) + } + + /// Adds the conflicts on one chord to `out`; `false` once `out` is full. + /// + /// The holders are grouped by scope and tool group, and only groups that relate are compared, + /// so pairs that are left out (unrelated panels, tools of one group) cost nothing per pair. + fn chord_conflicts(&self, chord: Trigger, holders: &BTreeSet<(usize, usize)>, out: &mut Vec) -> bool { + let mut groups: Vec = Vec::new(); + let mut group_of: HashMap<(&Scope, Option<&Option>), usize> = HashMap::new(); + for (pos, &(i, k)) in holders.iter().enumerate() { + let Some(b) = self.at(i, k) else { continue }; + let tools = match &self.catalogue[i].kind { + Kind::Tool { group } => Some(group), + _ => None, + }; + let g = *group_of.entry((&b.1, tools)).or_insert_with(|| { + groups.push(Group { scope: &b.1, tools, items: Vec::new() }); + groups.len() - 1 + }); + if let Some(group) = groups.get_mut(g) { + group.items.push((pos, i, b)); + } + } + let room = MAX_CONFLICTS.saturating_sub(out.len()); + let mut found: Vec = Vec::new(); + 'groups: for (n, g) in groups.iter().enumerate() { + for (m, h) in groups.iter().enumerate().skip(n) { + if g.tools.is_some() && g.tools == h.tools { + continue; + } + let Some(clash) = self.conflict_relation(g.scope, h.scope) else { continue }; + let same = m == n; + for (x, &(pa, i, a)) in g.items.iter().enumerate() { + let rest = if same { g.items.get(x + 1..).unwrap_or_default() } else { &h.items }; + for &(pb, j, b) in rest { + if i == j { + continue; + } + if found.len() >= room { + break 'groups; + } + let pair = if pa < pb { (pa, pb, clash, (i, a), (j, b)) } else { (pb, pa, clash, (j, b), (i, a)) }; + found.push(pair); + } + } + } + } + found.sort_by_key(|(pa, pb, ..)| (*pa, *pb)); + for (_, _, clash, (i, a), (j, b)) in found { + out.push(Conflict { + chord, + a: (self.catalogue[i].command.clone(), self.public(i, a)), + b: (self.catalogue[j].command.clone(), self.public(j, b)), + kind: if clash { ConflictKind::Clash } else { ConflictKind::Shadow }, + in_defaults: self.defaults[i].contains(a) && self.defaults[j].contains(b), + }); + } + out.len() < MAX_CONFLICTS + } + + fn apply(&mut self, i: usize, list: Vec, new: &[Bound], policy: Policy) -> Result { + if list.len() > MAX_BINDINGS { + return Err(AssignError::TooMany); + } + if let Some((t, _)) = new.iter().find(|(t, _)| self.is_reserved(&t.chord)) { + return Err(AssignError::Reserved(*t)); + } + let home = &self.catalogue[i].scope; + if let Some((_, s)) = new.iter().find(|(_, s)| !self.usable_scope(s, home)) { + return Err(AssignError::UnknownScope(s.clone())); + } + let clashes = self.clashes(i, new); + let holders: Vec = + clashes.iter().map(|(j, b)| Holder { command: self.catalogue[*j].command.clone(), binding: self.public(*j, b) }).collect(); + let mut done = Assigned::default(); + let mut writes: Vec<(usize, Vec)> = Vec::new(); + match policy { + Policy::Refuse if !holders.is_empty() => return Err(AssignError::Taken(holders)), + Policy::Refuse => {} + Policy::Keep => done.clashes = holders, + Policy::Steal => { + let mut victims: Vec = Vec::new(); + let mut gone: HashMap> = HashMap::new(); + for (j, b) in &clashes { + let list = gone.entry(*j).or_default(); + if list.is_empty() { + victims.push(*j); + } + list.push(b); + } + for j in victims { + let gone = gone.get(&j).map(Vec::as_slice).unwrap_or_default(); + let rest: Vec = self.current[j].iter().filter(|o| !gone.contains(o)).cloned().collect(); + writes.push((j, rest)); + } + done.taken_from = holders; + } + } + writes.push((i, list)); + self.commit(writes)?; + Ok(done) + } + + /// Stores several commands' bindings, or none of them when the overrides lack room for the + /// new entries. + fn commit(&mut self, writes: Vec<(usize, Vec)>) -> Result<(), AssignError> { + let needed = writes.iter().filter(|(i, list)| self.stored[*i].is_none() && !self.is_default(*i, list)).count(); + if self.overrides.len() + needed > MAX_COMMANDS { + return Err(AssignError::Full); + } + for (i, list) in writes { + self.store(i, list); + } + Ok(()) + } + + /// Writes a command's bindings to the overrides, dropping the entry when they equal the + /// defaults. Texts of the old entry this build cannot use stay in it, after the bindings and up + /// to [`MAX_BINDINGS`], unless the command is left without bindings: an entry of only such + /// texts loads as the defaults. Callers check for room first ([`Keymap::commit`]); texts always + /// fit, since a scope name, `": "` and the longest double press stay under + /// [`MAX_BINDING_TEXT`]. + fn store(&mut self, i: usize, list: Vec) { + let mut kept = if list.is_empty() { Vec::new() } else { self.unusable_texts(i) }; + kept.truncate(MAX_BINDINGS.saturating_sub(list.len())); + if let Some(old) = self.stored[i].take() { + self.overrides.remove(&old); + } + if !kept.is_empty() || !self.is_default(i, &list) { + let home = &self.catalogue[i].scope; + let mut texts: Vec = list.iter().map(|b| self.public(i, b).text(home)).collect(); + texts.extend(kept); + if self.overrides.insert(self.keys[i].clone(), texts) { + self.stored[i] = Some(self.keys[i].clone()); + } + } + self.set_current(i, list); + } + + /// Whether `list` is the command's defaults, comparing effective triggers. + fn is_default(&self, i: usize, list: &[Bound]) -> bool { + let defaults = &self.defaults[i]; + list.len() == defaults.len() && list.iter().zip(defaults).all(|(a, b)| self.same(a, b)) + } + + /// Whether a stored binding of a command with home scope `home` works here. + fn usable(&self, binding: &Binding, home: &Scope) -> bool { + !self.is_reserved(&binding.trigger.chord) && self.usable_scope(binding.scope_or(home), home) + } + + /// The texts of a command's overrides entry this build cannot use: a key name from a newer + /// version, a scope this app lacks, a chord this platform reserves. + fn unusable_texts(&self, i: usize) -> Vec { + let Some(texts) = self.stored[i].as_deref().and_then(|key| self.overrides.get(key)) else { return Vec::new() }; + let home = &self.catalogue[i].scope; + texts.iter().filter(|t| !Binding::parse(t).is_ok_and(|b| self.usable(&b, home))).cloned().collect() + } + + fn set_current(&mut self, i: usize, list: Vec) { + self.unindex(i); + if let Some(c) = self.current.get_mut(i) { + *c = list; + } + self.index_command(i); + } + + fn index_command(&mut self, i: usize) { + let Some(list) = self.current.get(i) else { return }; + for (k, (t, _)) in list.iter().enumerate() { + self.by_trigger.entry(t.effective(self.platform)).or_default().insert((i, k)); + } + } + + fn unindex(&mut self, i: usize) { + let Some(list) = self.current.get(i) else { return }; + for (k, (t, _)) in list.iter().enumerate() { + let t = t.effective(self.platform); + if let Some(holders) = self.by_trigger.get_mut(&t) { + holders.remove(&(i, k)); + if holders.is_empty() { + self.by_trigger.remove(&t); + } + } + } + } + + fn rebuild_index(&mut self) { + self.by_trigger.clear(); + for i in 0..self.current.len() { + self.index_command(i); + } + } + + /// Recomputes every command's bindings from the defaults and the overrides. + fn reload(&mut self) { + self.stored.iter_mut().for_each(|s| *s = None); + self.current.clone_from(&self.defaults); + // Exact keys first, so a canonical entry wins over a hand-written variant of it. + let mut entries: Vec<(&str, &[String])> = self.overrides.iter().collect(); + entries.sort_by_key(|(k, _)| !self.index.contains_key(*k)); + let mut found: Vec<(usize, String, Vec)> = Vec::new(); + let mut taken: HashSet = HashSet::new(); + for (key, texts) in entries { + let Some(i) = self.resolve_key(key) else { continue }; + if !taken.insert(i) { + continue; + } + let home = &self.catalogue[i].scope; + let usable = texts.iter().filter_map(|t| Binding::parse(t).ok()).filter(|b| self.usable(b, home)); + let list = self.normalize(usable, home); + // An entry none of whose texts is usable here (a key name from a newer version, a scope + // this app lacks, a chord this platform reserves) keeps the defaults; `[]` means no + // shortcut. + let list = if list.is_empty() && !texts.is_empty() { self.defaults[i].clone() } else { list }; + found.push((i, key.to_string(), list)); + } + for (i, key, list) in found { + self.stored[i] = Some(key); + self.current[i] = list; + } + self.rebuild_index(); + } +} diff --git a/crates/keymap/src/keymap/overrides.rs b/crates/keymap/src/keymap/overrides.rs new file mode 100644 index 000000000..914b13e68 --- /dev/null +++ b/crates/keymap/src/keymap/overrides.rs @@ -0,0 +1,337 @@ +use std::collections::BTreeMap; +use std::fmt; + +use serde::de::{self, IgnoredAny, MapAccess, SeqAccess, Visitor}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde_json::Value; + +use super::{DropReason, MAX_BINDING_TEXT, MAX_BINDINGS, MAX_COMMANDS, Problem}; +use crate::command::MAX_KEY; + +// Load notes are kept for `Keymap::problems`; a hostile file must not grow them without bound. +const MAX_NOTES: usize = 64; + +/// The user's changes to the default bindings: binding key → the full list of binding texts +/// that replaces the command's defaults (`[]` = no shortcut). +/// +/// Stored as an array of `{ command, keys }` items in key order, e.g. `[[shortcuts]]` blocks in +/// craft-settings; the map form `{ "": [texts] }` loads too. Loading never fails: +/// entries for unknown commands and texts that do not parse are kept verbatim; values that are not +/// text, overlong keys and texts, repeated keys (the first entry stays) and entries past the caps +/// are dropped, and a value that is neither a list nor a map loads as no overrides. All of these +/// are reported by [`Keymap::problems`](super::Keymap::problems). +#[derive(Clone, Debug, Default)] +pub struct Overrides { + map: BTreeMap>, + notes: Vec, +} + +impl PartialEq for Overrides { + fn eq(&self, other: &Overrides) -> bool { + self.map == other.map + } +} + +impl Eq for Overrides {} + +impl Overrides { + pub const fn new() -> Overrides { + Overrides { map: BTreeMap::new(), notes: Vec::new() } + } + + pub fn get(&self, key: &str) -> Option<&[String]> { + self.map.get(key).map(Vec::as_slice) + } + + pub fn iter(&self) -> impl Iterator { + self.map.iter().map(|(k, v)| (k.as_str(), v.as_slice())) + } + + pub fn len(&self) -> usize { + self.map.len() + } + + pub fn is_empty(&self) -> bool { + self.map.is_empty() + } + + /// Sets an entry verbatim. `false` (and nothing stored) for a key over [`MAX_KEY`] bytes, a + /// list over [`MAX_BINDINGS`], a text over [`MAX_BINDING_TEXT`] bytes, or a new key past + /// [`MAX_COMMANDS`] entries. + pub fn insert(&mut self, key: impl Into, texts: Vec) -> bool { + let key = key.into(); + let fits = key.len() <= MAX_KEY + && texts.len() <= MAX_BINDINGS + && texts.iter().all(|t| t.len() <= MAX_BINDING_TEXT) + && (self.map.contains_key(&key) || self.map.len() < MAX_COMMANDS); + if fits { + self.map.insert(key, texts); + } + fits + } + + pub fn remove(&mut self, key: &str) -> Option> { + self.map.remove(key) + } + + /// Removes every entry: all commands get their defaults. + pub fn clear(&mut self) { + self.map.clear(); + self.notes.clear(); + } + + /// What loading dropped. + pub fn load_notes(&self) -> &[Problem] { + &self.notes + } + + fn note(&mut self, problem: Problem) { + if self.notes.len() < MAX_NOTES { + self.notes.push(problem); + } + } +} + +// Written as an array of `{ command, keys }` items, not a map: craft-settings merges tables key +// by key and keeps keys a value no longer has, but replaces arrays whole, so a reset entry leaves +// the file only in this form. +impl Serialize for Overrides { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_seq(self.map.iter().map(|(command, keys)| Item { command, keys })) + } +} + +#[derive(Serialize)] +struct Item<'a> { + command: &'a str, + keys: &'a [String], +} + +impl<'de> Deserialize<'de> for Overrides { + fn deserialize>(deserializer: D) -> Result { + deserializer.deserialize_any(OverridesVisitor) + } +} + +struct OverridesVisitor; + +/// Collects entries with the caps applied. +#[derive(Default)] +struct Builder { + out: Overrides, + ignored: usize, +} + +impl Builder { + /// Whether an entry for `key` can be stored; notes why not. + fn admits(&mut self, key: &str) -> bool { + if key.len() > MAX_KEY { + self.out.note(Problem::Dropped { key: clip(key, MAX_KEY), reason: DropReason::KeyTooLong }); + return false; + } + if self.out.map.len() >= MAX_COMMANDS && !self.out.map.contains_key(key) { + self.ignored += 1; + return false; + } + true + } + + /// Stores an entry; a second entry for the same key is ignored and noted. + fn add(&mut self, key: String, value: Lenient) { + let out = &mut self.out; + if out.map.contains_key(&key) { + out.note(Problem::DuplicateKey { key }); + return; + } + let texts = match value { + Lenient::List { texts, other, extra } => { + if other { + out.note(Problem::Dropped { key: key.clone(), reason: DropReason::NotText }); + } + if extra > 0 { + out.note(Problem::Dropped { key: key.clone(), reason: DropReason::TooManyBindings }); + } + texts + } + Lenient::Text(t) => vec![t], + Lenient::Other => { + out.note(Problem::Dropped { key, reason: DropReason::NotAList }); + return; + } + }; + let (texts, long): (Vec, Vec) = texts.into_iter().partition(|t| t.len() <= MAX_BINDING_TEXT); + if !long.is_empty() { + out.note(Problem::Dropped { key: key.clone(), reason: DropReason::TextTooLong }); + } + out.map.insert(key, texts); + } + + fn finish(mut self) -> Overrides { + if self.ignored > 0 { + let ignored = self.ignored; + self.out.note(Problem::TooManyCommands { ignored }); + } + self.out + } +} + +/// No overrides, with a note that the value was not a list or map. +fn not_a_list() -> Overrides { + let mut out = Overrides::new(); + out.note(Problem::Dropped { key: String::new(), reason: DropReason::NotAList }); + out +} + +macro_rules! not_a_list { + ($($name:ident: $t:ty),*) => { + $(fn $name(self, _: $t) -> Result { + Ok(not_a_list()) + })* + }; +} + +impl<'de> Visitor<'de> for OverridesVisitor { + type Value = Overrides; + + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a list of `{ command, keys }` items or a map of binding keys to binding texts") + } + + not_a_list!(visit_bool: bool, visit_i64: i64, visit_u64: u64, visit_i128: i128, visit_u128: u128, visit_f64: f64, visit_str: &str, visit_bytes: &[u8], visit_char: char); + + fn visit_unit(self) -> Result { + Ok(not_a_list()) + } + + fn visit_none(self) -> Result { + Ok(not_a_list()) + } + + fn visit_some>(self, deserializer: D) -> Result { + deserializer.deserialize_any(OverridesVisitor) + } + + /// The array form, `[{ command = "…", keys = […] }, …]`. + fn visit_seq>(self, mut access: A) -> Result { + let mut b = Builder::default(); + while let Some(item) = access.next_element::()? { + let command = item.get("command").and_then(Value::as_str); + let keys = item.get("keys").map(Lenient::deserialize).and_then(Result::ok); + match (command, keys) { + (Some(command), Some(keys)) => { + if b.admits(command) { + b.add(command.to_string(), keys); + } + } + (command, _) => { + let key = clip(command.unwrap_or_default(), MAX_KEY); + b.out.note(Problem::Dropped { key, reason: DropReason::NotAList }); + } + } + } + Ok(b.finish()) + } + + /// The map form, binding key → texts (hand edits, older files). An empty text means no + /// shortcut, as in the apps that store one text per command and `""` for a removed shortcut. + fn visit_map>(self, mut access: A) -> Result { + let mut b = Builder::default(); + while let Some(key) = access.next_key::()? { + if b.admits(&key) { + let value = match access.next_value::()? { + Lenient::Text(t) if t.trim().is_empty() => Lenient::List { texts: Vec::new(), other: false, extra: 0 }, + Lenient::List { mut texts, other, extra } => { + texts.retain(|t| !t.trim().is_empty()); + Lenient::List { texts, other, extra } + } + value => value, + }; + b.add(key, value); + } else { + access.next_value::()?; + } + } + Ok(b.finish()) + } +} + +/// Cuts `s` to at most `max` bytes on a char boundary. +pub(crate) fn clip(s: &str, max: usize) -> String { + let mut end = s.len().min(max); + while !s.is_char_boundary(end) { + end -= 1; + } + s[..end].to_string() +} + +/// An entry's value as found: a list (texts kept up to the cap), one text, or anything else. +enum Lenient { + List { texts: Vec, other: bool, extra: usize }, + Text(String), + Other, +} + +impl<'de> Deserialize<'de> for Lenient { + fn deserialize>(deserializer: D) -> Result { + deserializer.deserialize_any(LenientVisitor) + } +} + +struct LenientVisitor; + +macro_rules! other { + ($($name:ident: $t:ty),*) => { + $(fn $name(self, _: $t) -> Result { + Ok(Lenient::Other) + })* + }; +} + +impl<'de> Visitor<'de> for LenientVisitor { + type Value = Lenient; + + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a list of binding texts") + } + + fn visit_str(self, v: &str) -> Result { + Ok(Lenient::Text(v.to_string())) + } + + fn visit_string(self, v: String) -> Result { + Ok(Lenient::Text(v)) + } + + other!(visit_bool: bool, visit_i64: i64, visit_u64: u64, visit_i128: i128, visit_u128: u128, visit_f64: f64, visit_bytes: &[u8], visit_char: char); + + fn visit_unit(self) -> Result { + Ok(Lenient::Other) + } + + fn visit_none(self) -> Result { + Ok(Lenient::Other) + } + + fn visit_some>(self, deserializer: D) -> Result { + deserializer.deserialize_any(LenientVisitor) + } + + fn visit_map>(self, mut access: A) -> Result { + while access.next_entry::()?.is_some() {} + Ok(Lenient::Other) + } + + fn visit_seq>(self, mut access: A) -> Result { + let mut texts = Vec::new(); + let mut other = false; + let mut extra = 0usize; + while let Some(item) = access.next_element::()? { + match item { + Lenient::Text(t) if texts.len() < MAX_BINDINGS => texts.push(t), + Lenient::Text(_) => extra += 1, + _ => other = true, + } + } + Ok(Lenient::List { texts, other, extra }) + } +} diff --git a/crates/keymap/src/lib.rs b/crates/keymap/src/lib.rs new file mode 100644 index 000000000..bebf33f7e --- /dev/null +++ b/crates/keymap/src/lib.rs @@ -0,0 +1,146 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +//! Keyboard bindings for the Craft suite. +//! +//! [`chord`] holds the key and modifier types, the canonical text form that settings and control +//! protocols store, display text per platform, and a reader for other applications' key text. +//! [`command`] names what a binding runs, [`scope`] where it works, and [`keymap`] holds an app's +//! catalogue with default bindings, the user's [`Overrides`], dispatch ([`Keymap::lookup`]), +//! editing and conflicts. [`reserved`] lists the chords each operating system takes. [`import`] +//! brings in other applications' shortcut sets. With the `egui` feature, the `egui` module +//! converts to and from egui keys, matches key presses against bindings and dispatches a frame's +//! key events. +//! +//! ``` +//! use craft_keymap::{Chord, Platform}; +//! +//! let chord = Chord::parse("⇧⌘Z").unwrap(); +//! assert_eq!(chord.to_string(), "Cmd+Shift+Z"); +//! assert_eq!(chord.display(Platform::Mac), "⇧⌘Z"); +//! assert_eq!(chord.display(Platform::Windows), "Ctrl+Shift+Z"); +//! ``` +//! +//! # A catalogue and dispatch +//! +//! The app lists every command it can bind. A command with parameters has the key +//! `window.panel {"panel":"layers"}` in settings and reports. Tools of one group share a key and +//! cycle. A binding can name a scope other than the command's home scope. +//! +//! ``` +//! use craft_keymap::{Active, Bindable, Binding, Chord, CommandRef, Keymap, Kind, Lookup, Platform, Scope, Scopes}; +//! use serde_json::json; +//! +//! let key = |text: &str| Binding::parse(text).unwrap(); +//! let layers = CommandRef::with_params("window.panel", json!({"panel": "layers"})); +//! let select = Kind::Tool { group: Some("select".into()) }; +//! let catalogue = vec![ +//! Bindable::new("file.save", "Save", Scope::app()).with_path(vec!["File".into(), "Save".into()]).with_default(key("Cmd+S")), +//! Bindable::new(layers.clone(), "Layers", Scope::app()).with_path(vec!["Window".into(), "Layers".into()]).with_default(key("F7")), +//! Bindable::new("tool.marquee", "Marquee Tool", Scope::app()).with_kind(select.clone()).with_default(key("M")), +//! Bindable::new("tool.ellipse", "Elliptical Marquee Tool", Scope::app()).with_kind(select).with_default(key("M")), +//! // Home scope: the Timeline panel, where it wins over the app's L. +//! Bindable::new("timeline.loop", "Loop", Scope::new("Timeline").unwrap()).with_default(key("L")), +//! Bindable::new("layer.lock", "Lock Layer", Scope::app()).with_default(key("L")), +//! // An app command whose binding works only in the Text context. +//! Bindable::new("type.bold", "Bold", Scope::app()).with_default(key("Text: Cmd+B")), +//! ]; +//! let keymap = Keymap::new(catalogue, Scopes::new().with_panel("Timeline").with_context("Text"), Platform::Mac); +//! assert_eq!(layers.key(), r#"window.panel {"panel":"layers"}"#); +//! +//! // Dispatch: the chord pressed, whether it is a double press, and what has the keyboard. +//! let press = |text: &str, active: &Active| keymap.lookup(&Chord::parse(text).unwrap(), false, active); +//! assert_eq!(press("F7", &Active::NONE), Lookup::Run(layers)); +//! assert_eq!(press("L", &Active::panel("Timeline")), Lookup::Run("timeline.loop".into())); +//! assert_eq!(press("L", &Active::NONE), Lookup::Run("layer.lock".into())); +//! assert_eq!(press("M", &Active::NONE), Lookup::Cycle(vec!["tool.marquee".into(), "tool.ellipse".into()])); +//! let editing = Active { contexts: &["Text"], typing: true, ..Active::NONE }; +//! assert_eq!(press("Cmd+B", &editing), Lookup::Run("type.bold".into())); +//! assert_eq!(press("M", &editing), Lookup::None, "plain keys go to the text field"); +//! ``` +//! +//! With the `egui` feature, `egui::Dispatcher` does this for a frame's key events. +//! +//! # Storing overrides +//! +//! [`Overrides`] is a field of the app's craft-settings type. It is stored as an array of +//! `{ command, keys }` tables, not as a table keyed by command: craft-settings merges tables key +//! by key with what the file holds, but replaces an array whole, so a reset command (an entry +//! removed) stays removed after saving. +//! +//! ```no_run +//! use craft_keymap::{Binding, Keymap, Overrides, Platform, Policy, Scopes}; +//! use craft_settings::{Location, Settings, SettingsStore}; +//! use serde::{Deserialize, Serialize}; +//! +//! #[derive(Serialize, Deserialize, Default, Clone, PartialEq)] +//! #[serde(default)] +//! struct Prefs { +//! shortcuts: Overrides, +//! } +//! +//! impl Settings for Prefs { +//! const APP_ID: &'static str = "acmecraft"; +//! const SCHEMA_VERSION: u32 = 1; +//! } +//! +//! # let catalogue = Vec::new(); +//! let (mut store, _report) = SettingsStore::::open(Location::Auto); +//! let mut keymap = Keymap::new(catalogue, Scopes::new(), Platform::current()).with_overrides(store.get().shortcuts.clone()); +//! // Entries for unknown commands and texts that do not parse are kept and listed here. +//! let _problems = keymap.problems(); +//! +//! // After each change in the shortcut editor: +//! keymap.assign(&"file.save".into(), Binding::parse("Cmd+Alt+S").unwrap(), Policy::Steal).ok(); +//! store.update(|p| p.shortcuts = keymap.overrides().clone()); +//! ``` +//! +//! # Importing a shortcut set +//! +//! The app's reader builds a [`ForeignSet`]; [`plan`] matches it without changing anything, so a +//! review UI can show [`ImportPlan::commands`] and the report first. +//! +//! ``` +//! use craft_keymap::{Bindable, Binding, ContextRule, Flavor, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, Keymap, Platform}; +//! use craft_keymap::{Scope, Scopes, plan}; +//! +//! let save = Bindable::new("file.save", "Save", Scope::app()) +//! .with_path(vec!["File".into(), "Save".into()]) +//! .with_default(Binding::parse("Cmd+S").unwrap()); +//! let mut keymap = Keymap::new(vec![save], Scopes::new(), Platform::Windows); +//! +//! let read = |text: &str| ForeignKey::read(Some("Default"), text, Flavor::Windows); +//! let set = ForeignSet { +//! name: Some("My Set".into()), +//! entries: vec![ +//! ForeignEntry::new(Some("File"), ["Save"]).with_key(read("Ctrl+Alt+S")).at_line(12), +//! ForeignEntry::new(Some("File"), ["Frobnicate"]).with_key(read("Ctrl+F")).at_line(13), +//! ], +//! }; +//! let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], ..ImportOptions::default() }; +//! let planned = plan(&set, &keymap, &options); +//! assert_eq!(planned.commands.len(), 1); +//! +//! let report = planned.apply(&mut keymap); +//! assert_eq!(report.changed[0].to, ["Cmd+Alt+S"]); +//! assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File > Frobnicate", Some(13))); +//! assert_eq!(keymap.bindings(&"file.save".into()), [Binding::parse("Cmd+Alt+S").unwrap()]); +//! ``` + +pub mod chord; +pub mod command; +#[cfg(feature = "egui")] +pub mod egui; +pub mod import; +pub mod keymap; +pub mod reserved; +pub mod scope; + +pub use chord::foreign::Flavor; +pub use chord::{Chord, Key, MAX_CHORD_TEXT, Mods, ParseError, Platform, Trigger}; +pub use command::{CommandRef, MAX_KEY}; +pub use import::{ContextRule, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportPlan, ImportReport, NoneDefined, Start, plan}; +pub use keymap::{ + AssignError, Assigned, Bindable, Binding, BindingError, Conflict, ConflictKind, DropReason, Holder, Keymap, Kind, Lookup, MAX_BINDING_TEXT, + MAX_BINDINGS, MAX_COMMANDS, MAX_CONFLICTS, Overrides, Policy, Problem, TypingRule, +}; +pub use scope::{Active, MAX_SCOPE_NAME, Scope, ScopeKind, Scopes}; diff --git a/crates/keymap/src/reserved.rs b/crates/keymap/src/reserved.rs new file mode 100644 index 000000000..7dbf847bf --- /dev/null +++ b/crates/keymap/src/reserved.rs @@ -0,0 +1,36 @@ +//! Chords the operating system takes before the app sees them. + +use crate::chord::{Chord, Platform}; + +// from photocraft crates/engine/src/prefs.rs `reserved_shortcut` +const MAC: &[&str] = &["Cmd+Tab", "Cmd+Shift+Tab", "Cmd+Alt+Escape", "Cmd+`"]; +const WINDOWS: &[&str] = &["Alt+Tab", "Alt+Shift+Tab", "Alt+F4", "Cmd+Alt+Delete", "Cmd+Escape", "Cmd+Shift+Escape"]; +// Linux and the BSDs: window switching and closing, and the virtual consoles. +const LINUX: &[&str] = &[ + "Alt+Tab", + "Alt+Shift+Tab", + "Alt+F4", + "Cmd+Alt+Delete", + "Cmd+Alt+F1", + "Cmd+Alt+F2", + "Cmd+Alt+F3", + "Cmd+Alt+F4", + "Cmd+Alt+F5", + "Cmd+Alt+F6", + "Cmd+Alt+F7", + "Cmd+Alt+F8", + "Cmd+Alt+F9", + "Cmd+Alt+F10", + "Cmd+Alt+F11", + "Cmd+Alt+F12", +]; + +/// The window switching, closing and session chords of `platform`. +pub fn system(platform: Platform) -> Vec { + let list = match platform { + Platform::Mac => MAC, + Platform::Windows => WINDOWS, + Platform::Linux => LINUX, + }; + list.iter().filter_map(|t| Chord::parse(t).ok()).collect() +} diff --git a/crates/keymap/src/scope.rs b/crates/keymap/src/scope.rs new file mode 100644 index 000000000..287413c9b --- /dev/null +++ b/crates/keymap/src/scope.rs @@ -0,0 +1,205 @@ +//! Where a binding works: the whole application, one panel, or a context such as text editing. + +use std::fmt; + +use serde::{Deserialize, Deserializer, Serialize}; + +/// Longest scope name, in bytes. +pub const MAX_SCOPE_NAME: usize = 64; + +const APP: &str = "Application"; + +/// The name of a scope. Never empty, at most [`MAX_SCOPE_NAME`] bytes, without `:`. +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)] +#[serde(transparent)] +pub struct Scope(String); + +impl Scope { + /// `None` for an empty name, one over [`MAX_SCOPE_NAME`] bytes, or one with `:` or a control + /// character. + pub fn new(name: impl Into) -> Option { + let name = name.into(); + let ok = !name.is_empty() && name.len() <= MAX_SCOPE_NAME && !name.chars().any(|c| c == ':' || c.is_control()); + ok.then_some(Scope(name)) + } + + /// The application scope, `Application`. + pub fn app() -> Scope { + Scope(APP.to_string()) + } + + pub fn is_app(&self) -> bool { + self.0 == APP + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for Scope { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl<'de> Deserialize<'de> for Scope { + fn deserialize>(deserializer: D) -> Result { + let name = String::deserialize(deserializer)?; + Scope::new(name).ok_or_else(|| serde::de::Error::custom("bad scope name")) + } +} + +/// What kind of scope a name is. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ScopeKind { + Application, + /// Works while the panel has the keyboard. Names that are not registered count as panels. + Panel, + /// Works only while the context is active, in any panel. + Context, +} + +/// The scope registry: contexts, panels and the pairs of panels that share their shortcuts. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Scopes { + panels: Vec, + contexts: Vec, + shares: Vec<(String, String)>, + panel_fallthrough: bool, +} + +impl Default for Scopes { + fn default() -> Scopes { + Scopes { panels: Vec::new(), contexts: Vec::new(), shares: Vec::new(), panel_fallthrough: true } + } +} + +/// What has the keyboard: the focused panel, the active contexts, and whether a text field is +/// being typed in. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Active<'a> { + pub panel: Option<&'a str>, + pub contexts: &'a [&'a str], + pub typing: bool, +} + +impl<'a> Active<'a> { + /// No panel focused, no context, not typing. + pub const NONE: Active<'static> = Active { panel: None, contexts: &[], typing: false }; + + pub const fn panel(panel: &'a str) -> Active<'a> { + Active { panel: Some(panel), contexts: &[], typing: false } + } +} + +impl Scopes { + pub fn new() -> Scopes { + Scopes::default() + } + + /// Registers a panel (used by [`Scopes::panels`]; unknown names rank as panels anyway). + pub fn with_panel(mut self, name: &str) -> Scopes { + if !self.panels.iter().any(|p| p == name) { + self.panels.push(name.to_string()); + } + self + } + + pub fn with_context(mut self, name: &str) -> Scopes { + if !self.contexts.iter().any(|c| c == name) { + self.contexts.push(name.to_string()); + } + self + } + + /// Two panels that show the same thing and share their shortcuts (EffectCraft's Timeline and + /// Composition). + pub fn with_share(mut self, a: &str, b: &str) -> Scopes { + if !self.shares(a, b) { + self.shares.push((a.to_string(), b.to_string())); + } + self + } + + /// Whether another panel's shortcut still runs when nothing nearer claims the chord. On by + /// default. + pub fn with_panel_fallthrough(mut self, on: bool) -> Scopes { + self.panel_fallthrough = on; + self + } + + pub fn panels(&self) -> &[String] { + &self.panels + } + + pub fn contexts(&self) -> &[String] { + &self.contexts + } + + pub fn panel_fallthrough(&self) -> bool { + self.panel_fallthrough + } + + /// Whether `scope` is the application or a registered panel, context or sharing panel. + pub fn knows(&self, scope: &Scope) -> bool { + let name = scope.as_str(); + scope.is_app() + || self.panels.iter().any(|p| p == name) + || self.contexts.iter().any(|c| c == name) + || self.shares.iter().any(|(a, b)| a == name || b == name) + } + + pub fn kind(&self, scope: &Scope) -> ScopeKind { + self.kind_of(scope.as_str()) + } + + fn kind_of(&self, name: &str) -> ScopeKind { + if name == APP { + ScopeKind::Application + } else if self.contexts.iter().any(|c| c == name) { + ScopeKind::Context + } else { + ScopeKind::Panel + } + } + + /// Whether panels `a` and `b` (in either order) share their shortcuts. + pub fn shares(&self, a: &str, b: &str) -> bool { + self.shares.iter().any(|(x, y)| (x == a && y == b) || (x == b && y == a)) + } + + /// How strongly a binding in `scope` claims a chord: lower wins, `None` does not run. An active + /// context 0, the focused panel 1, a panel sharing with it 2, the application 3, any other + /// panel 4 with fallthrough on. An inactive context never runs. + // from effectcraft#1266 `scope_rank` + pub fn rank(&self, scope: &Scope, active: &Active) -> Option { + let name = scope.as_str(); + match self.kind_of(name) { + ScopeKind::Context => active.contexts.contains(&name).then_some(0), + ScopeKind::Application => Some(3), + ScopeKind::Panel => match active.panel { + Some(p) if p == name => Some(1), + Some(p) if self.shares(p, name) => Some(2), + _ => self.panel_fallthrough.then_some(4), + }, + } + } + + /// Whether the same chord in `a` and `b` makes only one of them work: the same scope, two + /// panels that share, or two different contexts (both can be active at once). Other pairs that + /// can be active together shadow (`Some(false)`): a context over anything else, a panel over + /// the application. `None`: never active together (two unrelated panels). + pub(crate) fn relation(&self, a: &Scope, b: &Scope) -> Option { + if a == b { + return Some(true); + } + match (self.kind(a), self.kind(b)) { + (ScopeKind::Context, ScopeKind::Context) => Some(true), + (ScopeKind::Context, _) | (_, ScopeKind::Context) => Some(false), + (ScopeKind::Application, _) | (_, ScopeKind::Application) => Some(false), + (ScopeKind::Panel, ScopeKind::Panel) => self.shares(a.as_str(), b.as_str()).then_some(true), + } + } +} diff --git a/crates/keymap/tests/chord.rs b/crates/keymap/tests/chord.rs new file mode 100644 index 000000000..116b357e4 --- /dev/null +++ b/crates/keymap/tests/chord.rs @@ -0,0 +1,178 @@ +use craft_keymap::chord::foreign::{Flavor, ForeignError, ReadNote, read_foreign}; +use craft_keymap::{Chord, Key, MAX_CHORD_TEXT, Mods, ParseError, Platform, Trigger}; + +fn chord(text: &str) -> Chord { + Chord::parse(text).unwrap_or_else(|e| panic!("{text}: {e}")) +} + +fn mods(cmd: bool, ctrl: bool, alt: bool, shift: bool) -> Mods { + Mods { cmd, ctrl, alt, shift } +} + +#[test] +fn canonical_text_round_trips_for_every_key_and_modifier_set() { + for &key in Key::ALL { + for bits in 0..16u8 { + let c = Chord::new(mods(bits & 1 != 0, bits & 2 != 0, bits & 4 != 0, bits & 8 != 0), key); + let text = c.to_string(); + assert_eq!(Chord::parse(&text), Ok(c), "{text}"); + assert_eq!(Trigger::parse(&format!("{text} {text}")), Ok(Trigger::double(c)), "{text} double"); + let json = serde_json::to_string(&Trigger::single(c)).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), Trigger::single(c)); + // macOS display text reads back as the same chord. + assert_eq!(Chord::parse(&c.display(Platform::Mac)), Ok(c), "{}", c.display(Platform::Mac)); + } + } + assert_eq!(chord("Cmd+Ctrl+Alt+Shift+K").to_string(), "Cmd+Ctrl+Alt+Shift+K"); + assert_eq!(serde_json::to_string(&chord("shift+cmd+k")).unwrap(), "\"Cmd+Shift+K\""); +} + +#[test] +fn aliases_parse_to_canonical_chords() { + let cases = [ + ("cmd+shift+z", "Cmd+Shift+Z"), + ("Shift+Command+Z", "Cmd+Shift+Z"), + ("meta+z", "Cmd+Z"), + ("Super+Z", "Cmd+Z"), + ("mod+z", "Cmd+Z"), + ("⌘⇧Z", "Cmd+Shift+Z"), + ("⌃⌥⇧⌘K", "Cmd+Ctrl+Alt+Shift+K"), + ("⌘+K", "Cmd+K"), + ("⌘Shift+K", "Cmd+Shift+K"), + ("control+opt+left", "Ctrl+Alt+Left"), + ("ctl+option+ArrowUp", "Ctrl+Alt+Up"), + // craft-menu writes Ctrl before Cmd. + ("Ctrl+Cmd+Alt+Shift+M", "Cmd+Ctrl+Alt+Shift+M"), + ("Ctrl+Cmd+F", "Cmd+Ctrl+F"), + ("Cmd++", "Cmd++"), + ("⌘+", "Cmd++"), + ("+", "+"), + ("Cmd+Plus", "Cmd++"), + ("cmd+Equals", "Cmd+="), + ("Cmd+-", "Cmd+-"), + ("Cmd + K", "Cmd+K"), + ("esc", "Escape"), + ("return", "Enter"), + ("del", "Delete"), + ("pgup", "PageUp"), + ("pgdn", "PageDown"), + ("arrowdown", "Down"), + ("spacebar", "Space"), + ("ins", "Insert"), + ("f12", "F12"), + ("Num5", "5"), + ("Semicolon", ";"), + ("Questionmark", "?"), + ("OpenCurlyBracket", "{"), + ("Backtick", "`"), + ("⌘⌫", "Cmd+Backspace"), + ]; + for (text, canonical) in cases { + assert_eq!(chord(text).to_string(), canonical, "{text}"); + } +} + +#[test] +fn hostile_text_is_refused() { + let long = "Cmd+".repeat(MAX_CHORD_TEXT / 4) + "K"; + assert!(long.len() > MAX_CHORD_TEXT); + let cases: &[(&str, ParseError)] = &[ + ("", ParseError::Empty), + (" ", ParseError::Empty), + (&long, ParseError::TooLong), + ("+++", ParseError::UnknownModifier("+".into())), + ("++", ParseError::MissingKey), + ("Cmd+", ParseError::MissingKey), + ("Cmd", ParseError::MissingKey), + ("⌘", ParseError::MissingKey), + ("Shift+Alt", ParseError::MissingKey), + ("Cmd+Command+K", ParseError::DuplicateModifier("Command".into())), + ("⌘⌘K", ParseError::DuplicateModifier("⌘".into())), + ("Cmd+é", ParseError::UnknownKey("é".into())), + ("Ctrl+ж+K", ParseError::UnknownModifier("ж".into())), + ("Hyper+K", ParseError::UnknownModifier("Hyper".into())), + ("A B", ParseError::Sequence), + ("Cmd+K Cmd+J", ParseError::Sequence), + ("A A A", ParseError::UnknownKey("A A A".into())), + ]; + for (text, err) in cases { + assert_eq!(Trigger::parse(text).as_ref(), Err(err), "{text:?}"); + } + let wide = "⌘".repeat(30); + assert_eq!(Chord::parse(&wide), Err(ParseError::TooLong)); + assert!(serde_json::from_str::("\"Cmd+Nope\"").is_err()); +} + +#[test] +fn display_follows_the_platform() { + let c = chord("Cmd+Ctrl+Alt+Shift+K"); + assert_eq!(c.display(Platform::Mac), "⌃⌥⇧⌘K"); + assert_eq!(c.display(Platform::Windows), "Ctrl+Alt+Shift+K"); + assert_eq!(chord("Ctrl+Up").display(Platform::Mac), "⌃↑"); + assert_eq!(chord("Ctrl+Up").display(Platform::Linux), "Ctrl+Up"); + assert_eq!(chord("Cmd+Enter").display(Platform::Mac), "⌘⏎"); + assert_eq!(chord("Shift+Tab").display(Platform::Mac), "⇧⇥"); + assert_eq!(chord("Space").display(Platform::Mac), "Space"); + assert_eq!(chord("Alt+PageDown").display(Platform::Windows), "Alt+Page Down"); + assert_eq!(Trigger::parse("Cmd+K Cmd+K").unwrap().display(Platform::Mac), "⌘K ⌘K"); + assert_eq!(Trigger::parse("A A").unwrap().to_string(), "A A"); +} + +#[test] +fn ctrl_folds_into_cmd_off_macos() { + let ctrl = chord("Ctrl+S"); + let cmd = chord("Cmd+S"); + assert_ne!(ctrl.effective(Platform::Mac), cmd.effective(Platform::Mac)); + for p in [Platform::Windows, Platform::Linux] { + assert_eq!(ctrl.effective(p), cmd); + assert_eq!(chord("Cmd+Ctrl+S").effective(p), cmd); + } + assert!(ctrl.has_command() && cmd.has_command()); + assert!(chord("Shift+B").is_plain() && !chord("Alt+B").is_plain()); + assert!(chord("Shift+F35").is_function_key() && !chord("F").is_function_key()); +} + +#[test] +fn foreign_windows_text() { + let read = |t: &str| read_foreign(t, Flavor::Windows); + let ok = |t: &str| read(t).unwrap_or_else(|e| panic!("{t}: {e}")); + assert_eq!(ok("Shift+Ctrl+S"), (Trigger::single(chord("Cmd+Shift+S")), vec![])); + assert_eq!(ok("Ctrl+,").0, Trigger::single(chord("Cmd+,"))); + assert_eq!(ok(",").0, Trigger::single(chord(","))); + assert_eq!(ok("Ctrl++").0, Trigger::single(chord("Cmd++"))); + assert_eq!(ok("Ctrl+-").0, Trigger::single(chord("Cmd+-"))); + assert_eq!(ok("Alt-F4").0, Trigger::single(chord("Alt+F4"))); + assert_eq!(ok("Ctrl + S").0, Trigger::single(chord("Cmd+S"))); + assert_eq!(ok("Shift + Ctrl + S").0, Trigger::single(chord("Cmd+Shift+S"))); + assert_eq!(ok("Ctrl + +").0, Trigger::single(chord("Cmd++"))); + assert_eq!(ok("Alt - F4").0, Trigger::single(chord("Alt+F4"))); + assert_eq!(ok("Ctrl Page Down").0, Trigger::single(chord("Cmd+PageDown"))); + assert_eq!(ok("Shift+Up Arrow").0, Trigger::single(chord("Shift+Up"))); + assert_eq!(ok("Num +"), (Trigger::single(chord("+")), vec![ReadNote::Numpad])); + assert_eq!(ok("Ctrl+Num /"), (Trigger::single(chord("Cmd+/")), vec![ReadNote::Numpad])); + assert_eq!(ok("Numpad 5"), (Trigger::single(chord("5")), vec![ReadNote::Numpad])); + assert_eq!(ok("Num Enter"), (Trigger::single(chord("Enter")), vec![ReadNote::Numpad])); + assert_eq!(read("Win+E"), Err(ForeignError::UnsupportedModifier("Win".into()))); + assert_eq!(read("Meta+E"), Err(ForeignError::UnsupportedModifier("Meta".into()))); + assert_eq!(read(""), Err(ForeignError::Empty)); + assert_eq!(read(&"x".repeat(MAX_CHORD_TEXT + 1)), Err(ForeignError::TooLong)); + assert_eq!(read("Ctrl+Num Lock"), Err(ForeignError::UnknownKey("Num Lock".into()))); + assert_eq!(read("Alt"), Err(ForeignError::UnknownKey("Alt".into()))); +} + +#[test] +fn foreign_mac_text() { + let texts = ["Shift+Cmd+S", "Ctrl+Opt+Left"]; + assert_eq!(Flavor::detect(texts), Flavor::Mac); + assert_eq!(Flavor::detect(["Shift+Ctrl+S", "Alt+F4"]), Flavor::Windows); + assert_eq!(Flavor::detect(["⌥⌘K"]), Flavor::Mac); + let ok = |t: &str| read_foreign(t, Flavor::Mac).unwrap_or_else(|e| panic!("{t}: {e}")).0; + assert_eq!(ok("Shift+Cmd+S"), Trigger::single(chord("Cmd+Shift+S"))); + assert_eq!(ok("Ctrl+Opt+Left"), Trigger::single(chord("Ctrl+Alt+Left"))); + assert_eq!(ok("Control-Option-Space"), Trigger::single(chord("Ctrl+Alt+Space"))); + assert_eq!(ok("⇧⌘S"), Trigger::single(chord("Cmd+Shift+S"))); + assert_eq!(ok("⌃⌥⇞"), Trigger::single(chord("Ctrl+Alt+PageUp"))); + assert_eq!(ok("Cmd+,"), Trigger::single(chord("Cmd+,"))); + // In a Windows set the same ⌃ is the command modifier. + assert_eq!(read_foreign("⌃S", Flavor::Windows).map(|r| r.0), Ok(Trigger::single(chord("Cmd+S")))); +} diff --git a/crates/keymap/tests/egui.rs b/crates/keymap/tests/egui.rs new file mode 100644 index 000000000..7e275abab --- /dev/null +++ b/crates/keymap/tests/egui.rs @@ -0,0 +1,290 @@ +#![cfg(feature = "egui")] + +use craft_keymap::egui::{Dispatcher, Hit, matches}; +use craft_keymap::{Active, Bindable, Binding, Chord, CommandRef, Key, Keymap, Kind, Mods, Platform, Scope, Scopes}; +use egui::{Event, InputState, Key as EguiKey, Modifiers}; + +fn chord(text: &str) -> Chord { + Chord::parse(text).unwrap_or_else(|e| panic!("{text}: {e}")) +} + +#[test] +fn every_key_converts_both_ways() { + for &key in Key::ALL { + assert_eq!(Key::from_egui(key.to_egui()), Some(key), "{key}"); + } + for k in [EguiKey::Copy, EguiKey::Cut, EguiKey::Paste, EguiKey::BrowserBack, EguiKey::ShiftLeft, EguiKey::IntlBackslash] { + assert_eq!(Key::from_egui(k), None); + } +} + +#[test] +fn modifiers_and_shortcuts_follow_the_platform() { + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + assert_eq!(Mods::from_egui(&ctrl, Platform::Windows), Mods::CMD); + assert_eq!(Mods::from_egui(&Modifiers::CTRL, Platform::Mac), Mods::CTRL); + assert_eq!(Mods::from_egui(&Modifiers::MAC_CMD, Platform::Mac), Mods::CMD); + + assert!(matches(&chord("Ctrl+S"), EguiKey::S, &ctrl, Platform::Windows)); + assert!(matches(&chord("Cmd+S"), EguiKey::S, &ctrl, Platform::Windows)); + assert!(!matches(&chord("Cmd+S"), EguiKey::S, &Modifiers::CTRL, Platform::Mac)); + + let shortcut = chord("Cmd+Shift+Z").to_egui_shortcut(); + assert_eq!(shortcut.logical_key, EguiKey::Z); + assert!(Modifiers { mac_cmd: true, command: true, shift: true, ..Modifiers::NONE }.matches_exact(shortcut.modifiers)); +} + +#[test] +fn shifted_symbols_match_their_bindings() { + let p = Platform::Windows; + let shift = Modifiers::SHIFT; + let none = Modifiers::NONE; + let cmd = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + let cmd_shift = Modifiers { shift: true, ..cmd }; + + // Shift+base matches the shifted key egui reports, but the base key alone does not. + assert!(matches(&chord("Shift+;"), EguiKey::Colon, &shift, p)); + assert!(!matches(&chord("Shift+;"), EguiKey::Semicolon, &none, p)); + assert!(!matches(&chord(";"), EguiKey::Colon, &shift, p)); + assert!(matches(&chord("Shift+/"), EguiKey::Questionmark, &shift, p)); + assert!(matches(&chord("Cmd+Shift+]"), EguiKey::CloseCurlyBracket, &cmd_shift, p)); + assert!(matches(&chord("Shift+1"), EguiKey::Exclamationmark, &shift, p)); + // A shifted symbol bound directly matches while Shift is held to type it. + assert!(matches(&chord("?"), EguiKey::Questionmark, &shift, p)); + assert!(matches(&chord(":"), EguiKey::Colon, &none, p)); + + // Zoom keys: `=` also matches `+`, with or without Shift; `+` matches Shift+`=`. + assert!(matches(&chord("Cmd+="), EguiKey::Plus, &cmd, p)); + assert!(matches(&chord("Cmd+="), EguiKey::Plus, &cmd_shift, p)); + assert!(matches(&chord("Cmd+="), EguiKey::Equals, &cmd, p)); + assert!(matches(&chord("Cmd++"), EguiKey::Equals, &cmd_shift, p)); + assert!(matches(&chord("Cmd++"), EguiKey::Plus, &cmd_shift, p)); + assert!(!matches(&chord("Cmd++"), EguiKey::Equals, &cmd, p)); + assert!(!matches(&chord("Cmd+="), EguiKey::Plus, &none, p)); + assert!(!matches(&chord("Cmd+="), EguiKey::Minus, &cmd, p)); +} + +const CTRL: Modifiers = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + +fn dispatch_keymap() -> Keymap { + let app = |id: &str, keys: &[&str]| keys.iter().fold(Bindable::new(id, id, Scope::app()), |e, k| e.with_default(Binding::parse(k).unwrap())); + let tool = |id: &str| app(id, &["M"]).with_kind(Kind::Tool { group: Some("select".into()) }); + let catalogue = vec![ + app("edit.copy", &["Cmd+C", "Cmd+Insert"]), + app("app.quit", &["Cmd+Alt+Q"]), + app("view.refresh", &["Cmd+Alt+F5"]), + app("file.save", &["Cmd+S"]), + app("view.zoomIn", &["="]), + app("help.find", &["Shift+;"]), + app("tool.brush", &["B"]), + app("app.loop", &["L"]), + Bindable::new("timeline.loop", "Loop", Scope::new("Timeline").unwrap()).with_default(Binding::parse("L").unwrap()), + tool("tool.marquee"), + tool("tool.ellipse"), + app("reveal.one", &["U"]), + app("reveal.all", &["U U"]), + ]; + Keymap::new(catalogue, Scopes::new().with_panel("Timeline"), Platform::Windows) +} + +fn press(key: EguiKey, modifiers: Modifiers) -> Event { + Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers } +} + +fn frame(time: f64, modifiers: Modifiers, events: Vec) -> InputState { + let mut input = InputState::default(); + input.time = time; + input.modifiers = modifiers; + input.events = events; + input +} + +/// Dispatches one frame and returns the ids that ran and the events left. +fn run(d: &mut Dispatcher, km: &Keymap, active: &Active, mut input: InputState) -> (Vec, Vec) { + let hits = d.dispatch(&mut input, km, active); + (hits.into_iter().map(|h| h.command.id).collect(), input.events) +} + +#[test] +fn a_bound_press_runs_once_and_is_removed_with_its_text() { + let km = dispatch_keymap(); + let events = vec![ + press(EguiKey::B, Modifiers::NONE), + Event::Text("b".into()), + Event::Key { key: EguiKey::B, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }, + press(EguiKey::Q, Modifiers::NONE), + Event::Text("q".into()), + ]; + let (ran, left) = run(&mut Dispatcher::new(), &km, &Active::NONE, frame(1.0, Modifiers::NONE, events)); + assert_eq!(ran, ["tool.brush"]); + // The release and the unbound Q with its text stay. + assert_eq!(left.len(), 3); + assert!(matches!(left[0], Event::Key { key: EguiKey::B, pressed: false, .. })); + assert!(matches!(left[1], Event::Key { key: EguiKey::Q, pressed: true, .. })); + assert_eq!(left[2], Event::Text("q".into())); +} + +#[test] +fn shifted_symbols_and_zoom_keys_reach_their_bindings() { + let km = dispatch_keymap(); + let mut d = Dispatcher::new(); + let shift = Modifiers::SHIFT; + let (ran, left) = run(&mut d, &km, &Active::NONE, frame(1.0, shift, vec![press(EguiKey::Colon, shift), Event::Text(":".into())])); + assert_eq!(ran, ["help.find"]); + assert!(left.is_empty()); + let (ran, _) = run(&mut d, &km, &Active::NONE, frame(2.0, Modifiers::NONE, vec![press(EguiKey::Plus, Modifiers::NONE)])); + assert_eq!(ran, ["view.zoomIn"]); + let (ran, _) = run(&mut d, &km, &Active::NONE, frame(3.0, shift, vec![press(EguiKey::Plus, shift)])); + assert_eq!(ran, ["view.zoomIn"]); +} + +#[test] +fn clipboard_events_run_their_chords_outside_text_fields() { + let km = dispatch_keymap(); + let mut d = Dispatcher::new(); + let (ran, left) = run(&mut d, &km, &Active::NONE, frame(1.0, CTRL, vec![Event::Copy])); + assert_eq!(ran, ["edit.copy"]); + assert!(left.is_empty()); + + let typing = Active { typing: true, ..Active::NONE }; + let (ran, left) = run(&mut d, &km, &typing, frame(2.0, CTRL, vec![Event::Copy])); + assert!(ran.is_empty()); + assert_eq!(left, [Event::Copy]); + + // The web build sends the key press and the Copy event it causes: one copy. + let (ran, _) = run(&mut d, &km, &Active::NONE, frame(3.0, CTRL, vec![press(EguiKey::C, CTRL), Event::Copy])); + assert_eq!(ran, ["edit.copy"]); +} + +#[test] +fn clipboard_presses_stay_with_the_text_field() { + let km = dispatch_keymap(); + let mut d = Dispatcher::new(); + let typing = Active { typing: true, ..Active::NONE }; + // The web build's Cmd+C press and its Copy event both reach the text field. + let events = vec![press(EguiKey::C, CTRL), Event::Copy, press(EguiKey::Insert, CTRL)]; + let (ran, left) = run(&mut d, &km, &typing, frame(1.0, CTRL, events.clone())); + assert!(ran.is_empty(), "{ran:?}"); + assert_eq!(left, events); + let (ran, _) = run(&mut d, &km, &Active::NONE, frame(2.0, CTRL, vec![press(EguiKey::Insert, CTRL)])); + assert_eq!(ran, ["edit.copy"]); +} + +#[test] +fn a_press_that_types_text_stays_with_the_text_field() { + let km = dispatch_keymap(); + let mut d = Dispatcher::new(); + let typing = Active { typing: true, ..Active::NONE }; + // A press the web build's text agent follows with the text it typed. + let events = vec![press(EguiKey::B, Modifiers::NONE), Event::Text("b".into())]; + let (ran, left) = run(&mut d, &km, &typing, frame(1.0, Modifiers::NONE, events.clone())); + assert!(ran.is_empty(), "{ran:?}"); + assert_eq!(left, events); +} + +#[test] +fn ctrl_alt_on_a_printable_key_is_left_to_the_text_field() { + let km = dispatch_keymap(); + let mut d = Dispatcher::new(); + let typing = Active { typing: true, ..Active::NONE }; + // AltGr+Q on a German layout types `@`; Windows reports it as Ctrl+Alt+Q, and egui-winit sends + // no Text event while Ctrl is held. + let alt_gr = Modifiers { alt: true, ..CTRL }; + let events = vec![press(EguiKey::Q, alt_gr)]; + let (ran, left) = run(&mut d, &km, &typing, frame(1.0, alt_gr, events.clone())); + assert!(ran.is_empty(), "{ran:?}"); + assert_eq!(left, events); + let (ran, _) = run(&mut d, &km, &typing, frame(2.0, alt_gr, vec![press(EguiKey::F5, alt_gr)])); + assert_eq!(ran, ["view.refresh"], "a key that types nothing"); + let (ran, left) = run(&mut d, &km, &Active::NONE, frame(3.0, alt_gr, events)); + assert_eq!(ran, ["app.quit"], "outside a text field"); + assert!(left.is_empty()); + + // macOS has no AltGr: Cmd+Option+Q is a command chord while typing. + let mac = Keymap::new( + vec![Bindable::new("app.quit", "Quit", Scope::app()).with_default(Binding::parse("Cmd+Alt+Q").unwrap())], + Scopes::new(), + Platform::Mac, + ); + let cmd_opt = Modifiers { alt: true, mac_cmd: true, command: true, ..Modifiers::NONE }; + let (ran, _) = run(&mut Dispatcher::new(), &mac, &typing, frame(4.0, cmd_opt, vec![press(EguiKey::Q, cmd_opt)])); + assert_eq!(ran, ["app.quit"]); +} + +#[test] +fn typing_blocks_plain_keys_but_not_command_chords() { + let km = dispatch_keymap(); + let mut d = Dispatcher::new(); + let typing = Active { typing: true, ..Active::NONE }; + let events = vec![press(EguiKey::B, Modifiers::NONE), Event::Text("b".into()), press(EguiKey::S, CTRL)]; + let (ran, left) = run(&mut d, &km, &typing, frame(1.0, CTRL, events)); + assert_eq!(ran, ["file.save"]); + assert_eq!(left.len(), 2); + assert_eq!(left[1], Event::Text("b".into())); +} + +#[test] +fn the_focused_panel_wins_and_tool_groups_cycle() { + let km = dispatch_keymap(); + let mut d = Dispatcher::new(); + let l = || frame(1.0, Modifiers::NONE, vec![press(EguiKey::L, Modifiers::NONE)]); + assert_eq!(run(&mut d, &km, &Active::panel("Timeline"), l()).0, ["timeline.loop"]); + assert_eq!(run(&mut d, &km, &Active::NONE, l()).0, ["app.loop"]); + + let mut input = frame(2.0, Modifiers::NONE, vec![press(EguiKey::M, Modifiers::NONE)]); + let hits = d.dispatch(&mut input, &km, &Active::NONE); + let tools = vec![CommandRef::new("tool.marquee"), CommandRef::new("tool.ellipse")]; + assert_eq!(hits, [Hit { command: tools[0].clone(), cycle: tools }]); +} + +#[test] +fn a_second_press_runs_the_double_binding() { + let km = dispatch_keymap(); + let mut d = Dispatcher::new(); + let key = |d: &mut Dispatcher, k: EguiKey, t: f64| run(d, &km, &Active::NONE, frame(t, Modifiers::NONE, vec![press(k, Modifiers::NONE)])).0; + let u = |d: &mut Dispatcher, t: f64| key(d, EguiKey::U, t); + assert_eq!(u(&mut d, 1.0), ["reveal.one"]); + assert_eq!(u(&mut d, 1.3), ["reveal.all"]); + // The press after a double starts over. + assert_eq!(u(&mut d, 1.5), ["reveal.one"]); + assert_eq!(u(&mut d, 2.5), ["reveal.one"]); + // B in between breaks the pair. + key(&mut d, EguiKey::B, 2.6); + assert_eq!(u(&mut d, 2.7), ["reveal.one"]); +} + +#[test] +fn two_presses_in_one_frame_make_a_double() { + let km = dispatch_keymap(); + let mut d = Dispatcher::new(); + let u = press(EguiKey::U, Modifiers::NONE); + let (ran, left) = run(&mut d, &km, &Active::NONE, frame(4.0, Modifiers::NONE, vec![u.clone(), u])); + assert_eq!(ran, ["reveal.one", "reveal.all"]); + assert!(left.is_empty(), "{left:?}"); +} + +#[test] +fn key_repeats_run_only_when_turned_on() { + let km = Keymap::new( + vec![ + Bindable::new("nudge.right", "Nudge", Scope::app()).with_default(Binding::parse("Right").unwrap()), + Bindable::new("jump.right", "Jump", Scope::app()).with_default(Binding::parse("Right Right").unwrap()), + ], + Scopes::new(), + Platform::Windows, + ); + let held = |repeat: bool| Event::Key { key: EguiKey::ArrowRight, physical_key: None, pressed: true, repeat, modifiers: Modifiers::NONE }; + let events = || vec![held(false), held(true), held(true)]; + + let mut on = Dispatcher::new().with_repeat(true); + let (ran, left) = run(&mut on, &km, &Active::NONE, frame(1.0, Modifiers::NONE, events())); + assert_eq!(ran, ["nudge.right", "nudge.right", "nudge.right"]); + assert!(left.is_empty()); + // Repeats neither made nor broke a double: the next press within the window is one. + let (ran, _) = run(&mut on, &km, &Active::NONE, frame(1.3, Modifiers::NONE, vec![held(false)])); + assert_eq!(ran, ["jump.right"]); + + let (ran, left) = run(&mut Dispatcher::new(), &km, &Active::NONE, frame(1.0, Modifiers::NONE, events())); + assert_eq!(ran, ["nudge.right"]); + assert_eq!(left, [held(true), held(true)]); +} diff --git a/crates/keymap/tests/import.rs b/crates/keymap/tests/import.rs new file mode 100644 index 000000000..56d17315f --- /dev/null +++ b/crates/keymap/tests/import.rs @@ -0,0 +1,546 @@ +//! Import of synthetic shortcut sets written for these tests. + +use std::collections::BTreeMap; + +use craft_keymap::chord::foreign::ReadNote; +use craft_keymap::chord::foreign::{Flavor, ForeignError}; +use craft_keymap::import::{ + Failed, FailedChange, MAX_IMPORT_ENTRIES, MAX_IMPORT_TEXT, MAX_KEYS_PER_ENTRY, MAX_SUGGESTIONS, SkipReason, Skipped, UnmatchedReason, + normalize_label, +}; +use craft_keymap::{ + Bindable, Binding, CommandRef, ContextRule, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportReport, Keymap, Kind, MAX_COMMANDS, + NoneDefined, Overrides, Platform, Scope, Scopes, Start, plan, reserved, +}; +use serde_json::json; + +fn b(text: &str) -> Binding { + Binding::parse(text).unwrap_or_else(|e| panic!("{text}: {e}")) +} + +fn bindings(texts: &[&str]) -> Vec { + texts.iter().map(|t| b(t)).collect() +} + +fn command(id: impl Into, label: &str, path: &[&str], keys: &[&str]) -> Bindable { + let mut out = Bindable::new(id, label, Scope::app()); + if !path.is_empty() { + out = out.with_path(path.iter().map(|s| s.to_string()).collect()); + } + keys.iter().fold(out, |e, k| e.with_default(b(k))) +} + +fn panel(name: &str) -> CommandRef { + CommandRef::with_params("window.panel", json!({ "panel": name })) +} + +fn catalogue() -> Vec { + vec![ + command("file.new", "Document…", &["File", "New", "Document…"], &["Cmd+N"]), + command("dialog.newDocument", "New Document Dialog", &[], &["Cmd+N"]), + command("file.close", "Close", &["File", "Close"], &["Cmd+W"]), + command("file.save", "Save", &["File", "Save"], &["Cmd+S"]), + command("file.exit", "Exit", &["File", "Exit"], &[]), + command("edit.paste", "Paste", &["Edit", "Paste"], &["Cmd+V"]), + command("edit.clear", "Clear", &["Edit", "Clear"], &[]), + command("edit.duplicate", "Duplicate", &["Edit", "Duplicate"], &["Cmd+Alt+Shift+D"]), + command("edit.checkSpelling", "Check Spelling…", &["Edit", "Proofing", "Check Spelling…"], &[]), + command("edit.pen", "Pen", &["Edit", "Preferences", "Pen"], &[]), + command("app.palette", "Command Palette", &[], &["Cmd+Alt+K"]), + command(panel("layers"), "Layers", &["Window", "Layers"], &["F7"]), + command(panel("pages"), "Pages", &["Window", "Pages"], &["F12"]), + command("view.guides", "Guides", &["View", "Grids & Guides", "Guides"], &["Cmd+;"]), + command("view.goToPage", "Go to Page…", &["View", "Go to Page…"], &["Cmd+J"]), + command("view.zoomIn", "Zoom In", &["View", "Zoom In"], &["Cmd+="]), + command("object.textFrameOptions", "Text Frame Options…", &["Object", "Text Frame Options…"], &["Cmd+B"]), + command("type.break", "Break", &["Type", "Breaks", "Break"], &[]), + command("type.columnBreak", "Insert Break", &["Type", "Column", "Insert Break"], &[]), + command("type.frameBreak", "Insert Break", &["Type", "Frame", "Insert Break"], &[]), + command("type.bold", "Bold", &["Type", "Style", "Bold"], &[]), + command("type.italic", "Italic", &["Type", "Style", "Italic"], &[]), + command("tool.pen", "Pen Tool", &[], &["P"]).with_kind(Kind::Tool { group: None }).with_alias("Pen"), + command("tool.type", "Type Tool", &[], &["T"]).with_kind(Kind::Tool { group: None }), + command("scripts.run", "Run Script", &[], &[]), + ] +} + +fn keymap(platform: Platform) -> Keymap { + Keymap::new(catalogue(), Scopes::new().with_context("Text"), platform).with_reserved(reserved::system(platform)) +} + +fn key(flavor: Flavor, context: &str, text: &str) -> ForeignKey { + ForeignKey::read(Some(context), text, flavor) +} + +fn entry(menu: Option<&str>, path: &[&str], keys: &[(&str, &str)], flavor: Flavor) -> ForeignEntry { + keys.iter().fold(ForeignEntry::new(menu, path.iter().copied()), |e, (c, t)| e.with_key(key(flavor, c, t))) +} + +fn win(menu: &str, path: &[&str], keys: &[(&str, &str)]) -> ForeignEntry { + entry(Some(menu), path, keys, Flavor::Windows) +} + +/// An InDesign-like Windows set, one entry per match rule or apply rule. +fn windows_set() -> ForeignSet { + let d = "Default"; + let entries = vec![ + win("File", &["New", "Document..."], &[(d, "Ctrl+N")]), + win("File", &["Close"], &[(d, "Ctrl+W"), (d, "Ctrl+F4")]), + win("File", &["Save"], &[(d, "Ctrl+Hyperspace")]), + win("File", &["Exit"], &[(d, "Alt+F4")]), + win("Edit", &["Paste"], &[(d, "Ctrl+E")]), + win("Edit", &["Clear"], &[(d, "Ctrl+E")]), + win("Edit", &["Duplicate"], &[]), + win("Edit", &["Duplicate"], &[]), + win("Edit", &["Spelling", "Check Spelling..."], &[(d, "Ctrl+Alt+K"), ("Text", "F7")]), + win("Edit", &["Frobnicate Everything"], &[(d, "Ctrl+F12")]), + win("Edit", &["Never Heard Of It"], &[]), + win("Window", &["Layers"], &[(d, "F7")]), + win("Window", &["Pages"], &[(d, "Shift+F12")]), + win("View", &["Grids & Guides", "SHOW/HIDE Guides"], &[(d, "Ctrl+Alt+;")]), + win("Layout", &["Go To Page"], &[(d, "Ctrl+Alt+J")]), + win("Object", &["Text Frame", "Options"], &[(d, "Ctrl+Alt+B")]), + win("Type", &["Insert", "Break"], &[(d, "Ctrl+Alt+Enter")]), + win("Type", &["Insert Break"], &[(d, "Shift+Enter")]), + win("Type", &["Style", "Bold"], &[("Text", "Shift+Ctrl+B")]), + win("Type", &["Style", "Italic"], &[(d, "Ctrl+I"), ("Table", "Ctrl+Alt+I")]), + win("Tools", &["Pen"], &[(d, "Shift+P")]).tool(), + win("Tools", &["Zoom In"], &[(d, "Z")]).tool(), + entry(None, &["Zoom In"], &[(d, "Ctrl+Alt+I")], Flavor::Windows), + entry(None, &["Somewhere", "Zoom In"], &[(d, "Ctrl+F11")], Flavor::Windows), + win("Scripts", &["Frobnicate"], &[(d, "Ctrl+Alt+R")]), + ]; + ForeignSet { name: Some("My Set".into()), entries } +} + +fn numpad_set() -> ForeignSet { + ForeignSet { name: None, entries: vec![win("Window", &["Layers"], &[("Default", "Num 7")]).at_line(2)] } +} + +fn windows_options() -> ImportOptions { + let mut remembered = BTreeMap::new(); + remembered.insert(ForeignEntry::new(Some("Scripts"), ["Frobnicate"]).remember_key(), CommandRef::new("scripts.run")); + ImportOptions { + contexts: vec![("default".into(), ContextRule::Home), ("TEXT".into(), ContextRule::HomeWithoutHomeEntry)], + remembered, + ..ImportOptions::default() + } +} + +fn import_windows() -> (Keymap, ImportReport) { + let mut km = keymap(Platform::Windows); + let report = plan(&windows_set(), &km, &windows_options()).apply(&mut km); + (km, report) +} + +fn has(km: &Keymap, id: impl Into, texts: &[&str]) { + let c = id.into(); + assert_eq!(km.bindings(&c), bindings(texts), "{}", c.key()); +} + +#[test] +fn labels_normalise_for_matching() { + assert_eq!(normalize_label("Check Spelling..."), "check spelling"); + assert_eq!(normalize_label("Check Spelling…"), "check spelling"); + assert_eq!(normalize_label("Grids && Guides"), "grids guides"); + assert_eq!(normalize_label("SHOW/HIDE Guides"), "guides"); + assert_eq!(normalize_label("Show Hidden Characters"), "hidden characters"); + assert_eq!(normalize_label("Hide "), "hide", "nothing left after the prefix"); + assert_eq!(normalize_label("ÄRGER"), "ärger"); +} + +#[test] +fn every_match_step_finds_its_command() { + let (km, r) = import_windows(); + assert_eq!(r.set.as_deref(), Some("My Set")); + // 1: full path, with `&`, case, spacing and Show/Hide normalised. + has(&km, "view.guides", &["Cmd+Alt+;"]); + // 2: joined segments `Text Frame Options` in Object. + has(&km, "object.textFrameOptions", &["Cmd+Alt+B"]); + // 2 is ambiguous (two `Insert Break` in Type), 3 finds `Break`. + has(&km, "type.break", &["Cmd+Alt+Enter"]); + // 3: last segment in the menu, under another submenu. + has(&km, "edit.checkSpelling", &["Cmd+Alt+K"]); + // 4: the label anywhere; also with no menu for a one-segment path. + has(&km, "view.goToPage", &["Cmd+Alt+J"]); + has(&km, "view.zoomIn", &["Cmd+Alt+I"]); + // 0: a remembered answer. + has(&km, "scripts.run", &["Cmd+Alt+R"]); + // A command with parameters, by its path. + has(&km, panel("pages"), &["Shift+F12"]); + // A tool entry matches the tool, not the command with the same label. + has(&km, "tool.pen", &["Shift+P"]); + has(&km, "edit.pen", &[]); + + let unmatched: Vec<(&str, UnmatchedReason)> = r.unmatched.iter().map(|u| (u.item.as_str(), u.reason)).collect(); + assert_eq!( + unmatched, + [ + ("Edit > Frobnicate Everything", UnmatchedReason::NoMatch), + ("Type > Insert Break", UnmatchedReason::Ambiguous), + ("Type > Style > Italic", UnmatchedReason::Context), + ("Tools > Zoom In", UnmatchedReason::Tool), + ("Somewhere > Zoom In", UnmatchedReason::NoMatch), + ] + ); + assert_eq!(r.unmatched[2].keys, "Table: Ctrl+Alt+I"); + assert_eq!(r.unmatched_without_shortcut, 1); + assert_eq!(r.unreadable.len(), 1); + assert_eq!(r.unreadable[0].item, "File > Save"); + assert_eq!(r.unreadable[0].keys, "Default: Ctrl+Hyperspace"); + assert!(matches!(r.unreadable[0].reason, ForeignError::UnknownKey(_))); + assert!(r.suggestions.is_empty(), "not asked for"); + assert_eq!(r.truncated, 0); +} + +#[test] +fn the_set_wins_and_the_report_says_how() { + let (km, r) = import_windows(); + // Two keys for one command, both kept in order. + has(&km, "file.close", &["Cmd+W", "Cmd+F4"]); + // The Text context counts only without a Default key. + has(&km, "type.bold", &["Cmd+Shift+B"]); + has(&km, "type.italic", &["Cmd+I"]); + has(&km, panel("layers"), &["F7"]); + // A later entry takes a chord from an earlier one; the earlier command keeps what it had. + has(&km, "edit.paste", &["Cmd+V"]); + has(&km, "edit.clear", &["Cmd+E"]); + let skipped: Vec<_> = r.skipped.iter().map(|s| (s.command.id.as_str(), s.shortcut.as_str(), s.kept_by.clone(), s.reason)).collect(); + assert_eq!( + skipped, + [("file.exit", "Alt+F4", None, SkipReason::Reserved), ("edit.paste", "Cmd+E", Some(CommandRef::new("edit.clear")), SkipReason::Taken)] + ); + // Taken from a command outside the set; the twin keeps its shared default. + has(&km, "app.palette", &[]); + has(&km, "dialog.newDocument", &["Cmd+N"]); + let cleared: Vec<_> = r.conflicts_cleared.iter().map(|c| (c.command.id.as_str(), c.label.as_str(), c.shortcut.as_str())).collect(); + assert_eq!(cleared, [("app.palette", "Command Palette", "Cmd+Alt+K")]); + // None defined clears; an unreadable key leaves the command as it was. + has(&km, "edit.duplicate", &[]); + has(&km, "file.save", &["Cmd+S"]); + // Bindings equal to the defaults leave no override. + let o = km.overrides(); + assert_eq!(o.get("file.new"), None); + assert_eq!(o.get(&panel("layers").key()), None); + assert_eq!(o.get("edit.duplicate"), Some(&[][..])); + assert_eq!(o.get("file.close"), Some(&["Cmd+W".to_string(), "Cmd+F4".to_string()][..])); + + let changed: Vec<&str> = r.changed.iter().map(|c| c.command.id.as_str()).collect(); + assert_eq!( + changed, + [ + "file.close", + "edit.clear", + "edit.duplicate", + "edit.checkSpelling", + "window.panel", + "view.guides", + "view.goToPage", + "object.textFrameOptions", + "type.break", + "type.bold", + "type.italic", + "tool.pen", + "view.zoomIn", + "scripts.run", + ] + ); + assert_eq!(r.imported, changed.len()); + let close = &r.changed[0]; + assert_eq!((close.label.as_str(), close.item.as_str()), ("Close", "File > Close")); + assert_eq!((close.from.clone(), close.to.clone()), (vec!["Cmd+W".to_string()], vec!["Cmd+W".to_string(), "Cmd+F4".to_string()])); +} + +#[test] +fn a_mac_set_reads_its_modifiers_and_scopes_text_keys() { + let mut km = keymap(Platform::Mac); + let mac = |menu: &str, path: &[&str], keys: &[(&str, &str)]| entry(Some(menu), path, keys, Flavor::Mac); + let set = ForeignSet { + name: Some("Mac".into()), + entries: vec![ + mac("File", &["Save"], &[("Default", "⇧⌘S")]), + mac("Edit", &["Paste"], &[("Default", "Cmd+Ctrl+V")]), + mac("Type", &["Style", "Italic"], &[("Text", "Shift+Cmd+I")]), + mac("Type", &["Style", "Bold"], &[("Default", "Cmd+B"), ("Tables", "Cmd+Opt+B")]), + ], + }; + let text = Scope::new("Text").unwrap(); + let options = ImportOptions { + contexts: vec![("Default".into(), ContextRule::Home), ("Text".into(), ContextRule::Scope(text))], + ..ImportOptions::default() + }; + let r = plan(&set, &km, &options).apply(&mut km); + has(&km, "file.save", &["Cmd+Shift+S"]); + has(&km, "edit.paste", &["Cmd+Ctrl+V"]); + has(&km, "type.italic", &["Text: Cmd+Shift+I"]); + has(&km, "type.bold", &["Cmd+B"]); + has(&km, "object.textFrameOptions", &[]); + assert_eq!(r.conflicts_cleared[0].command.id, "object.textFrameOptions"); + assert_eq!(r.unmatched.len(), 1); + assert_eq!((r.unmatched[0].keys.as_str(), r.unmatched[0].reason), ("Tables: Cmd+Opt+B", UnmatchedReason::Context)); + assert_eq!(r.changed.iter().find(|c| c.command.id == "type.italic").map(|c| c.to.clone()), Some(vec!["Text: Cmd+Shift+I".to_string()])); +} + +#[test] +fn start_and_none_defined_options() { + let set = ForeignSet { name: None, entries: vec![win("File", &["Close"], &[("Default", "Ctrl+Q")]), win("Edit", &["Duplicate"], &[])] }; + let user = || { + let mut o = Overrides::new(); + o.insert("file.save", vec!["Cmd+Alt+S".into()]); + o + }; + let options = |start, none_defined| ImportOptions { + contexts: vec![("Default".into(), ContextRule::Home)], + start, + none_defined, + ..ImportOptions::default() + }; + + let mut km = keymap(Platform::Windows).with_overrides(user()); + plan(&set, &km, &options(Start::Current, NoneDefined::Keep)).apply(&mut km); + has(&km, "file.save", &["Cmd+Alt+S"]); + has(&km, "file.close", &["Cmd+Q"]); + has(&km, "edit.duplicate", &["Cmd+Alt+Shift+D"]); + + let mut km = keymap(Platform::Windows).with_overrides(user()); + let r = plan(&set, &km, &options(Start::Defaults, NoneDefined::Clear)).apply(&mut km); + has(&km, "file.save", &["Cmd+S"]); + has(&km, "file.close", &["Cmd+Q"]); + has(&km, "edit.duplicate", &[]); + assert_eq!(r.imported, 2); +} + +#[test] +fn changes_that_find_the_overrides_full_are_reported() { + let set = ForeignSet { + name: None, + entries: vec![ + win("File", &["Close"], &[("Default", "Ctrl+J")]), + win("File", &["Save"], &[("Default", "Ctrl+Alt+S")]), + win("Edit", &["Duplicate"], &[]), + ], + }; + let full = || { + let mut o = Overrides::new(); + o.insert("file.close", vec!["Cmd+Q".into()]); + for n in 1..MAX_COMMANDS { + o.insert(format!("junk.{n}"), vec!["Cmd+K".into()]); + } + assert_eq!(o.len(), MAX_COMMANDS); + o + }; + let options = |start| ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], start, ..ImportOptions::default() }; + + // file.close has an entry to rewrite; the other changes each need a new one. + let mut km = keymap(Platform::Windows).with_overrides(full()); + let r = plan(&set, &km, &options(Start::Current)).apply(&mut km); + has(&km, "file.close", &["Cmd+J"]); + has(&km, "view.goToPage", &["Cmd+J"]); + has(&km, "file.save", &["Cmd+S"]); + has(&km, "edit.duplicate", &["Cmd+Alt+Shift+D"]); + let row = |id: &str, label: &str, change, shortcuts: &[&str]| Failed { + command: id.into(), + label: label.into(), + change, + shortcuts: shortcuts.iter().map(|s| s.to_string()).collect(), + }; + assert_eq!( + r.failed, + [ + row("file.save", "Save", FailedChange::Bind, &["Cmd+Alt+S"]), + row("edit.duplicate", "Duplicate", FailedChange::Clear, &[]), + row("view.goToPage", "Go to Page…", FailedChange::Unbind, &["Cmd+J"]), + ] + ); + assert_eq!(r.imported, 1); + assert!(r.conflicts_cleared.is_empty()); + let v = serde_json::to_value(&r).unwrap(); + assert_eq!( + v["failed"][0], + json!({"command": {"id": "file.save", "params": null}, "label": "Save", "change": "bind", "shortcuts": ["Cmd+Alt+S"]}) + ); + + // Starting from the defaults drops the entries, so everything fits. + let mut km = keymap(Platform::Windows).with_overrides(full()); + let r = plan(&set, &km, &options(Start::Defaults)).apply(&mut km); + assert!(r.failed.is_empty(), "{:?}", r.failed); + has(&km, "file.close", &["Cmd+J"]); + has(&km, "view.goToPage", &[]); + has(&km, "file.save", &["Cmd+Alt+S"]); + has(&km, "edit.duplicate", &[]); +} + +#[test] +fn keys_in_unknown_scopes_are_skipped_and_the_rest_apply() { + let set = ForeignSet { name: None, entries: vec![win("File", &["Close"], &[("Default", "Ctrl+Q"), ("Story", "Ctrl+K"), ("Text", "Ctrl+L")])] }; + let options = ImportOptions { + contexts: vec![ + ("Default".into(), ContextRule::Home), + ("Story".into(), ContextRule::Scope(Scope::new("Story").unwrap())), + ("Text".into(), ContextRule::Scope(Scope::new("Text").unwrap())), + ], + ..ImportOptions::default() + }; + let mut km = keymap(Platform::Windows); + let r = plan(&set, &km, &options).apply(&mut km); + has(&km, "file.close", &["Cmd+Q", "Text: Cmd+L"]); + assert_eq!( + r.skipped, + [Skipped { + command: "file.close".into(), + item: "File > Close".into(), + line: None, + shortcut: "Story: Cmd+K".into(), + kept_by: None, + reason: SkipReason::UnknownScope + }] + ); + assert_eq!(serde_json::to_value(r.skipped[0].reason).unwrap(), "unknownScope"); +} + +#[test] +fn suggestions_are_reported_never_applied() { + let mut km = keymap(Platform::Windows); + let set = ForeignSet { name: None, entries: vec![win("Edit", &["Chek Spelling Now"], &[("Default", "Ctrl+K")])] }; + let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], suggest: true, ..ImportOptions::default() }; + let p = plan(&set, &km, &options); + assert!(p.commands.is_empty()); + let r = p.apply(&mut km); + assert_eq!(r.suggestions.len(), 1); + assert_eq!(r.suggestions[0].item, "Edit > Chek Spelling Now"); + assert!(r.suggestions[0].candidates.contains(&CommandRef::new("edit.checkSpelling")), "{:?}", r.suggestions); + has(&km, "edit.checkSpelling", &[]); + assert!(km.overrides().is_empty()); + assert_eq!(r.imported, 0); +} + +#[test] +fn hostile_sets_are_capped_and_counted() { + // A full catalogue whose labels share words with every unmatched entry below, so each + // suggestion scores every command. + let mut catalogue = catalogue(); + let filler = MAX_COMMANDS - catalogue.len(); + catalogue.extend((0..filler).map(|i| command(format!("filler.c{i}").as_str(), &format!("Filler Command {i}"), &[], &[]))); + let mut km = Keymap::new(catalogue, Scopes::new().with_context("Text"), Platform::Windows).with_reserved(reserved::system(Platform::Windows)); + let long: String = "ä€𝄞 x".repeat(MAX_IMPORT_TEXT); + // Odd entries have keys and long labels that match nothing, so they reach the suggestions: + // words in the whole label, or two words and symbols, which score high enough to suggest. + let wordy = "Filler Command ä€𝄞 ".repeat(MAX_IMPORT_TEXT / 8); + let symbols = format!("Filler Command {}", "€𝄞 ".repeat(MAX_IMPORT_TEXT)); + let filler_entry = |i: usize| match i % 4 { + 1 => win("Edit", &[&symbols], &[("Default", "Ctrl+F12")]), + 3 => win("Edit", &[&format!("{wordy}{i}")], &[("Default", "Ctrl+F12")]), + _ => win("Edit", &[&format!("Item {i}")], &[]), + }; + let mut entries: Vec = (0..MAX_IMPORT_ENTRIES + 500).map(filler_entry).collect(); + let mut big = ForeignEntry::new(Some(long.as_str()), std::iter::repeat_n(long.clone(), 100)); + for _ in 0..MAX_KEYS_PER_ENTRY + 10 { + let trigger = Err(ForeignError::UnknownKey(long.clone())); + big = big.with_key(ForeignKey { context: Some(long.clone()), text: long.clone(), trigger, notes: vec![ReadNote::Numpad; 1000] }); + } + entries.insert(0, big); + entries.insert(1, win("Edit", &["Paste"], &[("Default", &long), ("Default", "Ctrl+\u{0}"), ("Default", "Win+E")])); + let set = ForeignSet { name: Some(long.clone()), entries }; + let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], suggest: true, ..ImportOptions::default() }; + let started = std::time::Instant::now(); + let r = plan(&set, &km, &options).apply(&mut km); + assert!(started.elapsed() < std::time::Duration::from_secs(240), "{:?}", started.elapsed()); + // Read filler entries are those before the cap, after the two inserted ones. + let read = MAX_IMPORT_ENTRIES - 2; + let keyed = read / 2; + assert!(!r.suggestions.is_empty() && r.suggestions.len() <= MAX_SUGGESTIONS, "{}", r.suggestions.len()); + assert!(r.truncated >= 500 + 10 + keyed + 1 - MAX_SUGGESTIONS, "{}", r.truncated); + assert_eq!(r.set.as_ref().map(|s| s.chars().count()), Some(MAX_IMPORT_TEXT)); + let row = r.unmatched.iter().find(|u| u.item.starts_with('ä')).unwrap(); + assert!(row.item.chars().count() <= MAX_IMPORT_TEXT * 34, "item of capped segments"); + assert!(row.keys.chars().count() <= (2 * MAX_IMPORT_TEXT + 4) * MAX_KEYS_PER_ENTRY); + assert_eq!(r.unreadable.len(), 1, "Paste's keys"); + has(&km, "edit.paste", &["Cmd+V"]); + // Entries past the cap are left out. + assert_eq!(r.unmatched_without_shortcut, read - keyed); +} + +#[test] +fn rows_carry_source_lines_and_approximated_keys() { + let mut km = keymap(Platform::Windows); + let d = "Default"; + let set = ForeignSet { + name: None, + entries: vec![ + win("Window", &["Layers"], &[(d, "Ctrl+Num 5"), (d, "Num 7")]).at_line(3), + win("Window", &["Layers"], &[(d, "Shift+F7")]).at_line(4), + win("Edit", &["Paste"], &[(d, "Ctrl+Num 5")]).at_line(5), + win("Edit", &["Chek Spelling Now"], &[(d, "Ctrl+K")]).at_line(8), + win("File", &["Save"], &[(d, "Ctrl+Hyperspace")]).at_line(9), + ], + }; + let options = ImportOptions { contexts: vec![(d.into(), ContextRule::Home)], suggest: true, ..ImportOptions::default() }; + let r = plan(&set, &km, &options).apply(&mut km); + // A keypad key binds the main key and is reported. Paste, a later entry, takes Cmd+5. + has(&km, panel("layers"), &["7", "Shift+F7"]); + has(&km, "edit.paste", &["Cmd+5"]); + let approximated: Vec<_> = r.approximated.iter().map(|a| (a.item.as_str(), a.line, a.keys.as_str(), a.note)).collect(); + assert_eq!( + approximated, + [ + ("Window > Layers", Some(3), "Default: Ctrl+Num 5, Default: Num 7", ReadNote::Numpad), + ("Edit > Paste", Some(5), "Default: Ctrl+Num 5", ReadNote::Numpad) + ] + ); + // Merged entries report the first one's line. + let layers = r.changed.iter().find(|c| c.command == panel("layers")).unwrap(); + assert_eq!(layers.line, Some(3)); + assert_eq!((r.skipped[0].item.as_str(), r.skipped[0].line), ("Window > Layers", Some(3))); + assert_eq!(r.unmatched[0].line, Some(8)); + assert_eq!(r.suggestions[0].line, Some(8)); + assert_eq!(r.unreadable[0].line, Some(9)); +} + +#[test] +fn report_json_uses_camel_case_names() { + let mut km = keymap(Platform::Windows); + let mut options = windows_options(); + options.suggest = true; + let r = plan(&windows_set(), &km, &options).apply(&mut km); + let v = serde_json::to_value(&r).unwrap(); + let names = |v: &serde_json::Value| v.as_object().unwrap().keys().cloned().collect::>(); + let mut top = names(&v); + top.sort(); + assert_eq!( + top, + [ + "approximated", + "changed", + "conflictsCleared", + "failed", + "imported", + "set", + "skipped", + "suggestions", + "truncated", + "unmatched", + "unmatchedWithoutShortcut", + "unreadable" + ] + ); + let sorted = |v: &serde_json::Value| { + let mut n = names(v); + n.sort(); + n + }; + assert_eq!(sorted(&v["changed"][0]), ["command", "from", "item", "label", "line", "to"]); + assert_eq!(sorted(&v["conflictsCleared"][0]), ["command", "label", "shortcut"]); + assert_eq!(sorted(&v["skipped"][1]), ["command", "item", "keptBy", "line", "reason", "shortcut"]); + assert_eq!(v["skipped"][1]["keptBy"], json!({"id": "edit.clear", "params": null})); + assert_eq!(v["skipped"][0]["reason"], "reserved"); + assert_eq!(sorted(&v["unmatched"][0]), ["item", "keys", "line", "reason"]); + let reasons: Vec<&str> = v["unmatched"].as_array().unwrap().iter().filter_map(|u| u["reason"].as_str()).collect(); + assert_eq!(reasons, ["noMatch", "ambiguous", "context", "tool", "noMatch"]); + assert_eq!(sorted(&v["unreadable"][0]), ["item", "keys", "line", "reason"]); + assert_eq!(sorted(&v["suggestions"][0]), ["candidates", "item", "line"]); + let approximated = ImportReport { approximated: plan(&numpad_set(), &km, &options).report.approximated, ..ImportReport::default() }; + let a = serde_json::to_value(&approximated).unwrap(); + assert_eq!(sorted(&a["approximated"][0]), ["item", "keys", "line", "note"]); + assert_eq!(a["approximated"][0]["note"], "numpad"); + assert_eq!(v["changed"][0]["from"], json!(["Cmd+W"])); +} diff --git a/crates/keymap/tests/keymap.rs b/crates/keymap/tests/keymap.rs new file mode 100644 index 000000000..2e16997ae --- /dev/null +++ b/crates/keymap/tests/keymap.rs @@ -0,0 +1,523 @@ +use std::time::{Duration, Instant}; + +use craft_keymap::{ + Active, AssignError, Bindable, Binding, Chord, CommandRef, ConflictKind, DropReason, Key, Keymap, Kind, Lookup, MAX_BINDINGS, MAX_COMMANDS, + MAX_CONFLICTS, Mods, Overrides, Platform, Policy, Problem, Scope, Scopes, Trigger, TypingRule, reserved, +}; +use serde_json::json; + +fn chord(text: &str) -> Chord { + Chord::parse(text).unwrap_or_else(|e| panic!("{text}: {e}")) +} + +fn scope(name: &str) -> Scope { + Scope::new(name).unwrap() +} + +fn b(text: &str) -> Binding { + Binding::parse(text).unwrap_or_else(|e| panic!("{text}: {e}")) +} + +fn cmd(id: &str) -> CommandRef { + CommandRef::new(id) +} + +fn app(id: &str, keys: &[&str]) -> Bindable { + keys.iter().fold(Bindable::new(id, id, Scope::app()), |e, k| e.with_default(b(k))) +} + +fn in_scope(id: &str, home: &str, keys: &[&str]) -> Bindable { + keys.iter().fold(Bindable::new(id, id, scope(home)), |e, k| e.with_default(b(k))) +} + +fn run(id: &str) -> Lookup { + Lookup::Run(cmd(id)) +} + +fn scopes() -> Scopes { + Scopes::new().with_panel("Timeline").with_panel("Composition").with_share("Timeline", "Composition").with_context("Text") +} + +fn press(km: &Keymap, text: &str, active: &Active) -> Lookup { + km.lookup(&chord(text), false, active) +} + +#[test] +fn command_keys_are_canonical_whatever_the_map_order() { + let c = CommandRef::with_params("window.panel", json!({"z": [1, "a b"], "panel": "layers"})); + assert_eq!(c.key(), r#"window.panel {"panel":"layers","z":[1,"a b"]}"#); + assert_eq!(CommandRef::parse_key(&c.key()), Some(c)); + assert_eq!(CommandRef::with_params("edit.copy", json!({})).key(), "edit.copy"); + assert_eq!(CommandRef::parse_key("x {bad"), None); + assert_eq!(CommandRef::parse_key(&"x".repeat(300)), None); +} + +#[test] +fn lookup_picks_the_nearest_scope() { + let catalogue = vec![ + app("edit.copy", &["Cmd+C"]), + in_scope("timeline.copy", "Timeline", &["Cmd+C"]), + app("file.bake", &["Cmd+B"]), + in_scope("text.bold", "Text", &["Cmd+B", "Cmd+I"]), + in_scope("timeline.loop", "Timeline", &["L"]), + ]; + let km = Keymap::new(catalogue.clone(), scopes(), Platform::Mac); + let text = ["Text"]; + assert_eq!(press(&km, "Cmd+C", &Active::NONE), run("edit.copy")); + assert_eq!(press(&km, "Cmd+C", &Active::panel("Timeline")), run("timeline.copy")); + assert_eq!(press(&km, "Cmd+C", &Active::panel("Composition")), run("timeline.copy"), "sharing panel"); + assert_eq!(press(&km, "Cmd+C", &Active::panel("Effects")), run("edit.copy")); + assert_eq!(press(&km, "Cmd+B", &Active::panel("Timeline")), run("file.bake")); + assert_eq!(press(&km, "Cmd+B", &Active { panel: Some("Timeline"), contexts: &text, typing: false }), run("text.bold")); + assert_eq!(press(&km, "Cmd+I", &Active::NONE), Lookup::None, "inactive context"); + assert_eq!(press(&km, "L", &Active::panel("Effects")), run("timeline.loop"), "fallthrough"); + assert_eq!(km.lookup(&chord("L"), true, &Active::panel("Timeline")), Lookup::None, "double press is its own trigger"); + + let strict = Keymap::new(catalogue, scopes().with_panel_fallthrough(false), Platform::Mac); + assert_eq!(press(&strict, "L", &Active::panel("Effects")), Lookup::None); + assert_eq!(press(&strict, "L", &Active::panel("Timeline")), run("timeline.loop")); +} + +#[test] +fn typing_rules_decide_what_fires_in_a_text_field() { + let catalogue = vec![app("tool.brush", &["B"]), app("edit.copy", &["Cmd+C"]), app("help", &["F1"]), app("view.alt", &["Alt+V"])]; + let typing = Active { panel: None, contexts: &[], typing: true }; + let cases = [ + (TypingRule::PlainKeysWait, [false, true, true, true]), + (TypingRule::CommandKeysOnly, [false, true, true, false]), + (TypingRule::AllWait, [false, false, false, false]), + ]; + for (rule, fires) in cases { + let km = Keymap::new(catalogue.clone(), Scopes::new(), Platform::Windows).with_typing_rule(rule); + for ((key, id), fire) in [("B", "tool.brush"), ("Cmd+C", "edit.copy"), ("F1", "help"), ("Alt+V", "view.alt")].into_iter().zip(fires) { + let want = if fire { run(id) } else { Lookup::None }; + assert_eq!(press(&km, key, &typing), want, "{rule:?} {key}"); + assert_eq!(press(&km, key, &Active::NONE), run(id), "{rule:?} {key} not typing"); + } + } +} + +#[test] +fn bindings_of_an_active_context_fire_while_typing_under_every_rule() { + let catalogue = vec![ + app("text.bold", &["Text: Cmd+B", "Text: B"]), + app("file.bake", &["Cmd+B"]), + in_scope("timeline.cut", "Timeline", &["Cmd+K"]), + app("file.save", &["Cmd+S"]), + ]; + let editing = Active { panel: Some("Timeline"), contexts: &["Text"], typing: true }; + let elsewhere = Active { contexts: &[], ..editing }; + let km = Keymap::new(catalogue, scopes(), Platform::Mac).with_typing_rule(TypingRule::AllWait); + assert_eq!(press(&km, "Cmd+B", &editing), run("text.bold")); + assert_eq!(press(&km, "B", &editing), run("text.bold")); + assert_eq!(press(&km, "Cmd+K", &editing), Lookup::None, "panel bindings wait"); + assert_eq!(press(&km, "Cmd+S", &editing), Lookup::None, "app bindings wait"); + assert_eq!(press(&km, "Cmd+B", &elsewhere), Lookup::None, "the app binding waits when the context is not active"); +} + +#[test] +fn tools_of_one_group_cycle_and_keep_their_shared_key() { + let tool = |id: &str, group: &str| app(id, &["B"]).with_kind(Kind::Tool { group: Some(group.into()) }); + let mut km = + Keymap::new(vec![tool("tool.brush", "brush"), tool("tool.pencil", "brush"), tool("tool.mixer", "brush")], Scopes::new(), Platform::Mac); + assert_eq!(press(&km, "B", &Active::NONE), Lookup::Cycle(vec![cmd("tool.brush"), cmd("tool.pencil"), cmd("tool.mixer")])); + assert!(km.conflicts().is_empty()); + + km.clear(&cmd("tool.mixer")); + let done = km.assign(&cmd("tool.mixer"), b("B"), Policy::Steal).unwrap(); + assert!(done.taken_from.is_empty()); + assert_eq!(km.bindings(&cmd("tool.brush")), vec![b("B")]); + + let mixed = Keymap::new(vec![tool("tool.brush", "brush"), app("layer.bake", &["B"]), tool("tool.pencil", "brush")], Scopes::new(), Platform::Mac); + assert_eq!(press(&mixed, "B", &Active::NONE), run("tool.brush")); +} + +#[test] +fn steal_keep_and_refuse() { + let catalogue = vec![app("edit.copy", &["Cmd+C"]), app("edit.duplicate", &["Cmd+D"]), in_scope("timeline.copy", "Timeline", &[])]; + let mut km = Keymap::new(catalogue, scopes(), Platform::Mac); + let dup = cmd("edit.duplicate"); + + let err = km.assign(&dup, b("Cmd+C"), Policy::Refuse).unwrap_err(); + let AssignError::Taken(holders) = err else { panic!("{err:?}") }; + assert_eq!(holders[0].command, cmd("edit.copy")); + assert_eq!(km.bindings(&dup), vec![b("Cmd+D")]); + + let done = km.assign(&dup, b("Cmd+C"), Policy::Keep).unwrap(); + assert_eq!(done.clashes.len(), 1); + assert_eq!(km.bindings(&cmd("edit.copy")), vec![b("Cmd+C")]); + assert_eq!(km.bindings(&dup), vec![b("Cmd+D"), b("Cmd+C")]); + + km.reset_all(); + let done = km.assign(&dup, b("Cmd+C"), Policy::Steal).unwrap(); + assert_eq!(done.taken_from[0].command, cmd("edit.copy")); + assert!(km.bindings(&cmd("edit.copy")).is_empty()); + assert_eq!(km.overrides().get("edit.copy"), Some(&[][..])); + assert_eq!(press(&km, "Cmd+C", &Active::NONE), run("edit.duplicate")); + + // A panel binding shadows the application one; nothing is taken. + let done = km.assign(&cmd("timeline.copy"), b("Cmd+D"), Policy::Refuse).unwrap(); + assert!(done.taken_from.is_empty() && done.clashes.is_empty()); + assert_eq!(km.assign(&cmd("nope"), b("Cmd+D"), Policy::Steal), Err(AssignError::UnknownCommand)); +} + +#[test] +fn twins_keep_their_shared_default_key() { + let mut km = Keymap::new(vec![app("file.close", &["Cmd+W"]), app("sequence.close", &["Cmd+W"])], Scopes::new(), Platform::Mac); + km.clear(&cmd("sequence.close")); + let done = km.assign(&cmd("sequence.close"), b("Cmd+W"), Policy::Refuse).unwrap(); + assert!(done.taken_from.is_empty()); + assert_eq!(km.bindings(&cmd("file.close")), vec![b("Cmd+W")]); + assert!(km.overrides().is_empty(), "back to the defaults"); +} + +#[test] +fn clearing_a_command_frees_its_panel_copies() { + // filmcraft#1333: New Bin holds Cmd+B in the application and in the Project panel. + let catalogue = vec![app("project.newBin", &["Cmd+B", "Project: Cmd+B"]), app("clip.bold", &[])]; + let mut km = Keymap::new(catalogue, Scopes::new().with_panel("Project"), Platform::Mac); + assert_eq!(press(&km, "Cmd+B", &Active::panel("Project")), run("project.newBin")); + assert!(km.clear(&cmd("project.newBin"))); + assert!(km.bindings(&cmd("project.newBin")).is_empty()); + assert_eq!(press(&km, "Cmd+B", &Active::panel("Project")), Lookup::None); + assert!(km.assign(&cmd("clip.bold"), b("Project: Cmd+B"), Policy::Refuse).is_ok()); +} + +#[test] +fn reserved_chords_are_refused() { + let catalogue = vec![app("view.next", &[])]; + let mut mac = Keymap::new(catalogue.clone(), Scopes::new(), Platform::Mac).with_reserved(reserved::system(Platform::Mac)); + let err = mac.assign(&cmd("view.next"), b("Cmd+Tab"), Policy::Steal).unwrap_err(); + assert_eq!(err, AssignError::Reserved(Trigger::parse("Cmd+Tab").unwrap())); + + let mut win = Keymap::new(catalogue.clone(), Scopes::new(), Platform::Windows).with_reserved(reserved::system(Platform::Windows)); + assert!(matches!(win.assign(&cmd("view.next"), b("Ctrl+Alt+Delete"), Policy::Steal), Err(AssignError::Reserved(_)))); + assert!(reserved::system(Platform::Linux).contains(&chord("Cmd+Alt+F12"))); + + let mut o = Overrides::new(); + o.insert("view.next", vec!["Alt+F4".into()]); + let linux = Keymap::new(catalogue, Scopes::new(), Platform::Linux).with_reserved(reserved::system(Platform::Linux)).with_overrides(o); + assert!(linux.bindings(&cmd("view.next")).is_empty()); + assert_eq!(linux.problems(), vec![Problem::Reserved { key: "view.next".into(), text: "Alt+F4".into() }]); +} + +#[test] +fn conflicts_tell_clashes_from_shadows() { + let catalogue = vec![ + app("edit.copy", &["Cmd+C"]), + app("color.copy", &["Cmd+C"]), + in_scope("timeline.copy", "Timeline", &["Cmd+C"]), + in_scope("text.cut", "Text", &["Cmd+X"]), + app("edit.cut", &["Cmd+X"]), + app("edit.find", &["Cmd+F"]), + in_scope("tab.find", "Effects", &["Cmd+F"]), + in_scope("render.find", "Render", &["Cmd+R"]), + in_scope("effects.render", "Effects", &["Cmd+R"]), + ]; + let mut km = Keymap::new(catalogue, scopes(), Platform::Mac); + let summary = |km: &Keymap| -> Vec<(String, String, String, ConflictKind, bool)> { + km.conflicts().into_iter().map(|c| (c.chord.to_string(), c.a.0.id, c.b.0.id, c.kind, c.in_defaults)).collect() + }; + let s = |a: &str, x: &str, y: &str, k, d| (a.to_string(), x.to_string(), y.to_string(), k, d); + let mut want = vec![ + s("Cmd+C", "edit.copy", "color.copy", ConflictKind::Clash, true), + s("Cmd+C", "edit.copy", "timeline.copy", ConflictKind::Shadow, true), + s("Cmd+C", "color.copy", "timeline.copy", ConflictKind::Shadow, true), + s("Cmd+X", "text.cut", "edit.cut", ConflictKind::Shadow, true), + s("Cmd+F", "edit.find", "tab.find", ConflictKind::Shadow, true), + // Fallthrough: in a third panel the two tie. + s("Cmd+R", "render.find", "effects.render", ConflictKind::Shadow, true), + ]; + let sort = |mut v: Vec<(String, String, String, ConflictKind, bool)>| { + v.sort(); + v + }; + assert_eq!(sort(summary(&km)), sort(want.clone())); + + km.assign(&cmd("edit.find"), b("Cmd+D"), Policy::Steal).unwrap(); + km.assign(&cmd("edit.cut"), b("Cmd+D"), Policy::Keep).unwrap(); + want.push(s("Cmd+D", "edit.cut", "edit.find", ConflictKind::Clash, false)); + assert_eq!(sort(summary(&km)), sort(want.clone())); + + let order: Vec<_> = summary(&km).into_iter().map(|(c, a, b, ..)| (c, a, b)).collect(); + let chords: Vec = km.conflicts().iter().map(|c| c.chord).collect(); + assert!(chords.is_sorted(), "{order:?}"); + let c = |x: &str, y: &str| order.iter().position(|(_, a, b)| a == x && b == y); + assert!(c("edit.copy", "color.copy") < c("edit.copy", "timeline.copy"), "{order:?}"); + assert!(c("edit.copy", "timeline.copy") < c("color.copy", "timeline.copy"), "{order:?}"); + + let strict = Keymap::new(km.catalogue().to_vec(), scopes().with_panel_fallthrough(false), Platform::Mac); + assert!(!strict.conflicts().iter().any(|c| c.chord.to_string() == "Cmd+R")); +} + +/// 4096 commands, each with 16 bindings on one chord in 16 panels. +fn crowded(scopes: Scopes, kind: Kind) -> (Keymap, Overrides) { + let catalogue: Vec = (0..MAX_COMMANDS).map(|n| app(&format!("c.{n}"), &[]).with_kind(kind.clone())).collect(); + let mut o = Overrides::new(); + for n in 0..MAX_COMMANDS { + assert!(o.insert(format!("c.{n}"), (1..=MAX_BINDINGS).map(|p| format!("P{p}: K")).collect())); + } + (Keymap::new(catalogue, scopes, Platform::Mac), o) +} + +fn panels(n: usize) -> Scopes { + (1..=n).fold(Scopes::new(), |s, p| s.with_panel(&format!("P{p}"))) +} + +#[test] +fn crowded_chords_stay_fast() { + let limit = Duration::from_secs(8); + + // Panels the app never registered are not bound. + let (km, o) = crowded(Scopes::new(), Kind::Command); + let km = km.with_overrides(o); + let t = Instant::now(); + assert!(km.conflicts().is_empty()); + assert!(t.elapsed() < limit, "{:?}", t.elapsed()); + assert!(km.bindings(&cmd("c.0")).is_empty()); + assert_eq!(km.overrides().get("c.0").map(<[String]>::len), Some(MAX_BINDINGS), "kept verbatim"); + assert!(km.problems().contains(&Problem::UnknownScope { key: "c.0".into(), text: "P1: K".into() })); + + // Registered panels that never share: many conflicts, capped. + let (km, o) = crowded(panels(MAX_BINDINGS).with_panel_fallthrough(false), Kind::Command); + let km = km.with_overrides(o); + let t = Instant::now(); + assert_eq!(km.conflicts().len(), MAX_CONFLICTS); + assert!(t.elapsed() < limit, "{:?}", t.elapsed()); + + // Tools of one group: no conflicts, and no pair is compared. + let (km, o) = crowded(panels(MAX_BINDINGS), Kind::Tool { group: None }); + let km = km.with_overrides(o); + let t = Instant::now(); + assert!(km.conflicts().is_empty()); + assert!(t.elapsed() < limit, "{:?}", t.elapsed()); +} + +#[test] +fn assigning_many_commands_stays_fast() { + let catalogue: Vec = (0..MAX_COMMANDS).map(|n| app(&format!("c.{n}"), &[])).collect(); + let mut km = Keymap::new(catalogue, panels(MAX_BINDINGS), Platform::Mac); + let list: Vec = (1..=MAX_BINDINGS).map(|p| b(&format!("P{p}: K"))).collect(); + let t = Instant::now(); + for n in 0..MAX_COMMANDS { + let done = km.set_bindings(&cmd(&format!("c.{n}")), list.clone(), Policy::Steal).unwrap(); + assert_eq!(done.taken_from.len(), if n == 0 { 0 } else { MAX_BINDINGS }); + } + assert!(t.elapsed() < Duration::from_secs(8), "{:?}", t.elapsed()); + assert_eq!(km.bindings(&cmd(&format!("c.{}", MAX_COMMANDS - 1))), list); + assert!(km.bindings(&cmd("c.0")).is_empty()); + assert_eq!(press(&km, "K", &Active::panel("P3")), run(&format!("c.{}", MAX_COMMANDS - 1))); +} + +#[test] +fn binding_text_round_trips_for_every_key() { + let panel = scope("Timeline"); + for &key in Key::ALL { + for mods in [Mods::NONE, Mods { cmd: true, ctrl: true, alt: true, shift: true }] { + let chord = Chord::new(mods, key); + for trigger in [Trigger::single(chord), Trigger::double(chord)] { + for binding in [Binding::new(trigger), Binding::in_scope(trigger, panel.clone())] { + let text = binding.to_string(); + assert_eq!(Binding::parse(&text).as_ref(), Ok(&binding), "{text}"); + } + } + } + } + assert_eq!(Binding::parse(": :"), Ok(Binding::new(Trigger::double(Chord::plain(Key::Colon))))); +} + +#[test] +fn edits_are_refused_when_the_overrides_are_full() { + let catalogue = vec![app("edit.copy", &["Cmd+C"]), app("edit.duplicate", &["Cmd+D"]), app("edit.cut", &[])]; + let mut o = Overrides::new(); + o.insert("edit.cut", vec!["Cmd+X".into()]); + for n in 1..MAX_COMMANDS { + o.insert(format!("junk.{n}"), vec![]); + } + assert_eq!(o.len(), MAX_COMMANDS); + let mut km = Keymap::new(catalogue, Scopes::new(), Platform::Mac).with_overrides(o.clone()); + let (copy, dup, cut) = (cmd("edit.copy"), cmd("edit.duplicate"), cmd("edit.cut")); + + assert_eq!(km.assign(&dup, b("Cmd+K"), Policy::Steal), Err(AssignError::Full)); + assert_eq!(km.set_bindings(&dup, vec![], Policy::Steal), Err(AssignError::Full)); + assert!(!km.clear(©)); + assert!(!km.remove(©, &b("Cmd+C"))); + // Taking Cmd+C from edit.copy would need an entry for it too. + assert_eq!(km.assign(&cut, b("Cmd+C"), Policy::Steal), Err(AssignError::Full)); + assert_eq!(km.bindings(©), vec![b("Cmd+C")]); + assert_eq!(km.bindings(&cut), vec![b("Cmd+X")]); + assert_eq!(km.overrides(), &o); + + // Commands that have an entry still change, and back to the defaults frees one. + assert!(km.assign(&cut, b("Cmd+Shift+X"), Policy::Steal).is_ok()); + assert!(km.reset(&cut)); + assert!(km.assign(&dup, b("Cmd+K"), Policy::Steal).is_ok()); +} + +#[test] +fn bindings_in_unknown_scopes_are_refused() { + let catalogue = vec![app("edit.copy", &["Cmd+C"]), in_scope("timeline.mark", "Timeline", &["M"])]; + let mut km = Keymap::new(catalogue, Scopes::new().with_context("Text"), Platform::Mac); + let copy = cmd("edit.copy"); + assert_eq!(km.assign(©, b("Nowhere: Cmd+K"), Policy::Steal), Err(AssignError::UnknownScope(scope("Nowhere")))); + assert!(km.assign(©, b("Timeline: Cmd+K"), Policy::Steal).is_ok(), "a catalogue scope"); + assert!(km.assign(©, b("Text: Cmd+K"), Policy::Steal).is_ok(), "a registered scope"); + + let mut o = Overrides::new(); + o.insert("edit.copy", vec!["Nowhere: Cmd+K".into(), "Cmd+J".into()]); + km.set_overrides(o); + assert_eq!(km.bindings(©), vec![b("Cmd+J")]); + assert_eq!(km.problems(), vec![Problem::UnknownScope { key: "edit.copy".into(), text: "Nowhere: Cmd+K".into() }]); +} + +#[test] +fn unreadable_entries_keep_the_defaults() { + let catalogue = vec![app("edit.copy", &["Cmd+C"]), app("edit.paste", &["Cmd+V"])]; + let mut o = Overrides::new(); + o.insert("edit.copy", vec!["Cmd+Nope".into()]); + o.insert("edit.paste", vec![]); + let mut km = Keymap::new(catalogue, Scopes::new(), Platform::Mac).with_overrides(o); + assert_eq!(km.bindings(&cmd("edit.copy")), vec![b("Cmd+C")]); + assert!(km.bindings(&cmd("edit.paste")).is_empty()); + assert_eq!(km.overrides().get("edit.copy"), Some(&["Cmd+Nope".to_string()][..]), "verbatim"); + assert!(km.reset(&cmd("edit.copy"))); + assert_eq!(km.overrides().get("edit.copy"), None); +} + +#[test] +fn entries_with_nothing_usable_keep_the_defaults() { + let catalogue = vec![app("edit.copy", &["Cmd+C"]), app("edit.cut", &["Cmd+X"]), app("edit.paste", &["Cmd+V"]), app("edit.undo", &["Cmd+Z"])]; + let mut o = Overrides::new(); + o.insert("edit.copy", vec!["Nowhere: Cmd+K".into()]); + o.insert("edit.cut", vec!["Alt+F4".into()]); + o.insert("edit.paste", vec!["Nowhere: Cmd+K".into(), "Alt+F4".into(), "Cmd+J".into()]); + o.insert("edit.undo", vec![]); + let km = Keymap::new(catalogue, Scopes::new(), Platform::Linux).with_reserved(reserved::system(Platform::Linux)).with_overrides(o); + assert_eq!(km.bindings(&cmd("edit.copy")), vec![b("Cmd+C")], "only an unknown scope"); + assert_eq!(km.bindings(&cmd("edit.cut")), vec![b("Cmd+X")], "only a reserved chord"); + assert_eq!(km.bindings(&cmd("edit.paste")), vec![b("Cmd+J")]); + assert!(km.bindings(&cmd("edit.undo")).is_empty()); +} + +#[test] +fn overrides_hold_only_what_differs_from_the_defaults() { + let catalogue = vec![app("edit.copy", &["Cmd+C"]), in_scope("timeline.mark", "Timeline", &["M"])]; + let mut km = Keymap::new(catalogue, scopes(), Platform::Mac); + let copy = cmd("edit.copy"); + km.assign(©, b("Timeline: Cmd+K"), Policy::Steal).unwrap(); + assert_eq!(km.overrides().get("edit.copy"), Some(&["Cmd+C".to_string(), "Timeline: Cmd+K".to_string()][..])); + assert_eq!(km.bindings(©)[1], Binding::in_scope(Trigger::parse("Cmd+K").unwrap(), scope("Timeline"))); + assert!(km.remove(©, &b("Timeline: Cmd+K"))); + assert!(km.overrides().is_empty()); + + km.set_bindings(&cmd("timeline.mark"), vec![b("Timeline: M")], Policy::Steal).unwrap(); + assert!(km.overrides().is_empty(), "the home scope written out is the same binding"); + km.set_bindings(©, vec![b("Cmd+Shift+C")], Policy::Steal).unwrap(); + assert!(km.reset(©)); + assert!(km.overrides().is_empty()); +} + +#[test] +fn edits_keep_the_texts_this_build_cannot_use() { + let catalogue = vec![app("file.quit", &["Cmd+Q"]), app("file.close", &["Cmd+W"]), app("file.save", &["Cmd+S"])]; + let mut o = Overrides::new(); + o.insert("file.quit", vec!["Cmd+Q".into(), "Cmd+FutureKey".into(), "Nowhere: Cmd+J".into()]); + let mut km = Keymap::new(catalogue.clone(), scopes(), Platform::Mac).with_overrides(o); + let quit = cmd("file.quit"); + let texts = |km: &Keymap| km.overrides().get("file.quit").map(<[String]>::to_vec); + let strings = |t: &[&str]| Some(t.iter().map(|s| s.to_string()).collect::>()); + + km.assign(&quit, b("Cmd+W"), Policy::Steal).unwrap(); + assert_eq!(texts(&km), strings(&["Cmd+Q", "Cmd+W", "Cmd+FutureKey", "Nowhere: Cmd+J"])); + km.assign(&cmd("file.save"), b("Cmd+Q"), Policy::Steal).unwrap(); + assert_eq!(texts(&km), strings(&["Cmd+W", "Cmd+FutureKey", "Nowhere: Cmd+J"]), "taken by a Steal"); + let reloaded = Keymap::new(catalogue, scopes(), Platform::Mac).with_overrides(km.overrides().clone()); + assert_eq!(reloaded.bindings(&quit), vec![b("Cmd+W")]); + + // An entry of only such texts would load as the defaults, so a cleared command drops them. + assert!(km.clear(&quit)); + assert_eq!(texts(&km), strings(&[])); + assert!(km.reset(&quit)); + assert_eq!(texts(&km), None); +} + +#[test] +fn an_override_equal_to_the_defaults_on_this_platform_is_not_stored() { + let mut km = Keymap::new(vec![app("file.save", &["Cmd+S"])], Scopes::new(), Platform::Windows); + km.set_bindings(&cmd("file.save"), vec![b("Ctrl+S")], Policy::Steal).unwrap(); + assert!(km.overrides().is_empty()); + assert_eq!(press(&km, "Ctrl+S", &Active::NONE), run("file.save")); +} + +#[test] +fn an_empty_text_in_the_map_form_removes_the_shortcut() { + let catalogue = vec![app("edit.copy", &["Cmd+C"]), app("edit.paste", &["Cmd+V"]), app("edit.cut", &["Cmd+X"])]; + let o: Overrides = serde_json::from_str(r#"{"edit.copy": "", "edit.paste": [""], "edit.cut": "Cmd+K"}"#).unwrap(); + assert!(o.load_notes().is_empty(), "{:?}", o.load_notes()); + let km = Keymap::new(catalogue.clone(), Scopes::new(), Platform::Mac).with_overrides(o); + assert!(km.bindings(&cmd("edit.copy")).is_empty(), "a removed default stays removed"); + assert!(km.bindings(&cmd("edit.paste")).is_empty()); + assert_eq!(km.bindings(&cmd("edit.cut")), vec![b("Cmd+K")]); + assert!(km.problems().is_empty()); + + let saved = serde_json::to_string(km.overrides()).unwrap(); + let again = Keymap::new(catalogue, Scopes::new(), Platform::Mac).with_overrides(serde_json::from_str(&saved).unwrap()); + assert!(again.bindings(&cmd("edit.copy")).is_empty(), "{saved}"); +} + +#[test] +fn ctrl_folds_into_cmd_off_macos() { + let catalogue = vec![app("edit.cut", &["Cmd+X"]), app("mac.cut", &["Ctrl+X"])]; + let win = Keymap::new(catalogue.clone(), Scopes::new(), Platform::Windows); + let mac = Keymap::new(catalogue, Scopes::new(), Platform::Mac); + let conflicts = win.conflicts(); + assert_eq!(conflicts.len(), 1); + assert_eq!((conflicts[0].kind, conflicts[0].chord.to_string()), (ConflictKind::Clash, "Cmd+X".to_string())); + assert!(mac.conflicts().is_empty()); + assert_eq!(press(&win, "Ctrl+X", &Active::NONE), run("edit.cut")); + assert_eq!(press(&mac, "Ctrl+X", &Active::NONE), run("mac.cut")); +} + +#[test] +fn hostile_overrides_load_without_panic_and_report_problems() { + let mut doc = serde_json::Map::new(); + for i in 0..(MAX_COMMANDS + 100) { + doc.insert(format!("junk.{i}"), json!(["Cmd+Z"])); + } + doc.insert("edit.copy".into(), json!(["Cmd+Nope", "x".repeat(10_000), 7, "Shift+C"])); + doc.insert("a".into(), json!(["Shift+A"])); + doc.insert("é".repeat(300), json!([])); + doc.insert("b".into(), json!({"deep": [[[[1]]]]})); + let o: Overrides = serde_json::from_value(serde_json::Value::Object(doc)).unwrap(); + assert!(o.len() <= MAX_COMMANDS); + + let km = Keymap::new(vec![app("edit.copy", &["Cmd+C"]), app("a", &[])], Scopes::new(), Platform::Linux).with_overrides(o.clone()); + assert_eq!(km.bindings(&cmd("edit.copy")), vec![b("Shift+C")]); + assert_eq!(km.overrides().get("edit.copy"), Some(&["Cmd+Nope".to_string(), "Shift+C".to_string()][..]), "verbatim"); + let problems = km.problems(); + assert!(problems.iter().any(|p| matches!(p, Problem::TooManyCommands { .. }))); + assert!(problems.contains(&Problem::Dropped { key: "edit.copy".into(), reason: DropReason::TextTooLong })); + assert!(problems.contains(&Problem::Dropped { key: "edit.copy".into(), reason: DropReason::NotText })); + assert!(problems.iter().any(|p| matches!(p, Problem::Dropped { reason: DropReason::KeyTooLong, .. }))); + assert!(problems.iter().any(|p| matches!(p, Problem::BadBinding { text, .. } if text == "Cmd+Nope"))); + assert!(problems.iter().any(|p| matches!(p, Problem::UnknownCommand { key } if key == "junk.0"))); + + let text = serde_json::to_string(&o).unwrap(); + let again: Overrides = serde_json::from_str(&text).unwrap(); + assert_eq!(again, o); + assert!(text.starts_with(r#"[{"command":"a","keys":["Shift+A"]},"#), "{}", &text[..80]); + assert!(serde_json::from_str::(r#"{"x": {"y": 1}, "z": true, "w": null, "v": "Cmd+V"}"#).is_ok()); + let items: Overrides = + serde_json::from_str(r#"[{"command": "v", "keys": "Cmd+V"}, {"command": "x"}, {"keys": []}, 3, [], {"command": "y", "keys": [1]}]"#).unwrap(); + assert_eq!(items.iter().collect::>(), [("v", &["Cmd+V".to_string()][..]), ("y", &[][..])]); + assert_eq!(items.load_notes().len(), 5); + + let twice: Overrides = serde_json::from_str(r#"[{"command": "v", "keys": ["Cmd+V"]}, {"command": "v", "keys": []}]"#).unwrap(); + assert_eq!(twice.get("v"), Some(&["Cmd+V".to_string()][..]), "the first entry stays"); + assert_eq!(twice.load_notes(), [Problem::DuplicateKey { key: "v".into() }]); + for text in [r#""x""#, "5", "true", "null"] { + let o: Overrides = serde_json::from_str(text).unwrap(); + assert!(o.is_empty(), "{text}"); + assert_eq!(o.load_notes(), [Problem::Dropped { key: String::new(), reason: DropReason::NotAList }], "{text}"); + } +} diff --git a/crates/keymap/tests/settings.rs b/crates/keymap/tests/settings.rs new file mode 100644 index 000000000..c63c893ba --- /dev/null +++ b/crates/keymap/tests/settings.rs @@ -0,0 +1,122 @@ +use std::time::Duration; + +use craft_keymap::{Bindable, Binding, CommandRef, DropReason, Keymap, Overrides, Platform, Policy, Problem, Scope, Scopes}; +use craft_settings::{Location, OpenOptions, Probe, Settings, SettingsStore}; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +#[derive(Serialize, Deserialize, Default, Clone, PartialEq, Debug)] +#[serde(default)] +struct Prefs { + general: General, + shortcuts: Overrides, +} + +#[derive(Serialize, Deserialize, Default, Clone, PartialEq, Debug)] +#[serde(default)] +struct General { + language: String, +} + +impl Settings for Prefs { + const APP_ID: &'static str = "keymaptest"; + const SCHEMA_VERSION: u32 = 1; +} + +fn open(dir: &std::path::Path) -> SettingsStore { + let probe = Probe { env: Box::new(|_| None), exe_dir: None, platform_config_dir: None }; + let options = OpenOptions::new(Location::Dir(dir.to_path_buf())).probe(probe).debounce(Duration::from_millis(10)); + let (store, report) = SettingsStore::open_with(options); + assert!(report.section_errors.is_empty(), "{report:?}"); + store +} + +fn keymap(overrides: Overrides) -> Keymap { + let catalogue = vec![ + Bindable::new(CommandRef::with_params("window.panel", json!({"panel": "layers"})), "Layers", Scope::app()), + Bindable::new("text.bold", "Bold", Scope::app()), + Bindable::new("edit.copy", "Copy", Scope::app()).with_default(Binding::parse("Cmd+C").unwrap()), + Bindable::new("edit.paste", "Paste", Scope::app()).with_default(Binding::parse("Cmd+V").unwrap()), + ]; + Keymap::new(catalogue, Scopes::new().with_context("Text"), Platform::Mac).with_overrides(overrides) +} + +#[test] +fn overrides_round_trip_through_craft_settings() { + let tmp = tempfile::tempdir().unwrap(); + let mut km = keymap(Overrides::new()); + let layers = CommandRef::with_params("window.panel", json!({"panel": "layers"})); + km.assign(&layers, Binding::parse("Cmd+Shift+L").unwrap(), Policy::Steal).unwrap(); + km.assign(&"text.bold".into(), Binding::parse("Text: Cmd+B").unwrap(), Policy::Steal).unwrap(); + km.clear(&"edit.copy".into()); + + let mut store = open(tmp.path()); + store.update(|p| p.shortcuts = km.overrides().clone()); + store.flush().unwrap(); + + // A hand edit: one text that does not parse, one value that is not a list. + let path = tmp.path().join("config.toml"); + let text = std::fs::read_to_string(&path).unwrap(); + let edit = r#"shortcuts = [{ command = "edit.paste", keys = ["Cmd+Nope"] }, { command = "edit.cut", keys = 5 }, "#; + assert!(text.contains("shortcuts = ["), "{text}"); + std::fs::write(&path, text.replacen("shortcuts = [", edit, 1)).unwrap(); + + let mut store = open(tmp.path()); + let mut km = keymap(store.get().shortcuts.clone()); + assert_eq!(km.bindings(&layers), vec![Binding::parse("Cmd+Shift+L").unwrap()]); + assert_eq!(km.bindings(&"text.bold".into()), vec![Binding::parse("Text: Cmd+B").unwrap()]); + assert!(km.bindings(&"edit.copy".into()).is_empty()); + assert_eq!(km.bindings(&"edit.paste".into()), vec![Binding::parse("Cmd+V").unwrap()], "nothing readable: the defaults"); + assert_eq!(km.overrides().get("edit.paste"), Some(&["Cmd+Nope".to_string()][..])); + let problems = km.problems(); + assert!(problems.contains(&Problem::Dropped { key: "edit.cut".into(), reason: DropReason::NotAList }), "{problems:?}"); + assert!(problems.iter().any(|p| matches!(p, Problem::BadBinding { text, .. } if text == "Cmd+Nope")), "{problems:?}"); + + store.update(|p| p.general.language = "de".into()); + store.flush().unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("keys = [\"Cmd+Nope\"]"), "{text}"); + assert!( + text.contains(r#"command = "window.panel {\"panel\":\"layers\"}""#) || text.contains(r#"command = 'window.panel {"panel":"layers"}'"#), + "{text}" + ); + assert_eq!(open(tmp.path()).get().shortcuts, store.get().shortcuts); + + // Removals reach the file. + km.reset(&layers); + store.update(|p| p.shortcuts = km.overrides().clone()); + store.flush().unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + let line = text.lines().find(|l| l.starts_with("shortcuts = ")).unwrap(); + assert!(!line.contains("window.panel"), "{text}"); + let reloaded = open(tmp.path()); + assert!(keymap(reloaded.get().shortcuts.clone()).bindings(&layers).is_empty()); +} + +#[test] +fn hand_written_array_of_tables_and_map_forms_load() { + for text in [ + "schema_version = 1\n\n[[shortcuts]]\ncommand = \"edit.copy\"\nkeys = [\"Cmd+K\"]\n\n[[shortcuts]]\ncommand = \"edit.paste\"\nkeys = []\n", + "schema_version = 1\n\n[shortcuts]\n\"edit.copy\" = [\"Cmd+K\"]\n\"edit.paste\" = []\n", + ] { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join("config.toml"), text).unwrap(); + let km = keymap(open(tmp.path()).get().shortcuts.clone()); + assert_eq!(km.bindings(&"edit.copy".into()), vec![Binding::parse("Cmd+K").unwrap()], "{text}"); + assert!(km.bindings(&"edit.paste".into()).is_empty(), "{text}"); + } +} + +#[test] +fn a_shortcuts_value_that_is_not_a_list_loads_as_no_overrides() { + for value in ["\"x\"", "5", "true"] { + let tmp = tempfile::tempdir().unwrap(); + let text = format!("schema_version = 1\nshortcuts = {value}\n\n[general]\nlanguage = \"de\"\n"); + std::fs::write(tmp.path().join("config.toml"), text).unwrap(); + let store = open(tmp.path()); + assert!(store.get().shortcuts.is_empty(), "{value}"); + assert_eq!(store.get().general.language, "de", "{value}"); + let problems = keymap(store.get().shortcuts.clone()).problems(); + assert_eq!(problems, vec![Problem::Dropped { key: String::new(), reason: DropReason::NotAList }], "{value}"); + } +} From 4df9e5936a7ab0932e7e794dcc340696d3567d34 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 04:21:48 +0000 Subject: [PATCH 02/32] keymap: let apps decline dispatch hits and keep clipboard events Hit carries the trigger that matched and whether the press matched it exactly. Dispatcher::dispatch_filtered takes a predicate; a declined hit leaves its event and text in place. egui's Copy, Cut and Paste events stay with the app unless with_clipboard_events(true): egui-winit sends them in place of the clipboard presses, and a Paste event consumed as a hit lost its text. With them on, Hit::pasted holds that text, and a web clipboard press and the event it causes run once for every clipboard chord, not only Cmd+C/X/V. The Hit doc line moves from DOUBLE_PRESS to Hit. --- crates/keymap/README.md | 19 ++-- crates/keymap/src/egui.rs | 170 +++++++++++++++++++++++++++--------- crates/keymap/tests/egui.rs | 71 +++++++++++++-- 3 files changed, 206 insertions(+), 54 deletions(-) diff --git a/crates/keymap/README.md b/crates/keymap/README.md index 01b12ed8b..526d04419 100644 --- a/crates/keymap/README.md +++ b/crates/keymap/README.md @@ -175,9 +175,18 @@ assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File ``` A press that runs a command is removed from egui's events, with the text it typed, so widgets - do not see it too. egui's Copy, Cut and Paste events count as Cmd+C, Cmd+X and Cmd+V outside - text fields. While a text field has the keyboard, clipboard events, clipboard key presses, - presses followed by text, and off macOS Ctrl+Alt with a letter, digit, punctuation or Space - stay with it: AltGr arrives as Ctrl+Alt on Windows and some Linux setups, and egui-winit sends - no text while Ctrl is held. + do not see it too. Each `Hit` carries the `trigger` that matched and `exact`, which is false + when the press matched through a stand-in (`:` for `Shift+;`, `+` for `=`). + `dispatch_filtered` takes a predicate that can decline a hit, for example a chord the native + menu has already handled: the press and its text then stay in egui's events, in their place. + While a text field has the keyboard, clipboard key presses, presses followed by text, and off + macOS Ctrl+Alt with a letter, digit, punctuation or Space stay with it: AltGr arrives as + Ctrl+Alt on Windows and some Linux setups, and egui-winit sends no text while Ctrl is held. `Dispatcher::new().with_repeat(true)` also runs commands on key repeats (held arrows). + + egui's Copy, Cut and Paste events stay with the app by default. On the desktop, egui-winit + sends them in place of the Cmd+C, Cmd+X and Cmd+V presses (Ctrl off macOS), so a binding on + those chords runs only with `with_clipboard_events(true)`. Then the events count as their + chords outside text fields, and a Paste event's text moves to `Hit::pasted`. An app whose + paste command asks egui for a paste gets a Paste event back, which runs that command again; + such an app keeps the default. diff --git a/crates/keymap/src/egui.rs b/crates/keymap/src/egui.rs index 2d783839a..fd4039d54 100644 --- a/crates/keymap/src/egui.rs +++ b/crates/keymap/src/egui.rs @@ -3,7 +3,7 @@ use ::egui::{Event, InputState, Key as EguiKey, KeyboardShortcut, Modifiers}; -use crate::chord::{Chord, Key, Mods, Platform}; +use crate::chord::{Chord, Key, Mods, Platform, Trigger}; use crate::command::CommandRef; use crate::keymap::{Keymap, Lookup}; use crate::scope::Active; @@ -135,10 +135,10 @@ fn candidates(pressed: Key, held: Mods, platform: Platform) -> Vec { out } -/// A command a key press runs. /// Seconds within which a second press of the same chord counts as a double press. pub const DOUBLE_PRESS: f64 = 0.6; +/// A command a key press runs. #[derive(Clone, Debug, PartialEq)] pub struct Hit { /// The command to run; for tools sharing the chord, the first of `cycle`. @@ -146,15 +146,24 @@ pub struct Hit { /// Tools of one group sharing the chord, in catalogue order (the app picks the next one); /// empty for a plain command. pub cycle: Vec, + /// The chord whose binding matched, with `double` set when the double binding ran. + pub trigger: Trigger, + /// Whether `trigger` is the press itself. `false` when the press matched through a stand-in: + /// the shifted key for a Shift binding (`:` for `Shift+;`), Shift held to type a symbol, or + /// `+` and `=` standing for each other. + pub exact: bool, + /// The text of the Paste event that ran the command ([`Dispatcher::with_clipboard_events`]). + pub pasted: Option, } impl Hit { - fn from_lookup(lookup: Lookup) -> Option { - match lookup { - Lookup::None => None, - Lookup::Run(command) => Some(Hit { command, cycle: Vec::new() }), - Lookup::Cycle(cycle) => Some(Hit { command: cycle.first()?.clone(), cycle }), - } + fn from_lookup(lookup: Lookup, trigger: Trigger, exact: bool) -> Option { + let (command, cycle) = match lookup { + Lookup::None => return None, + Lookup::Run(command) => (command, Vec::new()), + Lookup::Cycle(cycle) => (cycle.first()?.clone(), cycle), + }; + Some(Hit { command, cycle, trigger, exact, pasted: None }) } } @@ -167,10 +176,16 @@ struct LastPress { /// Runs a keymap against egui's input, one call per frame before the UI reads its keys. /// -/// It reads key presses (repeats only when [`with_repeat`](Self::with_repeat) is on) and egui's -/// Copy, Cut and Paste events, which egui-winit sends in place of the Cmd+C, Cmd+X and Cmd+V -/// presses. A press that runs a command is removed from the events, together with the text it -/// typed when it has no command modifier, so no widget sees it too. Other events stay. +/// It reads key presses (repeats only when [`with_repeat`](Self::with_repeat) is on). A press +/// that runs a command is removed from the events, together with the text it typed when it has +/// no command modifier, so no widget sees it too. Other events stay. +/// +/// egui's Copy, Cut and Paste events stay with the app unless +/// [`with_clipboard_events`](Self::with_clipboard_events) is on. On the desktop, egui-winit sends +/// these events in place of the key presses for Cmd+C, Cmd+X and Cmd+V (Ctrl off macOS, plus +/// Shift+Delete, Ctrl+Insert and Shift+Insert on Windows), so bindings on those chords run only +/// with clipboard events on. The web build sends the key press and then the clipboard event; with +/// clipboard events off, such a press stays too. /// /// While [`Active::typing`], the text field keeps, without lookup: /// - clipboard events, and the clipboard key presses the web build sends with them (Cmd+C, Cmd+X, @@ -185,6 +200,7 @@ struct LastPress { pub struct Dispatcher { last: Option, repeat: bool, + clipboard: bool, } impl Dispatcher { @@ -199,11 +215,29 @@ impl Dispatcher { self } + /// Whether egui's Copy, Cut and Paste events count as the chords that cause them (Cmd+C, + /// Cmd+X, Cmd+V; Shift+Delete and Shift+Insert for Cut and Paste with Shift alone) outside text + /// fields. Off by default: the events stay in egui's input for the app's own handlers. With it + /// on, an event that runs a command is removed, and a Paste event's text moves to + /// [`Hit::pasted`]. An app that asks egui for a paste (`ViewportCommand::RequestPaste`) to run + /// its paste command gets a Paste event back, which with this on runs that command again. + pub fn with_clipboard_events(mut self, on: bool) -> Dispatcher { + self.clipboard = on; + self + } + /// The commands this frame's key presses run with `active` focus, in press order. /// /// A chord pressed again within [`DOUBLE_PRESS`] runs its double binding when it has one; /// the first press has already run the single binding. The press after a double starts over. pub fn dispatch(&mut self, input: &mut InputState, keymap: &Keymap, active: &Active) -> Vec { + self.dispatch_filtered(input, keymap, active, |_| true) + } + + /// [`dispatch`](Self::dispatch), with `accept` deciding each hit before its event is removed. + /// A declined hit is left out of the result and its event, with any text it typed, stays in + /// egui's input in its place. A declined press still counts toward a double press. + pub fn dispatch_filtered(&mut self, input: &mut InputState, keymap: &Keymap, active: &Active, mut accept: impl FnMut(&Hit) -> bool) -> Vec { let platform = keymap.platform(); let now = input.time; let frame_mods = Mods::from_egui(&input.modifiers, platform); @@ -211,24 +245,31 @@ impl Dispatcher { let mut kept = Vec::with_capacity(input.events.len()); // The Text event egui sends after a key press belongs to that press. let mut drop_text = false; - // The web build sends both the Cmd+C key press and the Copy event it causes. - let mut clipboard_key = None; + // The web build sends both a clipboard key press and the clipboard event it causes. + let mut clipboard_press = None; let events = std::mem::take(&mut input.events); let typed = if active.typing { typed_text(&events) } else { Vec::new() }; + let causes_event = if self.clipboard { Vec::new() } else { clipboard_event_follows(&events, platform) }; for (i, event) in events.into_iter().enumerate() { match &event { Event::Key { key, pressed: true, repeat, modifiers, .. } if !*repeat || self.repeat => { drop_text = false; let held = Mods::from_egui(modifiers, platform); if let Some(key) = Key::from_egui(*key) { - if active.typing && (typed.get(i) == Some(&true) || is_clipboard_press(key, held) || may_be_alt_gr(key, held, platform)) { + let clip = clipboard_kind(key, held); + let keep = if active.typing { + typed.get(i) == Some(&true) || clip.is_some() || may_be_alt_gr(key, held, platform) + } else { + causes_event.get(i) == Some(&true) + }; + if keep { kept.push(event); continue; } - if held.cmd && matches!(key, Key::C | Key::X | Key::V) { - clipboard_key = Some(key); + if clip.is_some() { + clipboard_press = clip; } - if let Some(hit) = self.press(key, held, *repeat, now, keymap, active) { + if let Some(hit) = self.press(key, held, *repeat, now, keymap, active).filter(&mut accept) { hits.push(hit); drop_text = !(held.cmd || held.ctrl); continue; @@ -240,13 +281,18 @@ impl Dispatcher { continue; } // A focused text field copies and pastes on these events itself. - Event::Copy | Event::Cut | Event::Paste(_) if !active.typing => { - let (key, held) = clipboard_chord(&event, frame_mods); - if clipboard_key == Some(key) { - clipboard_key = None; - } else if let Some(hit) = self.press(key, held, false, now, keymap, active) { - hits.push(hit); - continue; + Event::Copy | Event::Cut | Event::Paste(_) if self.clipboard && !active.typing => { + let (key, held, clip) = clipboard_chord(&event, frame_mods); + if clipboard_press == Some(clip) { + clipboard_press = None; + } else if let Some(mut hit) = self.press(key, held, false, now, keymap, active) { + if let Event::Paste(text) = &event { + hit.pasted = Some(text.clone()); + } + if accept(&hit) { + hits.push(hit); + continue; + } } } _ => {} @@ -260,7 +306,10 @@ impl Dispatcher { fn press(&mut self, key: Key, held: Mods, repeat: bool, now: f64, keymap: &Keymap, active: &Active) -> Option { let chords = candidates(key, held, keymap.platform()); let first = *chords.first()?; - let find = |double: bool| chords.iter().find_map(|c| Hit::from_lookup(keymap.lookup(c, double, active))); + let pressed = Chord::new(held, key); + let find = |double: bool| { + chords.iter().find_map(|&chord| Hit::from_lookup(keymap.lookup(&chord, double, active), Trigger { chord, double }, chord == pressed)) + }; if repeat { return find(false); } @@ -271,6 +320,33 @@ impl Dispatcher { } } +/// A clipboard event: Copy, Cut or Paste. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Clip { + Copy, + Cut, + Paste, +} + +/// For each event, whether it is a clipboard key press whose clipboard event comes later in the +/// frame, as the web build sends them. +fn clipboard_event_follows(events: &[Event], platform: Platform) -> Vec { + let mut out = vec![false; events.len()]; + let mut ahead = [false; 3]; + for (event, follows) in events.iter().zip(out.iter_mut()).rev() { + if let Some(seen) = event_clip(event).and_then(|c| ahead.get_mut(c as usize)) { + *seen = true; + } else if let Event::Key { key, pressed: true, modifiers, .. } = event { + let clip = Key::from_egui(*key).and_then(|k| clipboard_kind(k, Mods::from_egui(modifiers, platform))); + if let Some(seen) = clip.and_then(|c| ahead.get_mut(c as usize)) { + *follows = *seen; + *seen = false; + } + } + } + out +} + /// For each event, whether it is a key press followed by a Text event before the next press. fn typed_text(events: &[Event]) -> Vec { let mut out = vec![false; events.len()]; @@ -315,26 +391,38 @@ fn types_text(key: Key) -> bool { ) } -/// Whether a press is one a backend turns into a Copy, Cut or Paste event. -fn is_clipboard_press(key: Key, held: Mods) -> bool { - match key { - Key::C | Key::X | Key::V => held.cmd, - Key::Delete => held.shift, - Key::Insert => held.shift || held.cmd || held.ctrl, - _ => false, +fn event_clip(event: &Event) -> Option { + match event { + Event::Copy => Some(Clip::Copy), + Event::Cut => Some(Clip::Cut), + Event::Paste(_) => Some(Clip::Paste), + _ => None, } } -/// The press a clipboard event stands for, with the modifiers held. Off macOS egui-winit also -/// sends Cut for Shift+Delete and Paste for Shift+Insert. -fn clipboard_chord(event: &Event, held: Mods) -> (Key, Mods) { +/// The clipboard event a backend sends for a press, if any. +fn clipboard_kind(key: Key, held: Mods) -> Option { + match key { + Key::C if held.cmd => Some(Clip::Copy), + Key::X if held.cmd => Some(Clip::Cut), + Key::V if held.cmd => Some(Clip::Paste), + Key::Delete if held.shift => Some(Clip::Cut), + Key::Insert if held.shift => Some(Clip::Paste), + Key::Insert if held.cmd || held.ctrl => Some(Clip::Copy), + _ => None, + } +} + +/// The press a clipboard event stands for, with the modifiers held, and the event's kind. Off +/// macOS egui-winit also sends Cut for Shift+Delete and Paste for Shift+Insert. +fn clipboard_chord(event: &Event, held: Mods) -> (Key, Mods, Clip) { let with_cmd = Mods { cmd: true, ..held }; let shift_only = held.shift && !held.cmd; match event { - Event::Cut if shift_only => (Key::Delete, held), - Event::Cut => (Key::X, with_cmd), - Event::Paste(_) if shift_only => (Key::Insert, held), - Event::Paste(_) => (Key::V, with_cmd), - _ => (Key::C, with_cmd), + Event::Cut if shift_only => (Key::Delete, held, Clip::Cut), + Event::Cut => (Key::X, with_cmd, Clip::Cut), + Event::Paste(_) if shift_only => (Key::Insert, held, Clip::Paste), + Event::Paste(_) => (Key::V, with_cmd, Clip::Paste), + _ => (Key::C, with_cmd, Clip::Copy), } } diff --git a/crates/keymap/tests/egui.rs b/crates/keymap/tests/egui.rs index 7e275abab..23db9756c 100644 --- a/crates/keymap/tests/egui.rs +++ b/crates/keymap/tests/egui.rs @@ -1,7 +1,7 @@ #![cfg(feature = "egui")] use craft_keymap::egui::{Dispatcher, Hit, matches}; -use craft_keymap::{Active, Bindable, Binding, Chord, CommandRef, Key, Keymap, Kind, Mods, Platform, Scope, Scopes}; +use craft_keymap::{Active, Bindable, Binding, Chord, CommandRef, Key, Keymap, Kind, Mods, Platform, Scope, Scopes, Trigger}; use egui::{Event, InputState, Key as EguiKey, Modifiers}; fn chord(text: &str) -> Chord { @@ -71,6 +71,7 @@ fn dispatch_keymap() -> Keymap { let tool = |id: &str| app(id, &["M"]).with_kind(Kind::Tool { group: Some("select".into()) }); let catalogue = vec![ app("edit.copy", &["Cmd+C", "Cmd+Insert"]), + app("edit.paste", &["Cmd+V", "Shift+Insert"]), app("app.quit", &["Cmd+Alt+Q"]), app("view.refresh", &["Cmd+Alt+F5"]), app("file.save", &["Cmd+S"]), @@ -139,21 +140,74 @@ fn shifted_symbols_and_zoom_keys_reach_their_bindings() { } #[test] -fn clipboard_events_run_their_chords_outside_text_fields() { +fn clipboard_events_stay_with_the_app_by_default() { let km = dispatch_keymap(); let mut d = Dispatcher::new(); - let (ran, left) = run(&mut d, &km, &Active::NONE, frame(1.0, CTRL, vec![Event::Copy])); + // egui-winit sends these in place of the Ctrl+C and Ctrl+V presses. + let events = vec![Event::Copy, Event::Paste("text".into())]; + let (ran, left) = run(&mut d, &km, &Active::NONE, frame(1.0, CTRL, events.clone())); + assert!(ran.is_empty(), "{ran:?}"); + assert_eq!(left, events); + // The web build sends the press and then the event: both stay. + let events = vec![press(EguiKey::C, CTRL), Event::Copy, press(EguiKey::S, CTRL)]; + let (ran, left) = run(&mut d, &km, &Active::NONE, frame(2.0, CTRL, events.clone())); + assert_eq!(ran, ["file.save"]); + assert_eq!(left, events[..2]); + // A clipboard press with no clipboard event after it is an ordinary press. + let (ran, _) = run(&mut d, &km, &Active::NONE, frame(3.0, CTRL, vec![press(EguiKey::Insert, CTRL)])); assert_eq!(ran, ["edit.copy"]); - assert!(left.is_empty()); +} + +#[test] +fn clipboard_events_run_their_chords_outside_text_fields_when_turned_on() { + let km = dispatch_keymap(); + let mut d = Dispatcher::new().with_clipboard_events(true); + let mut input = frame(1.0, CTRL, vec![Event::Copy, Event::Paste("text".into())]); + let hits = d.dispatch(&mut input, &km, &Active::NONE); + let ran: Vec<_> = hits.iter().map(|h| (h.command.id.as_str(), h.pasted.as_deref())).collect(); + assert_eq!(ran, [("edit.copy", None), ("edit.paste", Some("text"))]); + assert!(input.events.is_empty()); let typing = Active { typing: true, ..Active::NONE }; let (ran, left) = run(&mut d, &km, &typing, frame(2.0, CTRL, vec![Event::Copy])); assert!(ran.is_empty()); assert_eq!(left, [Event::Copy]); - // The web build sends the key press and the Copy event it causes: one copy. - let (ran, _) = run(&mut d, &km, &Active::NONE, frame(3.0, CTRL, vec![press(EguiKey::C, CTRL), Event::Copy])); - assert_eq!(ran, ["edit.copy"]); + // The web build sends the key press and the clipboard event it causes: one run each. + for (time, key, mods, event, id) in [ + (3.0, EguiKey::C, CTRL, Event::Copy, "edit.copy"), + (4.0, EguiKey::Insert, CTRL, Event::Copy, "edit.copy"), + (5.0, EguiKey::Insert, Modifiers::SHIFT, Event::Paste("text".into()), "edit.paste"), + ] { + let (ran, _) = run(&mut d, &km, &Active::NONE, frame(time, mods, vec![press(key, mods), event])); + assert_eq!(ran, [id], "{key:?}"); + } +} + +#[test] +fn declined_hits_leave_their_events_in_order() { + let km = dispatch_keymap(); + let mut d = Dispatcher::new(); + let shift = Modifiers::SHIFT; + let events = vec![ + press(EguiKey::B, Modifiers::NONE), + Event::Text("b".into()), + press(EguiKey::S, CTRL), + press(EguiKey::Colon, shift), + Event::Text(":".into()), + press(EguiKey::Equals, Modifiers::NONE), + ]; + let mut input = frame(1.0, Modifiers::NONE, events.clone()); + let mut seen = Vec::new(); + let hits = d.dispatch_filtered(&mut input, &km, &Active::NONE, |hit| { + seen.push((hit.command.id.clone(), hit.trigger.chord.to_string(), hit.exact)); + hit.command.id != "file.save" && hit.command.id != "tool.brush" + }); + let s = |id: &str, chord: &str, exact| (id.to_string(), chord.to_string(), exact); + assert_eq!(seen, [s("tool.brush", "B", true), s("file.save", "Cmd+S", true), s("help.find", "Shift+;", false), s("view.zoomIn", "=", true)]); + let ran: Vec<_> = hits.iter().map(|h| h.command.id.as_str()).collect(); + assert_eq!(ran, ["help.find", "view.zoomIn"]); + assert_eq!(input.events, events[..3], "the declined B keeps its text, and Ctrl+S stays in its place"); } #[test] @@ -234,7 +288,8 @@ fn the_focused_panel_wins_and_tool_groups_cycle() { let mut input = frame(2.0, Modifiers::NONE, vec![press(EguiKey::M, Modifiers::NONE)]); let hits = d.dispatch(&mut input, &km, &Active::NONE); let tools = vec![CommandRef::new("tool.marquee"), CommandRef::new("tool.ellipse")]; - assert_eq!(hits, [Hit { command: tools[0].clone(), cycle: tools }]); + let trigger = Trigger::single(chord("M")); + assert_eq!(hits, [Hit { command: tools[0].clone(), cycle: tools, trigger, exact: true, pasted: None }]); } #[test] From 5208562c286fe41a6f702c73170ee27c73924992 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 04:22:49 +0000 Subject: [PATCH 03/32] keymap: store overrides as a map of one text per command when they fit Apps that stored { command: text } before read the field in older builds again. Overrides with several bindings for a command still serialize as the { command, keys } array. keymap::overrides_list always writes the array, for craft-settings files, where only an array lets a reset entry leave the file. --- crates/keymap/README.md | 19 ++++++----- crates/keymap/src/keymap.rs | 1 + crates/keymap/src/keymap/overrides.rs | 45 +++++++++++++++++++++++---- crates/keymap/tests/keymap.rs | 32 +++++++++++++++++++ crates/keymap/tests/settings.rs | 1 + 5 files changed, 85 insertions(+), 13 deletions(-) diff --git a/crates/keymap/README.md b/crates/keymap/README.md index 526d04419..74c72833b 100644 --- a/crates/keymap/README.md +++ b/crates/keymap/README.md @@ -73,13 +73,17 @@ macOS it folds into `cmd` (`Chord::effective`). ## Storing overrides -`Overrides` is a field of the app's craft-settings type. It is stored as an array of -`{ command, keys }` tables (`shortcuts = [{ command = "file.save", keys = ["Cmd+Alt+S"] }]`, or -`[[shortcuts]]` blocks), not as a table keyed by command: craft-settings merges tables key by key -with what the file holds, but replaces an array whole, so a reset command (an entry removed) -stays removed after saving. The map form `{ "" = [keys] }` also loads; there a single -text counts as a one-item list, and `""` means no shortcut, as in apps that store one text per -command. +`Overrides` is a field of the app's settings type. It is stored as a map of one text per command +(`{ "file.save": "Cmd+Alt+S", "edit.copy": "" }`, `""` for no shortcut) while no command has more +than one binding, so apps that stored that map before keep reading it in older builds. Once a +command has several bindings it is stored as an array of `{ command, keys }` tables +(`[{ command = "file.save", keys = ["Cmd+Alt+S", "F12"] }]`). Both forms load, and in the map form +a list of texts loads too. + +In a craft-settings type, put `#[serde(with = "craft_keymap::keymap::overrides_list")]` on the +field, which always writes the array: craft-settings merges tables key by key with what the file +holds but replaces an array whole, so only the array lets a reset command (an entry removed) stay +removed after saving. Hand-written `[[shortcuts]]` blocks load as the array. Texts the keymap cannot use (a key name from a newer version, an unknown scope, a reserved chord) stay in the entry when the command is edited, unless the edit leaves it without bindings. @@ -93,6 +97,7 @@ use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Default, Clone, PartialEq)] #[serde(default)] struct Prefs { + #[serde(with = "craft_keymap::keymap::overrides_list")] shortcuts: Overrides, } diff --git a/crates/keymap/src/keymap.rs b/crates/keymap/src/keymap.rs index 6281868ee..a55f50acb 100644 --- a/crates/keymap/src/keymap.rs +++ b/crates/keymap/src/keymap.rs @@ -12,6 +12,7 @@ use crate::command::{CommandRef, MAX_KEY}; use crate::scope::{Active, Scope, ScopeKind, Scopes}; pub use overrides::Overrides; +pub use overrides::list as overrides_list; /// Most commands a catalogue or an [`Overrides`] holds. pub const MAX_COMMANDS: usize = 4096; diff --git a/crates/keymap/src/keymap/overrides.rs b/crates/keymap/src/keymap/overrides.rs index 914b13e68..518581b54 100644 --- a/crates/keymap/src/keymap/overrides.rs +++ b/crates/keymap/src/keymap/overrides.rs @@ -14,8 +14,10 @@ const MAX_NOTES: usize = 64; /// The user's changes to the default bindings: binding key → the full list of binding texts /// that replaces the command's defaults (`[]` = no shortcut). /// -/// Stored as an array of `{ command, keys }` items in key order, e.g. `[[shortcuts]]` blocks in -/// craft-settings; the map form `{ "": [texts] }` loads too. Loading never fails: +/// Stored in key order as a map of one text per command (`{ "": "Cmd+K" }`, `""` for no +/// shortcut) while no entry has more than one text, and otherwise as an array of +/// `{ command, keys }` items. [`list`] always writes the array, for craft-settings files. Both +/// forms load, and in the map form a list of texts loads too. Loading never fails: /// entries for unknown commands and texts that do not parse are kept verbatim; values that are not /// text, overlong keys and texts, repeated keys (the first entry stays) and entries past the caps /// are dropped, and a value that is neither a list nor a map loads as no overrides. All of these @@ -92,12 +94,43 @@ impl Overrides { } } -// Written as an array of `{ command, keys }` items, not a map: craft-settings merges tables key -// by key and keeps keys a value no longer has, but replaces arrays whole, so a reset entry leaves -// the file only in this form. +// The map form is what apps that store one text per command read, so a file stays readable by +// their older builds while no command has more than one binding. impl Serialize for Overrides { fn serialize(&self, serializer: S) -> Result { - serializer.collect_seq(self.map.iter().map(|(command, keys)| Item { command, keys })) + if self.map.values().all(|keys| single(keys).is_some()) { + serializer.collect_map(self.map.iter().map(|(command, keys)| (command, single(keys).unwrap_or_default()))) + } else { + list::serialize(self, serializer) + } + } +} + +/// An entry's text in the map form: `""` for no shortcut. `None` for several texts, and for one +/// blank text, which the map form reads as no shortcut. +fn single(keys: &[String]) -> Option<&str> { + match keys { + [] => Some(""), + [text] if !text.trim().is_empty() => Some(text.as_str()), + _ => None, + } +} + +/// Serializes [`Overrides`] always as an array of `{ command, keys }` items, for +/// `#[serde(with = "craft_keymap::keymap::overrides_list")]`. craft-settings merges a table key +/// by key with what the file holds but replaces an array whole, so in a craft-settings file only +/// this form lets a reset command (an entry removed) stay removed after saving. +pub mod list { + use serde::{Deserialize, Deserializer, Serializer}; + + use super::{Item, Overrides}; + + pub fn serialize(overrides: &Overrides, serializer: S) -> Result { + serializer.collect_seq(overrides.map.iter().map(|(command, keys)| Item { command, keys })) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + Overrides::deserialize(deserializer) } } diff --git a/crates/keymap/tests/keymap.rs b/crates/keymap/tests/keymap.rs index 2e16997ae..24d2ade81 100644 --- a/crates/keymap/tests/keymap.rs +++ b/crates/keymap/tests/keymap.rs @@ -465,6 +465,38 @@ fn an_empty_text_in_the_map_form_removes_the_shortcut() { assert!(again.bindings(&cmd("edit.copy")).is_empty(), "{saved}"); } +#[test] +fn overrides_write_the_map_form_unless_a_command_has_several_keys() { + let mut o = Overrides::new(); + o.insert("edit.copy", vec!["Cmd+K".into()]); + o.insert("edit.paste", vec![]); + let text = serde_json::to_string(&o).unwrap(); + assert_eq!(text, r#"{"edit.copy":"Cmd+K","edit.paste":""}"#, "older builds read one text per command"); + assert_eq!(serde_json::from_str::(&text).unwrap(), o); + + o.insert("edit.cut", vec!["Cmd+X".into(), "Shift+Delete".into()]); + let text = serde_json::to_string(&o).unwrap(); + assert!(text.starts_with(r#"[{"command":"edit.copy","keys":["Cmd+K"]},"#), "{text}"); + assert_eq!(serde_json::from_str::(&text).unwrap(), o); + + // A blank text is kept verbatim (it loads as the defaults), which the map form cannot say. + let mut blank = Overrides::new(); + blank.insert("edit.copy", vec![" ".into()]); + let text = serde_json::to_string(&blank).unwrap(); + assert!(text.starts_with('['), "{text}"); + assert_eq!(serde_json::from_str::(&text).unwrap(), blank); + + #[derive(serde::Serialize)] + struct Prefs { + #[serde(with = "craft_keymap::keymap::overrides_list")] + shortcuts: Overrides, + } + let mut single = Overrides::new(); + single.insert("edit.copy", vec!["Cmd+K".into()]); + let text = serde_json::to_string(&Prefs { shortcuts: single }).unwrap(); + assert_eq!(text, r#"{"shortcuts":[{"command":"edit.copy","keys":["Cmd+K"]}]}"#); +} + #[test] fn ctrl_folds_into_cmd_off_macos() { let catalogue = vec![app("edit.cut", &["Cmd+X"]), app("mac.cut", &["Ctrl+X"])]; diff --git a/crates/keymap/tests/settings.rs b/crates/keymap/tests/settings.rs index c63c893ba..89c744bd0 100644 --- a/crates/keymap/tests/settings.rs +++ b/crates/keymap/tests/settings.rs @@ -9,6 +9,7 @@ use serde_json::json; #[serde(default)] struct Prefs { general: General, + #[serde(with = "craft_keymap::keymap::overrides_list")] shortcuts: Overrides, } From be51941628f2f3069eac709cf67fa69411cf36a5 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 04:23:26 +0000 Subject: [PATCH 04/32] keymap: add Keymap::conflicts_with and document the edit calls conflicts_with lists the commands that share one command's chords, with that command as a, without filtering every conflict. The README shows set_bindings with one binding for an editor with one shortcut per command; assign adds a binding. --- crates/keymap/README.md | 15 ++++++++++++++- crates/keymap/src/keymap.rs | 26 ++++++++++++++++++++++++++ crates/keymap/tests/keymap.rs | 22 ++++++++++++++++++++++ 3 files changed, 62 insertions(+), 1 deletion(-) diff --git a/crates/keymap/README.md b/crates/keymap/README.md index 74c72833b..4f4e062ea 100644 --- a/crates/keymap/README.md +++ b/crates/keymap/README.md @@ -113,10 +113,23 @@ let mut keymap = Keymap::new(catalogue, Scopes::new(), Platform::current()).with let _problems = keymap.problems(); // After each change in the shortcut editor: -keymap.assign(&"file.save".into(), Binding::parse("Cmd+Alt+S").unwrap(), Policy::Steal).ok(); +keymap.set_bindings(&"file.save".into(), vec![Binding::parse("Cmd+Alt+S").unwrap()], Policy::Steal).ok(); store.update(|p| p.shortcuts = keymap.overrides().clone()); ``` +## Editing + +- `set_bindings(&command, bindings, policy)` replaces a command's bindings. An editor with one + shortcut per command calls it with the one binding (`vec![binding]`); `assign` adds a binding + to those the command has. +- `remove` takes one binding away, `clear` leaves the command without shortcuts, `reset` gives it + its defaults back and `reset_all` does so for every command. +- `Policy` says what happens to other commands holding the chord: `Steal` takes it from them, + `Keep` lets both keep it and reports the clash, `Refuse` changes nothing and returns + `AssignError::Taken`. +- `conflicts()` lists every pair of commands on one chord; `conflicts_with(&command)` lists the + commands that share one command's chords, with that command as `a`. + ## Importing a shortcut set The app's reader turns a file (an InDesign Show Set, an Illustrator `.kys`) into an diff --git a/crates/keymap/src/keymap.rs b/crates/keymap/src/keymap.rs index a55f50acb..e57d7bf10 100644 --- a/crates/keymap/src/keymap.rs +++ b/crates/keymap/src/keymap.rs @@ -594,6 +594,32 @@ impl Keymap { out } + /// The conflicts [`Keymap::conflicts`] reports for one command's bindings, with that command + /// as `a`, in the order of its bindings, then catalogue order. Empty for an unknown command. + pub fn conflicts_with(&self, command: &CommandRef) -> Vec { + let Some(i) = self.find(command) else { return Vec::new() }; + let mut out = Vec::new(); + for a in &self.current[i] { + let chord = a.0.effective(self.platform); + let Some(holders) = self.by_trigger.get(&chord) else { continue }; + for &(j, k) in holders { + if j == i || self.same_group(i, j) { + continue; + } + let Some(b) = self.at(j, k) else { continue }; + let Some(clash) = self.conflict_relation(&a.1, &b.1) else { continue }; + out.push(Conflict { + chord, + a: (self.catalogue[i].command.clone(), self.public(i, a)), + b: (self.catalogue[j].command.clone(), self.public(j, b)), + kind: if clash { ConflictKind::Clash } else { ConflictKind::Shadow }, + in_defaults: self.defaults[i].contains(a) && self.defaults[j].contains(b), + }); + } + } + out + } + /// What is wrong with the stored overrides: load notes, unknown commands, texts that do not /// parse, reserved chords, unknown scopes, duplicate entries. pub fn problems(&self) -> Vec { diff --git a/crates/keymap/tests/keymap.rs b/crates/keymap/tests/keymap.rs index 24d2ade81..558f37ff3 100644 --- a/crates/keymap/tests/keymap.rs +++ b/crates/keymap/tests/keymap.rs @@ -246,6 +246,28 @@ fn conflicts_tell_clashes_from_shadows() { assert!(c("edit.copy", "color.copy") < c("edit.copy", "timeline.copy"), "{order:?}"); assert!(c("edit.copy", "timeline.copy") < c("color.copy", "timeline.copy"), "{order:?}"); + // One command's conflicts, with that command as `a`. + let with = |id: &str| -> Vec<(String, String, ConflictKind)> { + km.conflicts_with(&cmd(id)).into_iter().map(|c| (c.chord.to_string(), c.b.0.id, c.kind)).collect() + }; + let w = |chord: &str, other: &str, kind| (chord.to_string(), other.to_string(), kind); + assert_eq!(with("edit.copy"), [w("Cmd+C", "color.copy", ConflictKind::Clash), w("Cmd+C", "timeline.copy", ConflictKind::Shadow)]); + assert_eq!(with("edit.cut"), [w("Cmd+X", "text.cut", ConflictKind::Shadow), w("Cmd+D", "edit.find", ConflictKind::Clash)]); + assert!(with("nope").is_empty()); + for entry in km.catalogue() { + let id = entry.command.id.as_str(); + let mut direct: Vec<_> = km.conflicts_with(&entry.command).into_iter().map(|c| (c.chord, c.a.0.id, c.b.0.id, c.kind, c.in_defaults)).collect(); + let mut filtered: Vec<_> = km + .conflicts() + .into_iter() + .filter(|c| c.a.0.id == id || c.b.0.id == id) + .map(|c| if c.a.0.id == id { (c.chord, c.a.0.id, c.b.0.id, c.kind, c.in_defaults) } else { (c.chord, c.b.0.id, c.a.0.id, c.kind, c.in_defaults) }) + .collect(); + direct.sort(); + filtered.sort(); + assert_eq!(direct, filtered, "{id}"); + } + let strict = Keymap::new(km.catalogue().to_vec(), scopes().with_panel_fallthrough(false), Platform::Mac); assert!(!strict.conflicts().iter().any(|c| c.chord.to_string() == "Cmd+R")); } From 48c0e1b59d465f8ad6f209f194f310be9c9a5263 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 04:24:19 +0000 Subject: [PATCH 05/32] keymap: drop hand-written key variants when a command gets its defaults reset, and an edit that leaves a command with its defaults, removed only the entry the command read. A variant of its key (window.panel { "panel": "layers" }) stayed and took effect on the next load. Both remove every entry that resolves to the command. --- crates/keymap/src/keymap.rs | 29 +++++++++++++++++++++++------ crates/keymap/tests/keymap.rs | 23 +++++++++++++++++++++++ 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/crates/keymap/src/keymap.rs b/crates/keymap/src/keymap.rs index e57d7bf10..6f3f5dea7 100644 --- a/crates/keymap/src/keymap.rs +++ b/crates/keymap/src/keymap.rs @@ -367,6 +367,9 @@ pub struct Keymap { by_trigger: HashMap>, /// The overrides entry each command reads, when it has one. stored: Vec>, + /// Whether the overrides hold a hand-written variant of a command's key + /// (`window.panel { "panel": "layers" }`); only loading adds them. + variants: bool, /// Home and default scopes of the catalogue. catalogue_scopes: HashSet, scopes: Scopes, @@ -388,6 +391,7 @@ impl Keymap { current: Vec::new(), by_trigger: HashMap::new(), stored: Vec::new(), + variants: false, catalogue_scopes: HashSet::new(), scopes, platform, @@ -560,9 +564,7 @@ impl Keymap { pub fn reset(&mut self, command: &CommandRef) -> bool { let Some(i) = self.find(command) else { return false }; // The whole entry goes, texts this build cannot use included. - if let Some(old) = self.stored[i].take() { - self.overrides.remove(&old); - } + self.remove_entries(i); self.set_current(i, self.defaults[i].clone()); true } @@ -874,9 +876,7 @@ impl Keymap { fn store(&mut self, i: usize, list: Vec) { let mut kept = if list.is_empty() { Vec::new() } else { self.unusable_texts(i) }; kept.truncate(MAX_BINDINGS.saturating_sub(list.len())); - if let Some(old) = self.stored[i].take() { - self.overrides.remove(&old); - } + self.remove_entries(i); if !kept.is_empty() || !self.is_default(i, &list) { let home = &self.catalogue[i].scope; let mut texts: Vec = list.iter().map(|b| self.public(i, b).text(home)).collect(); @@ -888,6 +888,21 @@ impl Keymap { self.set_current(i, list); } + /// Removes a command's overrides entries: the one it reads and hand-written variants of its + /// key, which would take effect on the next load. + fn remove_entries(&mut self, i: usize) { + if let Some(old) = self.stored[i].take() { + self.overrides.remove(&old); + } + if !self.variants { + return; + } + let keys: Vec = self.overrides.iter().map(|(k, _)| k).filter(|k| self.resolve_key(k) == Some(i)).map(str::to_string).collect(); + for key in keys { + self.overrides.remove(&key); + } + } + /// Whether `list` is the command's defaults, comparing effective triggers. fn is_default(&self, i: usize, list: &[Bound]) -> bool { let defaults = &self.defaults[i]; @@ -951,8 +966,10 @@ impl Keymap { entries.sort_by_key(|(k, _)| !self.index.contains_key(*k)); let mut found: Vec<(usize, String, Vec)> = Vec::new(); let mut taken: HashSet = HashSet::new(); + self.variants = false; for (key, texts) in entries { let Some(i) = self.resolve_key(key) else { continue }; + self.variants |= !self.index.contains_key(key); if !taken.insert(i) { continue; } diff --git a/crates/keymap/tests/keymap.rs b/crates/keymap/tests/keymap.rs index 558f37ff3..a8501a796 100644 --- a/crates/keymap/tests/keymap.rs +++ b/crates/keymap/tests/keymap.rs @@ -575,3 +575,26 @@ fn hostile_overrides_load_without_panic_and_report_problems() { assert_eq!(o.load_notes(), [Problem::Dropped { key: String::new(), reason: DropReason::NotAList }], "{text}"); } } + +#[test] +fn reset_removes_hand_written_variants_of_a_key() { + let layers = CommandRef::with_params("window.panel", json!({"panel": "layers"})); + let catalogue = vec![Bindable::new(layers.clone(), "Layers", Scope::app()).with_default(b("F7"))]; + let load = || { + let mut o = Overrides::new(); + o.insert(r#"window.panel {"panel":"layers"}"#, vec!["Cmd+L".into()]); + o.insert(r#"window.panel { "panel": "layers" }"#, vec!["Cmd+K".into()]); + Keymap::new(catalogue.clone(), Scopes::new(), Platform::Mac).with_overrides(o) + }; + let mut km = load(); + assert_eq!(km.bindings(&layers), vec![b("Cmd+L")], "the canonical entry wins"); + km.reset(&layers); + assert!(km.overrides().is_empty(), "{:?}", km.overrides()); + + // Setting the defaults drops the entries too. + let mut km = load(); + km.set_bindings(&layers, vec![b("F7")], Policy::Steal).unwrap(); + assert!(km.overrides().is_empty(), "{:?}", km.overrides()); + let again = Keymap::new(catalogue.clone(), Scopes::new(), Platform::Mac).with_overrides(km.overrides().clone()); + assert_eq!(again.bindings(&layers), vec![b("F7")]); +} From 66f22029ba71dad29dcda156f01f680763aa6659 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 04:25:06 +0000 Subject: [PATCH 06/32] keymap: format the conflicts_with test --- crates/keymap/tests/keymap.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/keymap/tests/keymap.rs b/crates/keymap/tests/keymap.rs index a8501a796..475109d46 100644 --- a/crates/keymap/tests/keymap.rs +++ b/crates/keymap/tests/keymap.rs @@ -256,12 +256,19 @@ fn conflicts_tell_clashes_from_shadows() { assert!(with("nope").is_empty()); for entry in km.catalogue() { let id = entry.command.id.as_str(); - let mut direct: Vec<_> = km.conflicts_with(&entry.command).into_iter().map(|c| (c.chord, c.a.0.id, c.b.0.id, c.kind, c.in_defaults)).collect(); + let mut direct: Vec<_> = + km.conflicts_with(&entry.command).into_iter().map(|c| (c.chord, c.a.0.id, c.b.0.id, c.kind, c.in_defaults)).collect(); let mut filtered: Vec<_> = km .conflicts() .into_iter() .filter(|c| c.a.0.id == id || c.b.0.id == id) - .map(|c| if c.a.0.id == id { (c.chord, c.a.0.id, c.b.0.id, c.kind, c.in_defaults) } else { (c.chord, c.b.0.id, c.a.0.id, c.kind, c.in_defaults) }) + .map(|c| { + if c.a.0.id == id { + (c.chord, c.a.0.id, c.b.0.id, c.kind, c.in_defaults) + } else { + (c.chord, c.b.0.id, c.a.0.id, c.kind, c.in_defaults) + } + }) .collect(); direct.sort(); filtered.sort(); From 6e136c9114d4461e791f0599c4976fc0c01e0048 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 04:34:27 +0000 Subject: [PATCH 07/32] keymap: match panel-menu items, aliases in menus, and Show/Hide only for toggles MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ForeignEntry::in_panel_menu marks an item whose leading segments name a panel (InDesign's "Character: All Caps"); it also matches a catalogue path ending with its segments, then its last segment as a unique label. - Aliases count in the menu steps too, joined segments are tried as a label or alias anywhere, and normalize_label reads a colon as a space, so the alias "Preferences: General…" matches "Edit > Preferences > General...". - A leading Show, Hide or Show/Hide is dropped only for commands marked Bindable::toggle, and only after the names as written found nothing. - Keys in skipped contexts are left out of unmatched rows, so entries with only such keys no longer use up the suggestion cap. --- crates/keymap/README.md | 25 ++++- crates/keymap/src/import.rs | 190 ++++++++++++++++++++++++---------- crates/keymap/src/keymap.rs | 11 ++ crates/keymap/tests/import.rs | 139 ++++++++++++++++++++++++- 4 files changed, 300 insertions(+), 65 deletions(-) diff --git a/crates/keymap/README.md b/crates/keymap/README.md index 4f4e062ea..2027a2f56 100644 --- a/crates/keymap/README.md +++ b/crates/keymap/README.md @@ -164,9 +164,23 @@ assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File ``` - Matching, most specific first, each step needing exactly one command: the user's remembered - answers, the full menu path, the joined submenu segments as a label in that menu, the label in - that menu, the label or an alias anywhere. Labels are compared after `import::normalize_label`. - Tool entries match only tools. + answers, the full menu path, the joined submenu segments as a label or alias in that menu, the + label in that menu, the joined segments as a label or alias anywhere, the label anywhere. An + entry with no menu and several segments matches only by its full path, unless the reader marks + it `in_panel_menu()`. Tool entries match only tools. +- Names are compared after `import::normalize_label`: case, `…`, `...`, `&`, colons and extra + spaces aside, so the alias `Preferences: General…` matches `Edit > Preferences > General...`. + Aliases (`Bindable::with_alias`) count wherever labels do. +- Panel menus: sources list panel-menu items with the panel's name in front (InDesign's Panel + Menus area writes `Character: All Caps`; Illustrator and Photoshop sets have similar areas). + The reader splits the name into segments and marks the entry `ForeignEntry::in_panel_menu()`. + Such an entry also matches a catalogue path that ends with its segments (with the command's + label or the path's last segment last), and its last segment alone as a label. +- Show/Hide: a source often lists one toggle as two items, `Show Rulers` and `Hide Rulers`. Names + are matched as written first. When no step finds a command, the steps run again on commands + marked `Bindable::toggle()`, with a leading `Show `, `Hide ` or `Show/Hide ` dropped from the + entry's label and from the command's label, aliases and path labels. A command not marked as a + toggle never matches through a dropped prefix, so `Hide Conveyor` does not match `Conveyor`. - `ImportOptions.contexts` says what each source context becomes (home scope, another scope, the home scope only without a home entry, or skipped). - The set wins: a chord it gives to a command is taken from commands outside it (except twins @@ -176,8 +190,9 @@ assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File - Keys read approximately (a numeric keypad key bound as the main key) are listed in `approximated`. - With `ImportOptions.suggest`, unmatched entries get fuzzy candidates (`import::namematch`); - they are reported, never applied. Only the first 200 unmatched entries get them, and only the - first 200 characters of a name are compared. + they are reported, never applied. Only the first 200 unmatched entries with keys get them, and + only the first 200 characters of a name are compared. Keys in `ContextRule::Skip` contexts do + not count: an unmatched entry with only such keys counts in `unmatched_without_shortcut`. ## Features diff --git a/crates/keymap/src/import.rs b/crates/keymap/src/import.rs index 2af0ed4a5..958db9e83 100644 --- a/crates/keymap/src/import.rs +++ b/crates/keymap/src/import.rs @@ -26,7 +26,7 @@ pub const MAX_IMPORT_TEXT: usize = 1024; /// Most path segments read per entry; the label (last segment) is always kept. pub const MAX_PATH_SEGMENTS: usize = 32; /// Most unmatched entries [`ImportOptions::suggest`] looks for commands for; the rest are counted -/// in [`ImportReport::truncated`]. +/// in [`ImportReport::truncated`]. Entries without keys get no suggestion and do not count. pub const MAX_SUGGESTIONS: usize = 200; /// A shortcut set as an app's reader found it. @@ -49,6 +49,12 @@ pub struct ForeignEntry { pub line: Option, /// The item selects a tool. pub is_tool: bool, + /// The entry belongs to a panel menu: its leading path segments name the panel, not a + /// submenu of [`ForeignEntry::menu`], which is usually `None`. Sources write such items as + /// `Character: All Caps` (InDesign's Panel Menus area, the panel-menu areas of Illustrator and + /// Photoshop sets); the reader splits them into segments. Such an entry also matches a + /// catalogue path that ends with its path, and its last segment alone. + pub panel_menu: bool, } impl ForeignEntry { @@ -63,6 +69,12 @@ impl ForeignEntry { self } + /// Marks the entry as an item of a panel menu ([`ForeignEntry::panel_menu`]). + pub fn in_panel_menu(mut self) -> ForeignEntry { + self.panel_menu = true; + self + } + /// Adds a key after the others. pub fn with_key(mut self, key: ForeignKey) -> ForeignEntry { self.keys.push(key); @@ -350,7 +362,8 @@ pub struct ImportReport { #[serde(default)] pub failed: Vec, pub unmatched: Vec, - /// Entries without keys that matched no command. + /// Entries that matched no command and have no keys, or keys only in + /// [`ContextRule::Skip`] contexts. pub unmatched_without_shortcut: usize, pub unreadable: Vec, pub approximated: Vec, @@ -360,13 +373,19 @@ pub struct ImportReport { pub truncated: usize, } -/// The matching form of a label or menu name: lower case, no `…`, `...` or `&`, single spaces, -/// and no leading `show/hide `, `show ` or `hide ` when something remains (sources name a toggle -/// by what choosing it does now). +/// The matching form of a label or menu name: lower case, no `…`, `...` or `&`, a colon read as +/// a space (so the alias `Preferences: General…` matches the path `Preferences > General...`), +/// single spaces. pub fn normalize_label(s: &str) -> String { - let s = s.replace('…', "").replace("...", "").replace('&', ""); - let s = s.split_whitespace().collect::>().join(" ").to_lowercase(); - ["show/hide ", "show ", "hide "].iter().find_map(|p| s.strip_prefix(p).filter(|r| !r.is_empty())).map_or_else(|| s.clone(), str::to_string) + let s = s.replace('…', "").replace("...", "").replace('&', "").replace(':', " "); + s.split_whitespace().collect::>().join(" ").to_lowercase() +} + +/// A normalised name without a leading `show/hide `, `show ` or `hide ` when something remains: +/// sources name a toggle by what choosing it does now. Only toggle commands +/// ([`Bindable::is_toggle`]) are matched by this form. +fn toggle_name(s: &str) -> String { + ["show/hide ", "show ", "hide "].iter().find_map(|p| s.strip_prefix(p).filter(|r| !r.is_empty())).unwrap_or(s).to_string() } /// Matches `set` to the keymap's commands. Pure: the keymap is not changed. @@ -380,12 +399,25 @@ pub fn plan(set: &ForeignSet, keymap: &Keymap, options: &ImportOptions) -> Impor let mut planned_at: HashMap = HashMap::new(); let mut to_suggest: Vec = Vec::new(); + let rule_of = |k: &ForeignKey| -> Option<&ContextRule> { + match &k.context { + None => Some(&ContextRule::Home), + Some(c) => { + let c = c.to_lowercase(); + contexts.iter().find(|(n, _)| *n == c).map(|(_, r)| *r) + } + } + }; + for (order, raw) in set.entries.iter().take(MAX_IMPORT_ENTRIES).enumerate() { let entry = capped(raw, &mut cut); let item = entry.item(); let found = index.find(&entry, entry.is_tool, &options.remembered); let Found::One(i) = found else { - if entry.keys.is_empty() { + // Keys in skipped contexts would bind nothing, so they neither make a row nor count + // toward the suggestion cap. + let keys: Vec<&ForeignKey> = entry.keys.iter().filter(|k| rule_of(k) != Some(&ContextRule::Skip)).collect(); + if keys.is_empty() { report.unmatched_without_shortcut += 1; continue; } @@ -402,19 +434,10 @@ pub fn plan(set: &ForeignSet, keymap: &Keymap, options: &ImportOptions) -> Impor cut += 1; } } - report.unmatched.push(Unmatched { item, line: entry.line, keys: keys_text(entry.keys.iter()), reason }); + report.unmatched.push(Unmatched { item, line: entry.line, keys: keys_text(keys.into_iter()), reason }); continue; }; - let rule_of = |k: &ForeignKey| -> Option<&ContextRule> { - match &k.context { - None => Some(&ContextRule::Home), - Some(c) => { - let c = c.to_lowercase(); - contexts.iter().find(|(n, _)| *n == c).map(|(_, r)| *r) - } - } - }; let has_home = entry.keys.iter().any(|k| rule_of(k) == Some(&ContextRule::Home)); let mut unlisted = Vec::new(); let mut unreadable = Vec::new(); @@ -700,7 +723,7 @@ fn capped(e: &ForeignEntry, cut: &mut usize) -> ForeignEntry { }), }) .collect(); - ForeignEntry { menu: e.menu.as_deref().map(|m| cap_text(m, cut)), path, keys, line: e.line, is_tool: e.is_tool } + ForeignEntry { menu: e.menu.as_deref().map(|m| cap_text(m, cut)), path, keys, line: e.line, is_tool: e.is_tool, panel_menu: e.panel_menu } } enum Found { @@ -709,14 +732,15 @@ enum Found { None, } -/// The catalogue by normalised path and label, for the match steps. -struct Index { - tool: Vec, - /// Binding keys, for remembered answers. - keys: HashMap, +/// Catalogue names in one form, for the match steps. +#[derive(Default)] +struct Names { /// Normalised paths joined by U+001F. paths: HashMap>, - /// (top menu, label) at any depth of that menu. + /// The last two or more segments of paths, also with the label as the last one, joined by + /// U+001F: for panel-menu entries. + ends: HashMap>, + /// (top menu, label, alias or path label) at any depth of that menu. in_menu: HashMap<(String, String), Vec>, /// Labels, aliases and path labels anywhere. anywhere: HashMap>, @@ -729,26 +753,86 @@ fn add(map: &mut HashMap>, key: K, i: usi } } +impl Names { + /// Adds command `i`, its label, aliases and the last segment of each path passed through `form`. + fn add(&mut self, i: usize, b: &Bindable, form: fn(&str) -> String) { + let label = form(&normalize_label(&b.label)); + let names: Vec = std::iter::once(label.clone()).chain(b.aliases.iter().map(|a| form(&normalize_label(a)))).collect(); + for name in &names { + add(&mut self.anywhere, name.clone(), i); + } + for path in &b.paths { + let mut segs: Vec = path.iter().map(|s| normalize_label(s)).collect(); + if let [_, .., last] = segs.as_mut_slice() { + *last = form(last); + } + add(&mut self.paths, segs.join("\u{1f}"), i); + let Some(top) = segs.first() else { continue }; + for name in &names { + add(&mut self.in_menu, (top.clone(), name.clone()), i); + } + let [_, .., last] = segs.as_slice() else { continue }; + add(&mut self.in_menu, (top.clone(), last.clone()), i); + add(&mut self.anywhere, last.clone(), i); + let mut with_label = segs.clone(); + if let Some(l) = with_label.last_mut() { + *l = label.clone(); + } + for variant in [&segs, &with_label] { + for start in 0..variant.len().saturating_sub(1) { + if let Some(end) = variant.get(start..) { + add(&mut self.ends, end.join("\u{1f}"), i); + } + } + } + } + } + + /// The lists the match steps look up for an entry's normalised menu and path, most specific + /// first. + fn steps(&self, menu: Option<&String>, segs: &[String], panel_menu: bool) -> Vec>> { + let Some(last) = segs.last() else { return Vec::new() }; + let full = menu.into_iter().chain(segs).map(String::as_str).collect::>().join("\u{1f}"); + let mut steps = vec![self.paths.get(&full)]; + let joined = (segs.len() > 1).then(|| segs.join(" ")); + if let Some(m) = menu { + if let Some(j) = &joined { + steps.push(self.in_menu.get(&(m.clone(), j.clone()))); + } + steps.push(self.in_menu.get(&(m.clone(), last.clone()))); + } + if panel_menu && segs.len() > 1 { + steps.push(self.ends.get(&segs.join("\u{1f}"))); + } + if let Some(j) = &joined { + steps.push(self.anywhere.get(j)); + } + if menu.is_some() || segs.len() == 1 || panel_menu { + steps.push(self.anywhere.get(last)); + } + steps + } +} + +/// The catalogue by normalised path and label, for the match steps. +struct Index { + tool: Vec, + /// Binding keys, for remembered answers. + keys: HashMap, + names: Names, + /// Toggle commands by their names without a leading Show/Hide ([`toggle_name`]). + toggles: Names, +} + impl Index { fn new(keymap: &Keymap) -> Index { - let mut ix = Index { tool: Vec::new(), keys: HashMap::new(), paths: HashMap::new(), in_menu: HashMap::new(), anywhere: HashMap::new() }; + let mut ix = Index { tool: Vec::new(), keys: HashMap::new(), names: Names::default(), toggles: Names::default() }; for (i, b) in keymap.catalogue().iter().enumerate() { ix.tool.push(matches!(b.kind, Kind::Tool { .. })); ix.keys.insert(b.command.key(), i); - let label = normalize_label(&b.label); - add(&mut ix.anywhere, label.clone(), i); - for a in &b.aliases { - add(&mut ix.anywhere, normalize_label(a), i); - } - for path in &b.paths { - let segs: Vec = path.iter().map(|s| normalize_label(s)).collect(); - add(&mut ix.paths, segs.join("\u{1f}"), i); - let Some(top) = segs.first() else { continue }; - add(&mut ix.in_menu, (top.clone(), label.clone()), i); - if let [_, .., last] = segs.as_slice() { - add(&mut ix.in_menu, (top.clone(), last.clone()), i); - add(&mut ix.anywhere, last.clone(), i); - } + ix.names.add(i, b, str::to_string); + if b.is_toggle { + ix.toggles.add(i, b, toggle_name); } } ix @@ -763,7 +847,9 @@ impl Index { } } - /// The match steps in order; the first that finds exactly one command decides. + /// The match steps in order; the first that finds exactly one command decides. The steps run + /// on the names as written, then on toggle commands with the entry's label and theirs + /// without a leading Show/Hide. fn find(&self, entry: &ForeignEntry, tool: bool, remembered: &BTreeMap) -> Found { if let Some(c) = remembered.get(&entry.remember_key()) && let Some(&i) = self.keys.get(&c.key()) @@ -772,21 +858,15 @@ impl Index { return Found::One(i); } let segs: Vec = entry.path.iter().map(|s| normalize_label(s)).collect(); - let Some(last) = segs.last() else { return Found::None }; + let mut toggle_segs = segs.clone(); + if let Some(last) = toggle_segs.last_mut() { + *last = toggle_name(last); + } let menu = entry.menu.as_deref().map(normalize_label); - let full = menu.iter().chain(&segs).map(String::as_str).collect::>().join("\u{1f}"); - let mut steps = vec![self.paths.get(&full)]; - if let Some(m) = &menu { - if segs.len() > 1 { - steps.push(self.in_menu.get(&(m.clone(), segs.join(" ")))); - } - steps.push(self.in_menu.get(&(m.clone(), last.clone()))); - } - if menu.is_some() || segs.len() == 1 { - steps.push(self.anywhere.get(last)); - } + let steps = self.names.steps(menu.as_ref(), &segs, entry.panel_menu); + let toggle_steps = self.toggles.steps(menu.as_ref(), &toggle_segs, entry.panel_menu); let mut many = false; - for list in steps { + for list in steps.into_iter().chain(toggle_steps) { match self.pick(list, tool) { Found::One(i) => return Found::One(i), Found::Many => many = true, diff --git a/crates/keymap/src/keymap.rs b/crates/keymap/src/keymap.rs index 6f3f5dea7..d2a81ae98 100644 --- a/crates/keymap/src/keymap.rs +++ b/crates/keymap/src/keymap.rs @@ -146,6 +146,10 @@ pub struct Bindable { pub scope: Scope, #[serde(default)] pub kind: Kind, + /// The command shows and hides something (a panel, guides, rulers). Import matching reads a + /// foreign name without a leading `Show`, `Hide` or `Show/Hide` only for such commands. + #[serde(default)] + pub is_toggle: bool, #[serde(default)] pub defaults: Vec, } @@ -160,10 +164,17 @@ impl Bindable { aliases: Vec::new(), scope, kind: Kind::Command, + is_toggle: false, defaults: Vec::new(), } } + /// Marks the command as showing and hiding something ([`Bindable::is_toggle`]). + pub fn toggle(mut self) -> Bindable { + self.is_toggle = true; + self + } + pub fn with_kind(mut self, kind: Kind) -> Bindable { self.kind = kind; self diff --git a/crates/keymap/tests/import.rs b/crates/keymap/tests/import.rs index 56d17315f..635045ce5 100644 --- a/crates/keymap/tests/import.rs +++ b/crates/keymap/tests/import.rs @@ -49,7 +49,7 @@ fn catalogue() -> Vec { command("app.palette", "Command Palette", &[], &["Cmd+Alt+K"]), command(panel("layers"), "Layers", &["Window", "Layers"], &["F7"]), command(panel("pages"), "Pages", &["Window", "Pages"], &["F12"]), - command("view.guides", "Guides", &["View", "Grids & Guides", "Guides"], &["Cmd+;"]), + command("view.guides", "Guides", &["View", "Grids & Guides", "Guides"], &["Cmd+;"]).toggle(), command("view.goToPage", "Go to Page…", &["View", "Go to Page…"], &["Cmd+J"]), command("view.zoomIn", "Zoom In", &["View", "Zoom In"], &["Cmd+="]), command("object.textFrameOptions", "Text Frame Options…", &["Object", "Text Frame Options…"], &["Cmd+B"]), @@ -143,9 +143,8 @@ fn labels_normalise_for_matching() { assert_eq!(normalize_label("Check Spelling..."), "check spelling"); assert_eq!(normalize_label("Check Spelling…"), "check spelling"); assert_eq!(normalize_label("Grids && Guides"), "grids guides"); - assert_eq!(normalize_label("SHOW/HIDE Guides"), "guides"); - assert_eq!(normalize_label("Show Hidden Characters"), "hidden characters"); - assert_eq!(normalize_label("Hide "), "hide", "nothing left after the prefix"); + assert_eq!(normalize_label("SHOW/HIDE Guides"), "show/hide guides"); + assert_eq!(normalize_label("Preferences: General…"), "preferences general"); assert_eq!(normalize_label("ÄRGER"), "ärger"); } @@ -153,7 +152,7 @@ fn labels_normalise_for_matching() { fn every_match_step_finds_its_command() { let (km, r) = import_windows(); assert_eq!(r.set.as_deref(), Some("My Set")); - // 1: full path, with `&`, case, spacing and Show/Hide normalised. + // 1: full path, with `&`, case and spacing normalised, and Show/Hide dropped for a toggle. has(&km, "view.guides", &["Cmd+Alt+;"]); // 2: joined segments `Text Frame Options` in Object. has(&km, "object.textFrameOptions", &["Cmd+Alt+B"]); @@ -544,3 +543,133 @@ fn report_json_uses_camel_case_names() { assert_eq!(a["approximated"][0]["note"], "numpad"); assert_eq!(v["changed"][0]["from"], json!(["Cmd+W"])); } + +fn import_into(catalogue: Vec, entries: Vec, options: &ImportOptions) -> (Keymap, ImportReport) { + let mut km = Keymap::new(catalogue, Scopes::new(), Platform::Windows); + let report = plan(&ForeignSet { name: None, entries }, &km, options).apply(&mut km); + (km, report) +} + +fn default_context() -> ImportOptions { + ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], ..ImportOptions::default() } +} + +fn unmatched(r: &ImportReport) -> Vec<(&str, UnmatchedReason)> { + r.unmatched.iter().map(|u| (u.item.as_str(), u.reason)).collect() +} + +#[test] +fn panel_menu_entries_match_by_path_end_or_label() { + let catalogue = vec![ + command("type.allCaps", "All Caps", &["Panels", "Character", "All Caps"], &[]), + command("pages.overrideAll", "Override All Parent Items", &["Pages", "Override All Parent Page Items"], &[]), + command("paragraph.justification", "Justification…", &[], &[]), + command("swatches.new", "New Swatch", &["Swatches", "New Swatch"], &[]), + command("gradient.new", "New Swatch", &["Gradient", "New Swatch"], &[]), + command("character.smallCaps", "Small Caps", &[], &[]).with_alias("Character: Small Caps"), + ]; + let d = "Default"; + let panel_entry = |path: &[&str], key: &str| entry(None, path, &[(d, key)], Flavor::Windows).in_panel_menu(); + let entries = vec![ + // The end of a path, label last. + panel_entry(&["Character", "All Caps"], "Ctrl+F1"), + // The end of a path whose last segment differs from the label. + panel_entry(&["Pages", "Override All Parent Page Items"], "Ctrl+F2"), + // The last segment alone, as one command's label. + panel_entry(&["Paragraph", "Justification..."], "Ctrl+F3"), + // The panel picks one of two commands with the label. + panel_entry(&["Swatches", "New Swatch"], "Ctrl+F4"), + // The joined segments as an alias. + panel_entry(&["Character", "Small Caps"], "Ctrl+F5"), + // No path end fits and the label alone fits two commands. + panel_entry(&["Color", "New Swatch"], "Ctrl+F6"), + // Without the mark, a path with no menu matches only a whole catalogue path. + entry(None, &["Character", "All Caps"], &[(d, "Ctrl+F7")], Flavor::Windows), + ]; + let (km, r) = import_into(catalogue, entries, &default_context()); + has(&km, "type.allCaps", &["Cmd+F1"]); + has(&km, "pages.overrideAll", &["Cmd+F2"]); + has(&km, "paragraph.justification", &["Cmd+F3"]); + has(&km, "swatches.new", &["Cmd+F4"]); + has(&km, "character.smallCaps", &["Cmd+F5"]); + has(&km, "gradient.new", &[]); + assert_eq!(unmatched(&r), [("Color > New Swatch", UnmatchedReason::Ambiguous), ("Character > All Caps", UnmatchedReason::NoMatch)]); +} + +#[test] +fn aliases_match_like_labels() { + let catalogue = vec![ + command("app.quit", "Quit DesignCraft", &["File", "Quit DesignCraft"], &[]).with_alias("Exit"), + command("app.preferences", "Preferences…", &["Edit", "Preferences…"], &[]).with_alias("Preferences: General…"), + command("type.bold", "Bold", &["Type", "Style", "Bold"], &[]).with_alias("Apply bold"), + command("edit.paste", "Paste", &["Edit", "Paste"], &[]).with_alias("Einfügen"), + ]; + let d = "Default"; + let entries = vec![ + win("File", &["Exit"], &[(d, "Ctrl+Q")]), + win("Edit", &["Preferences", "General..."], &[(d, "Ctrl+K")]), + entry(None, &["Apply Bold"], &[(d, "Ctrl+Shift+B")], Flavor::Windows), + win("Bearbeiten", &["Einfügen"], &[(d, "Ctrl+Shift+V")]), + ]; + let (km, r) = import_into(catalogue, entries, &default_context()); + has(&km, "app.quit", &["Cmd+Q"]); + has(&km, "app.preferences", &["Cmd+K"]); + has(&km, "type.bold", &["Cmd+Shift+B"]); + has(&km, "edit.paste", &["Cmd+Shift+V"]); + assert!(r.unmatched.is_empty(), "{:?}", r.unmatched); +} + +#[test] +fn show_and_hide_are_read_off_only_for_toggles() { + let catalogue = vec![ + command(panel("conveyor"), "Conveyor", &["Window", "Conveyor"], &[]), + command("view.rulers", "Rulers", &["View", "Rulers"], &[]).toggle(), + command("view.frameEdges", "Show Frame Edges", &["View", "Extras", "Show Frame Edges"], &[]).toggle(), + command("view.hiddenCharacters", "Show Hidden Characters", &["Type", "Show Hidden Characters"], &[]), + ]; + let d = "Default"; + let entries = vec![ + // Not a toggle: the name must fit as written. + win("View", &["Extras", "Hide Conveyor"], &[(d, "Ctrl+F1")]), + // One toggle for both of the source's items. + win("View", &["Show Rulers"], &[(d, "Ctrl+R")]), + win("View", &["Hide Rulers"], &[(d, "Ctrl+Shift+R")]), + win("View", &["Extras", "Hide Frame Edges"], &[(d, "Ctrl+H")]), + // Exact names match any command. + win("Type", &["Show Hidden Characters"], &[(d, "Ctrl+Alt+I")]), + win("Type", &["Hide Hidden Characters"], &[(d, "Ctrl+Alt+H")]), + ]; + let (km, r) = import_into(catalogue, entries, &default_context()); + has(&km, panel("conveyor"), &[]); + has(&km, "view.rulers", &["Cmd+R", "Cmd+Shift+R"]); + has(&km, "view.frameEdges", &["Cmd+H"]); + has(&km, "view.hiddenCharacters", &["Cmd+Alt+I"]); + assert_eq!( + unmatched(&r), + [("View > Extras > Hide Conveyor", UnmatchedReason::NoMatch), ("Type > Hide Hidden Characters", UnmatchedReason::NoMatch)] + ); +} + +#[test] +fn only_entries_with_keys_to_bind_count_toward_suggestions() { + let catalogue = vec![command("edit.checkSpelling", "Check Spelling…", &["Edit", "Check Spelling…"], &[])]; + let d = "Default"; + // Twice the cap of unmatched entries without keys, or with keys only in a skipped context, + // before one with a key. + let mut entries: Vec = (0..MAX_SUGGESTIONS) + .flat_map(|i| [win("Edit", &[&format!("Nothing {i}")], &[]), win("Edit", &[&format!("Tables {i}")], &[("Table", "Ctrl+T")])]) + .collect(); + entries.push(win("Edit", &["Chek Spelling Now"], &[(d, "Ctrl+K"), ("Table", "Ctrl+T")])); + let options = ImportOptions { + contexts: vec![(d.into(), ContextRule::Home), ("Table".into(), ContextRule::Skip)], + suggest: true, + ..ImportOptions::default() + }; + let (_, r) = import_into(catalogue, entries, &options); + assert_eq!(r.unmatched_without_shortcut, 2 * MAX_SUGGESTIONS); + assert_eq!(r.unmatched.len(), 1); + assert_eq!(r.unmatched[0].keys, "Default: Ctrl+K", "keys in a skipped context are left out"); + assert_eq!(r.suggestions.len(), 1); + assert_eq!(r.suggestions[0].candidates, [CommandRef::new("edit.checkSpelling")]); + assert_eq!(r.truncated, 0); +} From 1e4ab21708793dbe66ff7e1cfc5b5094c3c9a305 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 04:45:45 +0000 Subject: [PATCH 08/32] keymap: keep panel-menu entries without keys from clearing commands The last segment of a panel-menu entry matches alone only when the panel name is a segment of some catalogue path. An entry without keys matched only as a panel-menu item leaves the command's shortcuts alone and is listed in ImportReport::matched_without_change. Tests cover an entry without keys next to one with keys for the same command, in both orders. --- crates/keymap/README.md | 9 +++- crates/keymap/src/import.rs | 96 ++++++++++++++++++++++++++--------- crates/keymap/tests/import.rs | 89 ++++++++++++++++++++++++++++++-- 3 files changed, 163 insertions(+), 31 deletions(-) diff --git a/crates/keymap/README.md b/crates/keymap/README.md index 2027a2f56..81b55ec95 100644 --- a/crates/keymap/README.md +++ b/crates/keymap/README.md @@ -175,7 +175,11 @@ assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File Menus area writes `Character: All Caps`; Illustrator and Photoshop sets have similar areas). The reader splits the name into segments and marks the entry `ForeignEntry::in_panel_menu()`. Such an entry also matches a catalogue path that ends with its segments (with the command's - label or the path's last segment last), and its last segment alone as a label. + label or the path's last segment last), and its last segment alone as a label. The last + segment alone counts only when the first segment, the panel, is a segment of some catalogue + path, so `History: New Document` matches nothing in an app without a History panel. An entry + without keys that matched only these ways leaves the command's shortcuts alone and is listed + in `matched_without_change` (reason `PanelMenu`). - Show/Hide: a source often lists one toggle as two items, `Show Rulers` and `Hide Rulers`. Names are matched as written first. When no step finds a command, the steps run again on commands marked `Bindable::toggle()`, with a leading `Show `, `Hide ` or `Show/Hide ` dropped from the @@ -186,7 +190,8 @@ assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File - The set wins: a chord it gives to a command is taken from commands outside it (except twins sharing it as a default), a later entry takes a chord from an earlier one (as when the entries are applied in file order; the earlier key is listed in `skipped`), and an entry without keys - can clear its command. + can clear its command. It clears it only when no entry matched to the same command has keys, + whatever the order of the entries. - Keys read approximately (a numeric keypad key bound as the main key) are listed in `approximated`. - With `ImportOptions.suggest`, unmatched entries get fuzzy candidates (`import::namematch`); diff --git a/crates/keymap/src/import.rs b/crates/keymap/src/import.rs index 958db9e83..4a3ff1380 100644 --- a/crates/keymap/src/import.rs +++ b/crates/keymap/src/import.rs @@ -53,7 +53,9 @@ pub struct ForeignEntry { /// submenu of [`ForeignEntry::menu`], which is usually `None`. Sources write such items as /// `Character: All Caps` (InDesign's Panel Menus area, the panel-menu areas of Illustrator and /// Photoshop sets); the reader splits them into segments. Such an entry also matches a - /// catalogue path that ends with its path, and its last segment alone. + /// catalogue path that ends with its path, and its last segment alone when its first segment + /// is a segment of some catalogue path. Without keys, an entry matched only these ways + /// changes nothing ([`ImportReport::matched_without_change`]). pub panel_menu: bool, } @@ -153,7 +155,8 @@ pub enum Start { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum NoneDefined { - /// The command loses its shortcuts. + /// The command loses its shortcuts, unless another entry matched to it has keys or the entry + /// matched only through a panel-menu rule ([`NoChangeReason::PanelMenu`]). #[default] Clear, /// The command keeps its shortcuts. @@ -195,7 +198,8 @@ pub struct Planned { pub item: String, pub line: Option, pub bindings: Vec, - /// Every matched entry had no keys. + /// Every matched entry had no keys, so [`NoneDefined::Clear`] clears the command. One entry + /// with keys, in any order, keeps an entry without keys from clearing them. pub none_defined: bool, } @@ -210,7 +214,8 @@ pub struct ImportPlan { pub commands: Vec, pub start: Start, pub none_defined: NoneDefined, - /// `unmatched`, `unreadable`, `approximated`, `suggestions` and the counts; + /// `unmatched`, `unreadable`, `approximated`, `suggestions`, `matched_without_change` and the + /// counts; /// [`ImportPlan::apply`] adds the rest. pub report: ImportReport, } @@ -327,6 +332,27 @@ pub struct Unreadable { pub reason: ForeignError, } +/// An entry without keys that matched a command and left its shortcuts alone. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MatchedWithoutChange { + pub command: CommandRef, + pub label: String, + pub item: String, + pub line: Option, + pub reason: NoChangeReason, +} + +/// Why a [`MatchedWithoutChange`] entry did not clear its command. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum NoChangeReason { + /// The entry matched only through a panel-menu rule (a catalogue path ending with its + /// segments, or its last segment alone). Such a match is close enough to bind the entry's + /// keys, not to take a command's shortcuts away. + PanelMenu, +} + /// Likely commands for an unmatched entry, best first. Never applied. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -361,6 +387,9 @@ pub struct ImportReport { pub skipped: Vec, #[serde(default)] pub failed: Vec, + /// Entries without keys that matched a command and changed nothing. + #[serde(default)] + pub matched_without_change: Vec, pub unmatched: Vec, /// Entries that matched no command and have no keys, or keys only in /// [`ContextRule::Skip`] contexts. @@ -413,7 +442,7 @@ pub fn plan(set: &ForeignSet, keymap: &Keymap, options: &ImportOptions) -> Impor let entry = capped(raw, &mut cut); let item = entry.item(); let found = index.find(&entry, entry.is_tool, &options.remembered); - let Found::One(i) = found else { + let Found::One(i, by_panel) = found else { // Keys in skipped contexts would bind nothing, so they neither make a row nor count // toward the suggestion cap. let keys: Vec<&ForeignKey> = entry.keys.iter().filter(|k| rule_of(k) != Some(&ContextRule::Skip)).collect(); @@ -423,7 +452,7 @@ pub fn plan(set: &ForeignSet, keymap: &Keymap, options: &ImportOptions) -> Impor } let reason = match found { Found::Many => UnmatchedReason::Ambiguous, - _ if matches!(index.find(&entry, !entry.is_tool, &BTreeMap::new()), Found::One(_)) => UnmatchedReason::Tool, + _ if matches!(index.find(&entry, !entry.is_tool, &BTreeMap::new()), Found::One(..)) => UnmatchedReason::Tool, _ => UnmatchedReason::NoMatch, }; if options.suggest && reason != UnmatchedReason::Tool { @@ -438,6 +467,13 @@ pub fn plan(set: &ForeignSet, keymap: &Keymap, options: &ImportOptions) -> Impor continue; }; + if by_panel && entry.keys.is_empty() { + let (command, label) = + keymap.catalogue().get(i).map(|b| (b.command.clone(), b.label.clone())).unwrap_or_else(|| (CommandRef::new(""), String::new())); + report.matched_without_change.push(MatchedWithoutChange { command, label, item, line: entry.line, reason: NoChangeReason::PanelMenu }); + continue; + } + let has_home = entry.keys.iter().any(|k| rule_of(k) == Some(&ContextRule::Home)); let mut unlisted = Vec::new(); let mut unreadable = Vec::new(); @@ -727,7 +763,8 @@ fn capped(e: &ForeignEntry, cut: &mut usize) -> ForeignEntry { } enum Found { - One(usize), + /// The command, and whether only a panel-menu step found it. + One(usize, bool), Many, None, } @@ -789,26 +826,30 @@ impl Names { } /// The lists the match steps look up for an entry's normalised menu and path, most specific - /// first. - fn steps(&self, menu: Option<&String>, segs: &[String], panel_menu: bool) -> Vec>> { + /// first, each with whether it is a panel-menu step. `panel` is `Some(known)` for a panel-menu + /// entry, `known` saying whether the catalogue has its panel; only then does its last segment + /// alone match. + fn steps(&self, menu: Option<&String>, segs: &[String], panel: Option) -> Vec<(Option<&Vec>, bool)> { let Some(last) = segs.last() else { return Vec::new() }; let full = menu.into_iter().chain(segs).map(String::as_str).collect::>().join("\u{1f}"); - let mut steps = vec![self.paths.get(&full)]; + let mut steps = vec![(self.paths.get(&full), false)]; let joined = (segs.len() > 1).then(|| segs.join(" ")); if let Some(m) = menu { if let Some(j) = &joined { - steps.push(self.in_menu.get(&(m.clone(), j.clone()))); + steps.push((self.in_menu.get(&(m.clone(), j.clone())), false)); } - steps.push(self.in_menu.get(&(m.clone(), last.clone()))); + steps.push((self.in_menu.get(&(m.clone(), last.clone())), false)); } - if panel_menu && segs.len() > 1 { - steps.push(self.ends.get(&segs.join("\u{1f}"))); + if panel.is_some() && segs.len() > 1 { + steps.push((self.ends.get(&segs.join("\u{1f}")), true)); } if let Some(j) = &joined { - steps.push(self.anywhere.get(j)); + steps.push((self.anywhere.get(j), false)); } - if menu.is_some() || segs.len() == 1 || panel_menu { - steps.push(self.anywhere.get(last)); + if menu.is_some() || segs.len() == 1 { + steps.push((self.anywhere.get(last), false)); + } else if panel == Some(true) { + steps.push((self.anywhere.get(last), true)); } steps } @@ -822,15 +863,18 @@ struct Index { names: Names, /// Toggle commands by their names without a leading Show/Hide ([`toggle_name`]). toggles: Names, + /// Every normalised segment of every catalogue path: the panels and menus the app has. + segments: HashSet, } impl Index { fn new(keymap: &Keymap) -> Index { - let mut ix = Index { tool: Vec::new(), keys: HashMap::new(), names: Names::default(), toggles: Names::default() }; + let mut ix = Index { tool: Vec::new(), keys: HashMap::new(), names: Names::default(), toggles: Names::default(), segments: HashSet::new() }; for (i, b) in keymap.catalogue().iter().enumerate() { ix.tool.push(matches!(b.kind, Kind::Tool { .. })); ix.keys.insert(b.command.key(), i); ix.names.add(i, b, str::to_string); + ix.segments.extend(b.paths.iter().flatten().map(|s| normalize_label(s))); if b.is_toggle { ix.toggles.add(i, b, toggle_name); } @@ -841,7 +885,7 @@ impl Index { fn pick(&self, list: Option<&Vec>, tool: bool) -> Found { let mut fits = list.into_iter().flatten().filter(|i| self.tool.get(**i) == Some(&tool)); match (fits.next(), fits.next()) { - (Some(i), None) => Found::One(*i), + (Some(i), None) => Found::One(*i, false), (Some(_), Some(_)) => Found::Many, _ => Found::None, } @@ -849,13 +893,14 @@ impl Index { /// The match steps in order; the first that finds exactly one command decides. The steps run /// on the names as written, then on toggle commands with the entry's label and theirs - /// without a leading Show/Hide. + /// without a leading Show/Hide. A panel-menu entry's last segment alone matches only when + /// its first segment, the panel, is a segment of some catalogue path. fn find(&self, entry: &ForeignEntry, tool: bool, remembered: &BTreeMap) -> Found { if let Some(c) = remembered.get(&entry.remember_key()) && let Some(&i) = self.keys.get(&c.key()) && self.tool.get(i) == Some(&tool) { - return Found::One(i); + return Found::One(i, false); } let segs: Vec = entry.path.iter().map(|s| normalize_label(s)).collect(); let mut toggle_segs = segs.clone(); @@ -863,12 +908,13 @@ impl Index { *last = toggle_name(last); } let menu = entry.menu.as_deref().map(normalize_label); - let steps = self.names.steps(menu.as_ref(), &segs, entry.panel_menu); - let toggle_steps = self.toggles.steps(menu.as_ref(), &toggle_segs, entry.panel_menu); + let panel = entry.panel_menu.then(|| segs.first().is_some_and(|p| self.segments.contains(p))); + let steps = self.names.steps(menu.as_ref(), &segs, panel); + let toggle_steps = self.toggles.steps(menu.as_ref(), &toggle_segs, panel); let mut many = false; - for list in steps.into_iter().chain(toggle_steps) { + for (list, by_panel) in steps.into_iter().chain(toggle_steps) { match self.pick(list, tool) { - Found::One(i) => return Found::One(i), + Found::One(i, _) => return Found::One(i, by_panel), Found::Many => many = true, Found::None => {} } diff --git a/crates/keymap/tests/import.rs b/crates/keymap/tests/import.rs index 635045ce5..a015c9a5d 100644 --- a/crates/keymap/tests/import.rs +++ b/crates/keymap/tests/import.rs @@ -5,8 +5,8 @@ use std::collections::BTreeMap; use craft_keymap::chord::foreign::ReadNote; use craft_keymap::chord::foreign::{Flavor, ForeignError}; use craft_keymap::import::{ - Failed, FailedChange, MAX_IMPORT_ENTRIES, MAX_IMPORT_TEXT, MAX_KEYS_PER_ENTRY, MAX_SUGGESTIONS, SkipReason, Skipped, UnmatchedReason, - normalize_label, + Failed, FailedChange, MAX_IMPORT_ENTRIES, MAX_IMPORT_TEXT, MAX_KEYS_PER_ENTRY, MAX_SUGGESTIONS, NoChangeReason, SkipReason, Skipped, + UnmatchedReason, normalize_label, }; use craft_keymap::{ Bindable, Binding, CommandRef, ContextRule, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportReport, Keymap, Kind, MAX_COMMANDS, @@ -513,6 +513,7 @@ fn report_json_uses_camel_case_names() { "conflictsCleared", "failed", "imported", + "matchedWithoutChange", "set", "skipped", "suggestions", @@ -567,6 +568,9 @@ fn panel_menu_entries_match_by_path_end_or_label() { command("swatches.new", "New Swatch", &["Swatches", "New Swatch"], &[]), command("gradient.new", "New Swatch", &["Gradient", "New Swatch"], &[]), command("character.smallCaps", "Small Caps", &[], &[]).with_alias("Character: Small Caps"), + // The app has Paragraph and Color panels. + command(panel("paragraph"), "Paragraph", &["Window", "Paragraph"], &[]), + command(panel("color"), "Color", &["Window", "Color"], &[]), ]; let d = "Default"; let panel_entry = |path: &[&str], key: &str| entry(None, path, &[(d, key)], Flavor::Windows).in_panel_menu(); @@ -575,8 +579,10 @@ fn panel_menu_entries_match_by_path_end_or_label() { panel_entry(&["Character", "All Caps"], "Ctrl+F1"), // The end of a path whose last segment differs from the label. panel_entry(&["Pages", "Override All Parent Page Items"], "Ctrl+F2"), - // The last segment alone, as one command's label. + // The last segment alone, as one command's label, for a panel the app has. panel_entry(&["Paragraph", "Justification..."], "Ctrl+F3"), + // The last segment alone matches nothing for a panel the app lacks. + panel_entry(&["History", "Justification..."], "Ctrl+F8"), // The panel picks one of two commands with the label. panel_entry(&["Swatches", "New Swatch"], "Ctrl+F4"), // The joined segments as an alias. @@ -593,7 +599,14 @@ fn panel_menu_entries_match_by_path_end_or_label() { has(&km, "swatches.new", &["Cmd+F4"]); has(&km, "character.smallCaps", &["Cmd+F5"]); has(&km, "gradient.new", &[]); - assert_eq!(unmatched(&r), [("Color > New Swatch", UnmatchedReason::Ambiguous), ("Character > All Caps", UnmatchedReason::NoMatch)]); + assert_eq!( + unmatched(&r), + [ + ("History > Justification...", UnmatchedReason::NoMatch), + ("Color > New Swatch", UnmatchedReason::Ambiguous), + ("Character > All Caps", UnmatchedReason::NoMatch) + ] + ); } #[test] @@ -673,3 +686,71 @@ fn only_entries_with_keys_to_bind_count_toward_suggestions() { assert_eq!(r.suggestions[0].candidates, [CommandRef::new("edit.checkSpelling")]); assert_eq!(r.truncated, 0); } + +fn pages_catalogue() -> Vec { + vec![ + command("app.newDocumentDialog", "New Document…", &["File", "New Document…"], &["Cmd+N"]), + command("layout.pages.insert", "Insert Pages…", &["Layout", "Pages", "Insert Pages…"], &["Cmd+Shift+P"]), + command("file.close", "Close", &["File", "Close"], &["Cmd+W"]), + ] +} + +#[test] +fn panel_menu_entries_without_keys_change_nothing() { + let none = |path: &[&str]| ForeignEntry::new(None, path.iter().copied()).in_panel_menu(); + let entries = vec![ + // The app has no History panel, so the last segment alone does not match. + none(&["History", "New Document"]), + // A path end matches, but without keys the command keeps its shortcuts. + none(&["Pages", "Insert Pages..."]), + // The same for the last segment alone, with a panel the app has. + none(&["Pages", "New Document"]), + ]; + let (km, r) = import_into(pages_catalogue(), entries, &default_context()); + has(&km, "app.newDocumentDialog", &["Cmd+N"]); + has(&km, "layout.pages.insert", &["Cmd+Shift+P"]); + assert!(r.changed.is_empty(), "{:?}", r.changed); + assert_eq!(r.unmatched_without_shortcut, 1); + let rows: Vec<(&str, &str, NoChangeReason)> = + r.matched_without_change.iter().map(|m| (m.item.as_str(), m.command.id.as_str(), m.reason)).collect(); + assert_eq!( + rows, + [ + ("Pages > Insert Pages...", "layout.pages.insert", NoChangeReason::PanelMenu), + ("Pages > New Document", "app.newDocumentDialog", NoChangeReason::PanelMenu) + ] + ); + let v = serde_json::to_value(&r).unwrap(); + let mut fields: Vec = v["matchedWithoutChange"][0].as_object().unwrap().keys().cloned().collect(); + fields.sort(); + assert_eq!(fields, ["command", "item", "label", "line", "reason"]); + assert_eq!(v["matchedWithoutChange"][0]["reason"], "panelMenu"); +} + +#[test] +fn an_entry_without_keys_never_clears_keys_another_entry_gives() { + let d = "Default"; + let keyed = || win("Layout", &["Pages", "Insert Pages..."], &[(d, "Ctrl+Alt+P")]); + let keyless = || win("Layout", &["Insert Pages..."], &[]); + for entries in [vec![keyed(), keyless()], vec![keyless(), keyed()]] { + let (km, _) = import_into(pages_catalogue(), entries, &default_context()); + has(&km, "layout.pages.insert", &["Cmd+Alt+P"]); + } + + // A panel-menu entry without keys, and the menu entry with the command's keys. + let entries = vec![ + ForeignEntry::new(None, ["Pages", "Insert Pages..."]).in_panel_menu(), + win("Layout", &["Pages", "Insert Pages..."], &[(d, "Ctrl+Shift+P")]), + ]; + let (km, r) = import_into(pages_catalogue(), entries, &default_context()); + has(&km, "layout.pages.insert", &["Cmd+Shift+P"]); + assert_eq!(r.matched_without_change.len(), 1); + + // The later entry still takes the chord from another command; the entry without keys does + // not clear the command that lost it. + let entries = vec![keyless(), keyed(), win("File", &["Close"], &[(d, "Ctrl+Alt+P")])]; + let (km, r) = import_into(pages_catalogue(), entries, &default_context()); + has(&km, "file.close", &["Cmd+Alt+P"]); + has(&km, "layout.pages.insert", &["Cmd+Shift+P"]); + assert_eq!(r.skipped.iter().map(|s| (s.command.id.as_str(), s.reason)).collect::>(), [("layout.pages.insert", SkipReason::Taken)]); +} From 362eb59fd26b01a5848a0cdf778486479b92e5c2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 11:59:53 +0000 Subject: [PATCH 09/32] keymap: keep an earlier entry's chord when the later entry finds the overrides full --- crates/keymap/src/import.rs | 172 ++++++++++++++++++++-------------- crates/keymap/tests/import.rs | 13 +++ 2 files changed, 115 insertions(+), 70 deletions(-) diff --git a/crates/keymap/src/import.rs b/crates/keymap/src/import.rs index 4a3ff1380..89e4b2f84 100644 --- a/crates/keymap/src/import.rs +++ b/crates/keymap/src/import.rs @@ -547,27 +547,115 @@ impl ImportPlan { /// [`ImportReport::skipped`]. /// /// A change that finds the overrides full is left out and reported in - /// [`ImportReport::failed`]; the others still apply. With [`Start::Defaults`] that cannot - /// happen. + /// [`ImportReport::failed`]; the others still apply, and a chord it would have taken from an + /// earlier entry stays with that entry. With [`Start::Defaults`] that cannot happen. pub fn apply(&self, keymap: &mut Keymap) -> ImportReport { - let mut report = self.report.clone(); let before: Vec> = self.commands.iter().map(|p| keymap.bindings(&p.command)).collect(); // Dropping every entry leaves room for all of them: each catalogue command takes at most one // entry, and the catalogue holds at most `MAX_COMMANDS`. if self.start == Start::Defaults { keymap.reset_all(); } - let home_of = |km: &Keymap, c: &CommandRef| km.bindable(c).map_or_else(Scope::app, |b| b.scope.clone()); + let start = keymap.clone(); + // Commands whose bindings found the overrides full after taking a chord from an earlier + // entry. They are left out of the claims and the plan is applied again, so the earlier + // entry keeps the chord, as when the entries are applied in file order. + let mut dropped: HashMap = HashMap::new(); + 'attempt: loop { + let mut report = self.report.clone(); + let (accepted, displaced) = self.resolve(keymap, &dropped, &mut report); + let home_of = |km: &Keymap, c: &CommandRef| km.bindable(c).map_or_else(Scope::app, |b| b.scope.clone()); + let label_of = |km: &Keymap, c: &CommandRef| km.bindable(c).map(|b| b.label.clone()).unwrap_or_default(); + let mut decided: HashSet = HashSet::new(); + for (c, (p, list)) in self.commands.iter().zip(&accepted).enumerate() { + let failed = + |km: &Keymap, change, shortcuts| Failed { command: p.command.clone(), label: label_of(km, &p.command), change, shortcuts }; + if let Some(f) = dropped.get(&c) { + report.failed.push(f.clone()); + continue; + } + if !list.is_empty() { + let list = in_default_order(keymap, &p.command, list); + if keymap.set_bindings(&p.command, list.clone(), Policy::Keep).is_err() { + let home = home_of(keymap, &p.command); + let f = failed(keymap, FailedChange::Bind, list.iter().map(|b| b.text(&home)).collect()); + if displaced.contains(&c) { + dropped.insert(c, f); + *keymap = start.clone(); + continue 'attempt; + } + report.failed.push(f); + continue; + } + } else if p.none_defined && self.none_defined == NoneDefined::Clear { + if !keymap.clear(&p.command) { + report.failed.push(failed(keymap, FailedChange::Clear, Vec::new())); + continue; + } + } else { + continue; + } + decided.insert(p.command.key()); + } + for (p, list) in self.commands.iter().zip(&accepted) { + if list.is_empty() || !decided.contains(&p.command.key()) { + continue; + } + for h in keymap.clashing(&p.command, list) { + if decided.contains(&h.command.key()) { + continue; + } + let home = home_of(keymap, &h.command); + let label = label_of(keymap, &h.command); + let shortcut = h.binding.text(&home); + if keymap.remove(&h.command, &h.binding) { + report.conflicts_cleared.push(Cleared { command: h.command, label, shortcut }); + } else { + report.failed.push(Failed { command: h.command, label, change: FailedChange::Unbind, shortcuts: vec![shortcut] }); + } + } + } + + for (p, from) in self.commands.iter().zip(&before) { + if !decided.contains(&p.command.key()) { + continue; + } + let to = keymap.bindings(&p.command); + if to == *from { + continue; + } + let home = home_of(keymap, &p.command); + let texts = |l: &[Binding]| l.iter().map(|b| b.text(&home)).collect::>(); + report.changed.push(Changed { + command: p.command.clone(), + label: label_of(keymap, &p.command), + item: p.item.clone(), + line: p.line, + from: texts(from), + to: texts(&to), + }); + } + report.imported = report.changed.len(); + return report; + } + } + + /// Settles which command each claimed chord goes to, in entry order, leaving out the claims of + /// `dropped` commands. Returns each command's accepted bindings and the commands that took a + /// chord from an earlier entry; skipped keys go to `report`. + fn resolve(&self, keymap: &Keymap, dropped: &HashMap, report: &mut ImportReport) -> (Vec>, HashSet) { + let home_of = |c: &CommandRef| keymap.bindable(c).map_or_else(Scope::app, |b| b.scope.clone()); let mut claims: Vec<(usize, &PlannedBinding)> = self.commands.iter().enumerate().flat_map(|(c, p)| p.bindings.iter().map(move |b| (c, b))).collect(); claims.sort_by_key(|(_, b)| b.order); let platform = keymap.platform(); let mut taken: HashMap> = HashMap::new(); let mut accepted: Vec> = vec![Vec::new(); self.commands.len()]; + let mut displaced: HashSet = HashSet::new(); for (c, pb) in claims { let Some(p) = self.commands.get(c) else { continue }; - let shortcut = || pb.binding.text(&home_of(keymap, &p.command)); + let shortcut = || pb.binding.text(&home_of(&p.command)); let skip = |reason| Skipped { command: p.command.clone(), item: pb.item.clone(), line: pb.line, shortcut: shortcut(), kept_by: None, reason }; if keymap.is_reserved(&pb.binding.trigger.chord) { @@ -578,6 +666,9 @@ impl ImportPlan { report.skipped.push(skip(SkipReason::UnknownScope)); continue; } + if dropped.contains_key(&c) { + continue; + } let effective = pb.binding.trigger.effective(platform); let (scope, tools) = match keymap.bindable(&p.command) { Some(b) => (pb.binding.scope_or(&b.scope).clone(), if let Kind::Tool { group } = &b.kind { Some(group.clone()) } else { None }), @@ -596,6 +687,9 @@ impl ImportPlan { !clash }); } + if !lost.is_empty() { + displaced.insert(c); + } for (k, earlier) in lost { if let Some(list) = accepted.get_mut(k) { list.retain(|b| !std::ptr::eq(*b, earlier)); @@ -605,7 +699,7 @@ impl ImportPlan { command: other.command.clone(), item: earlier.item.clone(), line: earlier.line, - shortcut: earlier.binding.text(&home_of(keymap, &other.command)), + shortcut: earlier.binding.text(&home_of(&other.command)), kept_by: Some(p.command.clone()), reason: SkipReason::Taken, }); @@ -618,70 +712,8 @@ impl ImportPlan { list.push(pb); } } - let accepted: Vec> = accepted.into_iter().map(|l| l.into_iter().map(|b| b.binding.clone()).collect()).collect(); - - let label_of = |km: &Keymap, c: &CommandRef| km.bindable(c).map(|b| b.label.clone()).unwrap_or_default(); - let mut decided: HashSet = HashSet::new(); - for (p, list) in self.commands.iter().zip(&accepted) { - let failed = |km: &Keymap, change, shortcuts| Failed { command: p.command.clone(), label: label_of(km, &p.command), change, shortcuts }; - if !list.is_empty() { - let list = in_default_order(keymap, &p.command, list); - if keymap.set_bindings(&p.command, list.clone(), Policy::Keep).is_err() { - let home = home_of(keymap, &p.command); - report.failed.push(failed(keymap, FailedChange::Bind, list.iter().map(|b| b.text(&home)).collect())); - continue; - } - } else if p.none_defined && self.none_defined == NoneDefined::Clear { - if !keymap.clear(&p.command) { - report.failed.push(failed(keymap, FailedChange::Clear, Vec::new())); - continue; - } - } else { - continue; - } - decided.insert(p.command.key()); - } - - for (p, list) in self.commands.iter().zip(&accepted) { - if list.is_empty() || !decided.contains(&p.command.key()) { - continue; - } - for h in keymap.clashing(&p.command, list) { - if decided.contains(&h.command.key()) { - continue; - } - let home = home_of(keymap, &h.command); - let label = label_of(keymap, &h.command); - let shortcut = h.binding.text(&home); - if keymap.remove(&h.command, &h.binding) { - report.conflicts_cleared.push(Cleared { command: h.command, label, shortcut }); - } else { - report.failed.push(Failed { command: h.command, label, change: FailedChange::Unbind, shortcuts: vec![shortcut] }); - } - } - } - - for (p, from) in self.commands.iter().zip(before) { - if !decided.contains(&p.command.key()) { - continue; - } - let to = keymap.bindings(&p.command); - if to == from { - continue; - } - let home = home_of(keymap, &p.command); - let texts = |l: &[Binding]| l.iter().map(|b| b.text(&home)).collect::>(); - report.changed.push(Changed { - command: p.command.clone(), - label: label_of(keymap, &p.command), - item: p.item.clone(), - line: p.line, - from: texts(&from), - to: texts(&to), - }); - } - report.imported = report.changed.len(); - report + let accepted = accepted.into_iter().map(|l| l.into_iter().map(|b| b.binding.clone()).collect()).collect(); + (accepted, displaced) } } diff --git a/crates/keymap/tests/import.rs b/crates/keymap/tests/import.rs index a015c9a5d..425f5d59d 100644 --- a/crates/keymap/tests/import.rs +++ b/crates/keymap/tests/import.rs @@ -367,6 +367,19 @@ fn changes_that_find_the_overrides_full_are_reported() { has(&km, "view.goToPage", &[]); has(&km, "file.save", &["Cmd+Alt+S"]); has(&km, "edit.duplicate", &[]); + + // A later entry whose change finds the overrides full leaves the chord with the earlier one. + let set = ForeignSet { + name: None, + entries: vec![win("File", &["Close"], &[("Default", "Ctrl+Alt+J")]), win("File", &["Save"], &[("Default", "Ctrl+Alt+J")])], + }; + let mut km = keymap(Platform::Windows).with_overrides(full()); + let r = plan(&set, &km, &options(Start::Current)).apply(&mut km); + has(&km, "file.close", &["Cmd+Alt+J"]); + has(&km, "file.save", &["Cmd+S"]); + assert_eq!(r.failed, [row("file.save", "Save", FailedChange::Bind, &["Cmd+Alt+J"])]); + assert!(r.skipped.is_empty(), "{:?}", r.skipped); + assert_eq!(r.imported, 1); } #[test] From 53f16925cfd410b847c485c6fbd1132036090266 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 13:15:36 +0000 Subject: [PATCH 10/32] keymap: put overrides_list on the craft-settings example in the crate docs --- crates/keymap/src/lib.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/keymap/src/lib.rs b/crates/keymap/src/lib.rs index bebf33f7e..f669e6d7b 100644 --- a/crates/keymap/src/lib.rs +++ b/crates/keymap/src/lib.rs @@ -62,10 +62,11 @@ //! //! # Storing overrides //! -//! [`Overrides`] is a field of the app's craft-settings type. It is stored as an array of -//! `{ command, keys }` tables, not as a table keyed by command: craft-settings merges tables key -//! by key with what the file holds, but replaces an array whole, so a reset command (an entry -//! removed) stays removed after saving. +//! [`Overrides`] is a field of the app's craft-settings type, marked +//! `#[serde(with = "craft_keymap::keymap::overrides_list")]` so that it is stored as an array of +//! `{ command, keys }` tables. craft-settings merges tables key by key with what the file holds, +//! but replaces an array whole, so a reset command (an entry removed) stays removed after saving. +//! Without the attribute, overrides with at most one text per command are written as a table. //! //! ```no_run //! use craft_keymap::{Binding, Keymap, Overrides, Platform, Policy, Scopes}; @@ -75,6 +76,7 @@ //! #[derive(Serialize, Deserialize, Default, Clone, PartialEq)] //! #[serde(default)] //! struct Prefs { +//! #[serde(with = "craft_keymap::keymap::overrides_list")] //! shortcuts: Overrides, //! } //! From 4a721df085b82f1d64e229b941c64c12aca44564 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 20:47:23 +0000 Subject: [PATCH 11/32] keymap: state that chord reservations are opt-in through with_reserved --- crates/keymap/README.md | 3 +++ crates/keymap/src/keymap.rs | 3 ++- crates/keymap/src/lib.rs | 6 ++++-- crates/keymap/src/reserved.rs | 6 +++++- 4 files changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/keymap/README.md b/crates/keymap/README.md index 81b55ec95..1f2d1b752 100644 --- a/crates/keymap/README.md +++ b/crates/keymap/README.md @@ -13,6 +13,9 @@ its file-format readers and its UI. kept or reported (`Keymap::problems`, the import report). - Hostile input is capped: commands, bindings per command, text lengths, import entries, keys, path segments and fuzzy suggestions (the `MAX_*` constants). What is cut is counted. +- Reserved chords are opt-in. A keymap reserves no chord unless the app passes a list to + `Keymap::with_reserved`, e.g. `reserved::system(platform)` for the operating system's window + switching and closing chords. A reserved chord cannot be assigned or bound. - Dependencies: `serde` and `serde_json`; `egui` with the `egui` feature. ## A catalogue and dispatch diff --git a/crates/keymap/src/keymap.rs b/crates/keymap/src/keymap.rs index d2a81ae98..4ceb76d16 100644 --- a/crates/keymap/src/keymap.rs +++ b/crates/keymap/src/keymap.rs @@ -434,7 +434,8 @@ impl Keymap { self } - /// Chords that cannot be assigned, e.g. [`reserved::system`](crate::reserved::system). + /// Chords that cannot be assigned or bound, e.g. [`reserved::system`](crate::reserved::system). + /// Without this call the keymap reserves no chord. pub fn with_reserved(mut self, chords: Vec) -> Keymap { self.reserved = chords; self.reload(); diff --git a/crates/keymap/src/lib.rs b/crates/keymap/src/lib.rs index f669e6d7b..e673848c7 100644 --- a/crates/keymap/src/lib.rs +++ b/crates/keymap/src/lib.rs @@ -6,8 +6,10 @@ //! protocols store, display text per platform, and a reader for other applications' key text. //! [`command`] names what a binding runs, [`scope`] where it works, and [`keymap`] holds an app's //! catalogue with default bindings, the user's [`Overrides`], dispatch ([`Keymap::lookup`]), -//! editing and conflicts. [`reserved`] lists the chords each operating system takes. [`import`] -//! brings in other applications' shortcut sets. With the `egui` feature, the `egui` module +//! editing and conflicts. [`reserved`] lists the chords each operating system takes; a keymap +//! reserves no chord unless the app opts in with [`Keymap::with_reserved`], e.g. +//! `with_reserved(reserved::system(platform))`. [`import`] brings in other applications' shortcut +//! sets. With the `egui` feature, the `egui` module //! converts to and from egui keys, matches key presses against bindings and dispatches a frame's //! key events. //! diff --git a/crates/keymap/src/reserved.rs b/crates/keymap/src/reserved.rs index 7dbf847bf..4d64d36ac 100644 --- a/crates/keymap/src/reserved.rs +++ b/crates/keymap/src/reserved.rs @@ -1,4 +1,7 @@ //! Chords the operating system takes before the app sees them. +//! +//! A keymap reserves these only when the app passes them to +//! [`Keymap::with_reserved`](crate::Keymap::with_reserved). use crate::chord::{Chord, Platform}; @@ -25,7 +28,8 @@ const LINUX: &[&str] = &[ "Cmd+Alt+F12", ]; -/// The window switching, closing and session chords of `platform`. +/// The window switching, closing and session chords of `platform`, for +/// [`Keymap::with_reserved`](crate::Keymap::with_reserved). pub fn system(platform: Platform) -> Vec { let list = match platform { Platform::Mac => MAC, From a160c1cdeca75bb45375f4810344138b9df0d91e Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 20:47:24 +0000 Subject: [PATCH 12/32] ci: add keymap workflow for core, egui dispatch, macOS, Windows and WASM --- .github/workflows/keymap.yml | 66 ++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 .github/workflows/keymap.yml diff --git a/.github/workflows/keymap.yml b/.github/workflows/keymap.yml new file mode 100644 index 000000000..97b1124e2 --- /dev/null +++ b/.github/workflows/keymap.yml @@ -0,0 +1,66 @@ +name: Keymap + +on: + push: + branches: [main] + paths: ["crates/keymap/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"] + pull_request: + paths: ["crates/keymap/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: keymap-${{ github.ref }} + cancel-in-progress: true + +jobs: + linux: + timeout-minutes: 15 + name: Keymap (Linux) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - uses: Swatinem/rust-cache@v2 + with: + key: craft-keymap-linux + - run: cargo fmt -p craft-keymap --check + - run: cargo clippy -p craft-keymap --all-targets --no-default-features --locked -- -D warnings + - run: cargo clippy -p craft-keymap --all-targets --all-features --locked -- -D warnings + # Doctests run once, in the all-features step. + - name: Test core + run: cargo test -p craft-keymap --no-default-features --lib --tests --locked + - name: Test egui dispatch + run: cargo test -p craft-keymap --all-features --locked + native: + timeout-minutes: 15 + name: Keymap (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + os: [macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + with: + key: craft-keymap-${{ matrix.os }} + - run: cargo test -p craft-keymap --all-features --locked + wasm: + timeout-minutes: 10 + name: Keymap WASM + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + targets: wasm32-unknown-unknown + - uses: Swatinem/rust-cache@v2 + with: + key: craft-keymap-wasm + - run: cargo check -p craft-keymap --all-features --locked --target wasm32-unknown-unknown From 0b34fdb1527cad02df8361936d72e34938dfe05d Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 21:30:56 +0000 Subject: [PATCH 13/32] keymap: split the hostile import test into a fast cap test and an ignored worst-case timing test --- crates/keymap/tests/import.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/keymap/tests/import.rs b/crates/keymap/tests/import.rs index 425f5d59d..e89428b6e 100644 --- a/crates/keymap/tests/import.rs +++ b/crates/keymap/tests/import.rs @@ -428,6 +428,40 @@ fn suggestions_are_reported_never_applied() { #[test] fn hostile_sets_are_capped_and_counted() { + let mut km = keymap(Platform::Windows); + let long: String = "ä€𝄞 x".repeat(MAX_IMPORT_TEXT); + let mut big = ForeignEntry::new(Some(long.as_str()), std::iter::repeat_n(long.clone(), 100)); + for _ in 0..MAX_KEYS_PER_ENTRY + 10 { + let trigger = Err(ForeignError::UnknownKey(long.clone())); + big = big.with_key(ForeignKey { context: Some(long.clone()), text: long.clone(), trigger, notes: vec![ReadNote::Numpad; 1000] }); + } + // Unmatched entries with keys, more than the suggestions take. + let near = win("Edit", &["Chek Spelling Now"], &[("Default", "Ctrl+F12")]); + let mut entries: Vec = std::iter::repeat_n(near, MAX_SUGGESTIONS + 10).collect(); + entries.push(big); + entries.push(win("Edit", &["Paste"], &[("Default", &long), ("Default", "Ctrl+\u{0}"), ("Default", "Win+E")])); + // Entries without keys fill the set to the cap and 500 past it. + let keyless = MAX_IMPORT_ENTRIES - entries.len(); + entries.extend(std::iter::repeat_n(ForeignEntry::new(None, Vec::::new()), keyless + 500)); + let set = ForeignSet { name: Some(long.clone()), entries }; + let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], suggest: true, ..ImportOptions::default() }; + let r = plan(&set, &km, &options).apply(&mut km); + assert_eq!(r.suggestions.len(), MAX_SUGGESTIONS); + // The set name, entries and keys past the caps, and suggestions past the cap (with the big entry's). + assert!(r.truncated >= 1 + 500 + 10 + 11, "{}", r.truncated); + assert_eq!(r.set.as_ref().map(|s| s.chars().count()), Some(MAX_IMPORT_TEXT)); + let row = r.unmatched.iter().find(|u| u.item.starts_with('ä')).unwrap(); + assert!(row.item.chars().count() <= MAX_IMPORT_TEXT * 34, "item of capped segments"); + assert!(row.keys.chars().count() <= (2 * MAX_IMPORT_TEXT + 4) * MAX_KEYS_PER_ENTRY); + assert_eq!(r.unreadable.len(), 1, "Paste's keys"); + has(&km, "edit.paste", &["Cmd+V"]); + // Entries past the cap are left out. + assert_eq!(r.unmatched_without_shortcut, keyless); +} + +#[test] +#[ignore = "worst-case timing; run with --ignored"] +fn hostile_sets_finish_in_time() { // A full catalogue whose labels share words with every unmatched entry below, so each // suggestion scores every command. let mut catalogue = catalogue(); From c519b7a856f4c7987c4a90c50bb1ffa9faa9e3e7 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 21:37:38 +0000 Subject: [PATCH 14/32] keymap: split crowded_chords_stay_fast into a small cap test and an ignored worst-case timing test --- crates/keymap/tests/keymap.rs | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/crates/keymap/tests/keymap.rs b/crates/keymap/tests/keymap.rs index 475109d46..502c3cedc 100644 --- a/crates/keymap/tests/keymap.rs +++ b/crates/keymap/tests/keymap.rs @@ -279,11 +279,11 @@ fn conflicts_tell_clashes_from_shadows() { assert!(!strict.conflicts().iter().any(|c| c.chord.to_string() == "Cmd+R")); } -/// 4096 commands, each with 16 bindings on one chord in 16 panels. -fn crowded(scopes: Scopes, kind: Kind) -> (Keymap, Overrides) { - let catalogue: Vec = (0..MAX_COMMANDS).map(|n| app(&format!("c.{n}"), &[]).with_kind(kind.clone())).collect(); +/// `commands` commands, each with 16 bindings on one chord in 16 panels. +fn crowded(commands: usize, scopes: Scopes, kind: Kind) -> (Keymap, Overrides) { + let catalogue: Vec = (0..commands).map(|n| app(&format!("c.{n}"), &[]).with_kind(kind.clone())).collect(); let mut o = Overrides::new(); - for n in 0..MAX_COMMANDS { + for n in 0..commands { assert!(o.insert(format!("c.{n}"), (1..=MAX_BINDINGS).map(|p| format!("P{p}: K")).collect())); } (Keymap::new(catalogue, scopes, Platform::Mac), o) @@ -294,11 +294,31 @@ fn panels(n: usize) -> Scopes { } #[test] +fn crowded_chords_are_capped() { + // Panels the app never registered are not bound. + let (km, o) = crowded(2, Scopes::new(), Kind::Command); + let km = km.with_overrides(o); + assert!(km.conflicts().is_empty()); + assert!(km.bindings(&cmd("c.0")).is_empty()); + assert_eq!(km.overrides().get("c.0").map(<[String]>::len), Some(MAX_BINDINGS), "kept verbatim"); + assert!(km.problems().contains(&Problem::UnknownScope { key: "c.0".into(), text: "P1: K".into() })); + + // Registered panels that never share: 32 commands make 16 × 496 pairs, capped. + let (km, o) = crowded(32, panels(MAX_BINDINGS).with_panel_fallthrough(false), Kind::Command); + assert_eq!(km.with_overrides(o).conflicts().len(), MAX_CONFLICTS); + + // Tools of one group: no conflicts. + let (km, o) = crowded(32, panels(MAX_BINDINGS), Kind::Tool { group: None }); + assert!(km.with_overrides(o).conflicts().is_empty()); +} + +#[test] +#[ignore = "worst-case timing; run with --ignored"] fn crowded_chords_stay_fast() { let limit = Duration::from_secs(8); // Panels the app never registered are not bound. - let (km, o) = crowded(Scopes::new(), Kind::Command); + let (km, o) = crowded(MAX_COMMANDS, Scopes::new(), Kind::Command); let km = km.with_overrides(o); let t = Instant::now(); assert!(km.conflicts().is_empty()); @@ -308,14 +328,14 @@ fn crowded_chords_stay_fast() { assert!(km.problems().contains(&Problem::UnknownScope { key: "c.0".into(), text: "P1: K".into() })); // Registered panels that never share: many conflicts, capped. - let (km, o) = crowded(panels(MAX_BINDINGS).with_panel_fallthrough(false), Kind::Command); + let (km, o) = crowded(MAX_COMMANDS, panels(MAX_BINDINGS).with_panel_fallthrough(false), Kind::Command); let km = km.with_overrides(o); let t = Instant::now(); assert_eq!(km.conflicts().len(), MAX_CONFLICTS); assert!(t.elapsed() < limit, "{:?}", t.elapsed()); // Tools of one group: no conflicts, and no pair is compared. - let (km, o) = crowded(panels(MAX_BINDINGS), Kind::Tool { group: None }); + let (km, o) = crowded(MAX_COMMANDS, panels(MAX_BINDINGS), Kind::Tool { group: None }); let km = km.with_overrides(o); let t = Instant::now(); assert!(km.conflicts().is_empty()); From 3ef24a785b0e6d00e6c26ef1e3230ba52bf0fd51 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 00:49:05 +0000 Subject: [PATCH 15/32] keymap: egui::platform gives the browser's operating system on the web --- crates/keymap/src/chord.rs | 3 ++- crates/keymap/src/egui.rs | 25 +++++++++++++++++++++++-- crates/keymap/tests/egui.rs | 11 ++++++++++- 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/keymap/src/chord.rs b/crates/keymap/src/chord.rs index 740ccf211..43dcf8ac7 100644 --- a/crates/keymap/src/chord.rs +++ b/crates/keymap/src/chord.rs @@ -22,7 +22,8 @@ pub enum Platform { } impl Platform { - /// The platform this build runs on. Web builds count as Linux. + /// The platform this build runs on. Web builds count as Linux; with the `egui` feature, + /// `egui::platform` gives the browser's operating system. pub const fn current() -> Platform { if cfg!(target_os = "macos") { Platform::Mac diff --git a/crates/keymap/src/egui.rs b/crates/keymap/src/egui.rs index fd4039d54..ca8b31920 100644 --- a/crates/keymap/src/egui.rs +++ b/crates/keymap/src/egui.rs @@ -1,13 +1,34 @@ //! Conversions between the crate's keys and egui's, matching egui key presses to chords, and a -//! [`Dispatcher`] that turns a frame's key events into the commands they run. +//! [`Dispatcher`] that turns a frame's key events into the commands they run. [`platform`] gives +//! the platform to build a keymap for, the browser's operating system included on the web. -use ::egui::{Event, InputState, Key as EguiKey, KeyboardShortcut, Modifiers}; +use ::egui::os::OperatingSystem; +use ::egui::{Context, Event, InputState, Key as EguiKey, KeyboardShortcut, Modifiers}; use crate::chord::{Chord, Key, Mods, Platform, Trigger}; use crate::command::CommandRef; use crate::keymap::{Keymap, Lookup}; use crate::scope::Active; +/// The platform to build a keymap for in this context. Unlike [`Platform::current`], a web build +/// gets the browser's operating system, which eframe reads from the user agent, so a Mac browser +/// shows and matches Cmd shortcuts. eframe sets it before the first frame; an app that builds its +/// keymap earlier rebuilds it when this differs. +pub fn platform(ctx: &Context) -> Platform { + Platform::from(ctx.os()) +} + +/// iOS counts as Mac; Android and unknown systems count as Linux. +impl From for Platform { + fn from(os: OperatingSystem) -> Platform { + match os { + OperatingSystem::Mac | OperatingSystem::IOS => Platform::Mac, + OperatingSystem::Windows => Platform::Windows, + OperatingSystem::Nix | OperatingSystem::Android | OperatingSystem::Unknown => Platform::Linux, + } + } +} + // Both matches are generated from one list so that a key added to `Key` without an egui // counterpart fails to compile. macro_rules! egui_keys { diff --git a/crates/keymap/tests/egui.rs b/crates/keymap/tests/egui.rs index 23db9756c..5487c8074 100644 --- a/crates/keymap/tests/egui.rs +++ b/crates/keymap/tests/egui.rs @@ -1,6 +1,6 @@ #![cfg(feature = "egui")] -use craft_keymap::egui::{Dispatcher, Hit, matches}; +use craft_keymap::egui::{Dispatcher, Hit, matches, platform}; use craft_keymap::{Active, Bindable, Binding, Chord, CommandRef, Key, Keymap, Kind, Mods, Platform, Scope, Scopes, Trigger}; use egui::{Event, InputState, Key as EguiKey, Modifiers}; @@ -8,6 +8,15 @@ fn chord(text: &str) -> Chord { Chord::parse(text).unwrap_or_else(|e| panic!("{text}: {e}")) } +#[test] +fn a_browser_on_a_mac_gets_the_mac_keymap() { + let ctx = egui::Context::default(); + ctx.set_os(egui::os::OperatingSystem::from_user_agent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15")); + assert_eq!(platform(&ctx), Platform::Mac); + ctx.set_os(egui::os::OperatingSystem::from_user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64)")); + assert_eq!(platform(&ctx), Platform::Windows); +} + #[test] fn every_key_converts_both_ways() { for &key in Key::ALL { From 1b329b9422c0e05a7e5dbd09edb4ba9e53a92621 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 02:39:41 +0000 Subject: [PATCH 16/32] keymap: a web clipboard press takes its clipboard event and the pasted text with it --- crates/keymap/README.md | 4 ++- crates/keymap/src/egui.rs | 71 +++++++++++++++++++++---------------- crates/keymap/tests/egui.rs | 25 +++++++++++++ 3 files changed, 69 insertions(+), 31 deletions(-) diff --git a/crates/keymap/README.md b/crates/keymap/README.md index 1f2d1b752..70308245b 100644 --- a/crates/keymap/README.md +++ b/crates/keymap/README.md @@ -228,6 +228,8 @@ assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File egui's Copy, Cut and Paste events stay with the app by default. On the desktop, egui-winit sends them in place of the Cmd+C, Cmd+X and Cmd+V presses (Ctrl off macOS), so a binding on those chords runs only with `with_clipboard_events(true)`. Then the events count as their - chords outside text fields, and a Paste event's text moves to `Hit::pasted`. An app whose + chords outside text fields, and a Paste event's text moves to `Hit::pasted`. The web build + sends the key press and then the event; the press runs the command and takes the event, with + its text, along. An app whose paste command asks egui for a paste gets a Paste event back, which runs that command again; such an app keeps the default. diff --git a/crates/keymap/src/egui.rs b/crates/keymap/src/egui.rs index ca8b31920..70330db6e 100644 --- a/crates/keymap/src/egui.rs +++ b/crates/keymap/src/egui.rs @@ -173,7 +173,8 @@ pub struct Hit { /// the shifted key for a Shift binding (`:` for `Shift+;`), Shift held to type a symbol, or /// `+` and `=` standing for each other. pub exact: bool, - /// The text of the Paste event that ran the command ([`Dispatcher::with_clipboard_events`]). + /// The text of the Paste event that ran the command, or on the web the Paste event that came + /// with the press that ran it ([`Dispatcher::with_clipboard_events`]). pub pasted: Option, } @@ -240,7 +241,8 @@ impl Dispatcher { /// Cmd+X, Cmd+V; Shift+Delete and Shift+Insert for Cut and Paste with Shift alone) outside text /// fields. Off by default: the events stay in egui's input for the app's own handlers. With it /// on, an event that runs a command is removed, and a Paste event's text moves to - /// [`Hit::pasted`]. An app that asks egui for a paste (`ViewportCommand::RequestPaste`) to run + /// [`Hit::pasted`]. On the web, the key press runs the command and its clipboard event goes + /// with it the same way; when the press runs nothing, or the hit is declined, both stay. An app that asks egui for a paste (`ViewportCommand::RequestPaste`) to run /// its paste command gets a Paste event back, which with this on runs that command again. pub fn with_clipboard_events(mut self, on: bool) -> Dispatcher { self.clipboard = on; @@ -266,11 +268,12 @@ impl Dispatcher { let mut kept = Vec::with_capacity(input.events.len()); // The Text event egui sends after a key press belongs to that press. let mut drop_text = false; - // The web build sends both a clipboard key press and the clipboard event it causes. - let mut clipboard_press = None; let events = std::mem::take(&mut input.events); let typed = if active.typing { typed_text(&events) } else { Vec::new() }; - let causes_event = if self.clipboard { Vec::new() } else { clipboard_event_follows(&events, platform) }; + // The web build sends both a clipboard key press and the clipboard event it causes. The + // press decides: its event goes with it when it runs a command and stays otherwise. + let causes = clipboard_event_follows(&events, platform); + let mut caused_taken: Vec> = vec![None; events.len()]; for (i, event) in events.into_iter().enumerate() { match &event { Event::Key { key, pressed: true, repeat, modifiers, .. } if !*repeat || self.repeat => { @@ -281,16 +284,22 @@ impl Dispatcher { let keep = if active.typing { typed.get(i) == Some(&true) || clip.is_some() || may_be_alt_gr(key, held, platform) } else { - causes_event.get(i) == Some(&true) + !self.clipboard && causes[i].is_some() }; if keep { kept.push(event); continue; } - if clip.is_some() { - clipboard_press = clip; + let caused = causes[i].clone(); + let hit = self.press(key, held, *repeat, now, keymap, active).map(|mut hit| { + hit.pasted = caused.as_ref().and_then(|(_, text)| text.clone()); + hit + }); + let hit = hit.filter(&mut accept); + if let Some((j, _)) = caused { + caused_taken[j] = Some(hit.is_some()); } - if let Some(hit) = self.press(key, held, *repeat, now, keymap, active).filter(&mut accept) { + if let Some(hit) = hit { hits.push(hit); drop_text = !(held.cmd || held.ctrl); continue; @@ -303,9 +312,11 @@ impl Dispatcher { } // A focused text field copies and pastes on these events itself. Event::Copy | Event::Cut | Event::Paste(_) if self.clipboard && !active.typing => { - let (key, held, clip) = clipboard_chord(&event, frame_mods); - if clipboard_press == Some(clip) { - clipboard_press = None; + let (key, held) = clipboard_chord(&event, frame_mods); + if let Some(taken) = caused_taken[i] { + if taken { + continue; + } } else if let Some(mut hit) = self.press(key, held, false, now, keymap, active) { if let Event::Paste(text) = &event { hit.pasted = Some(text.clone()); @@ -349,19 +360,19 @@ enum Clip { Paste, } -/// For each event, whether it is a clipboard key press whose clipboard event comes later in the -/// frame, as the web build sends them. -fn clipboard_event_follows(events: &[Event], platform: Platform) -> Vec { - let mut out = vec![false; events.len()]; - let mut ahead = [false; 3]; - for (event, follows) in events.iter().zip(out.iter_mut()).rev() { +/// For each clipboard key press whose clipboard event comes later in the frame, as the web build +/// sends them: the index of that event, and the text of a Paste event. +fn clipboard_event_follows(events: &[Event], platform: Platform) -> Vec)>> { + let mut out = vec![None; events.len()]; + let mut ahead: [Option; 3] = [None; 3]; + for (i, event) in events.iter().enumerate().rev() { if let Some(seen) = event_clip(event).and_then(|c| ahead.get_mut(c as usize)) { - *seen = true; + *seen = Some(i); } else if let Event::Key { key, pressed: true, modifiers, .. } = event { let clip = Key::from_egui(*key).and_then(|k| clipboard_kind(k, Mods::from_egui(modifiers, platform))); - if let Some(seen) = clip.and_then(|c| ahead.get_mut(c as usize)) { - *follows = *seen; - *seen = false; + if let Some(j) = clip.and_then(|c| ahead.get_mut(c as usize)).and_then(Option::take) { + let text = if let Some(Event::Paste(text)) = events.get(j) { Some(text.clone()) } else { None }; + out[i] = Some((j, text)); } } } @@ -434,16 +445,16 @@ fn clipboard_kind(key: Key, held: Mods) -> Option { } } -/// The press a clipboard event stands for, with the modifiers held, and the event's kind. Off -/// macOS egui-winit also sends Cut for Shift+Delete and Paste for Shift+Insert. -fn clipboard_chord(event: &Event, held: Mods) -> (Key, Mods, Clip) { +/// The press a clipboard event stands for, with the modifiers held. Off macOS egui-winit also +/// sends Cut for Shift+Delete and Paste for Shift+Insert. +fn clipboard_chord(event: &Event, held: Mods) -> (Key, Mods) { let with_cmd = Mods { cmd: true, ..held }; let shift_only = held.shift && !held.cmd; match event { - Event::Cut if shift_only => (Key::Delete, held, Clip::Cut), - Event::Cut => (Key::X, with_cmd, Clip::Cut), - Event::Paste(_) if shift_only => (Key::Insert, held, Clip::Paste), - Event::Paste(_) => (Key::V, with_cmd, Clip::Paste), - _ => (Key::C, with_cmd, Clip::Copy), + Event::Cut if shift_only => (Key::Delete, held), + Event::Cut => (Key::X, with_cmd), + Event::Paste(_) if shift_only => (Key::Insert, held), + Event::Paste(_) => (Key::V, with_cmd), + _ => (Key::C, with_cmd), } } diff --git a/crates/keymap/tests/egui.rs b/crates/keymap/tests/egui.rs index 5487c8074..567a852e7 100644 --- a/crates/keymap/tests/egui.rs +++ b/crates/keymap/tests/egui.rs @@ -193,6 +193,31 @@ fn clipboard_events_run_their_chords_outside_text_fields_when_turned_on() { } } +#[test] +fn a_web_paste_carries_its_text_and_takes_its_event() { + let km = dispatch_keymap(); + let mut d = Dispatcher::new().with_clipboard_events(true); + // The web build sends the Cmd+V press and then the Paste event with the clipboard text. + let events = vec![press(EguiKey::V, CTRL), Event::Paste("text".into()), press(EguiKey::C, CTRL), Event::Copy]; + let mut input = frame(1.0, CTRL, events.clone()); + let mut seen = Vec::new(); + let hits = d.dispatch_filtered(&mut input, &km, &Active::NONE, |hit| { + seen.push(hit.pasted.clone()); + true + }); + let ran: Vec<_> = hits.iter().map(|h| (h.command.id.as_str(), h.pasted.as_deref())).collect(); + assert_eq!(ran, [("edit.paste", Some("text")), ("edit.copy", None)]); + assert_eq!(seen, [Some("text".to_string()), None], "the filter sees the pasted text"); + assert!(input.events.is_empty(), "{:?}", input.events); + + // A declined press leaves the press and its event in place, and the event does not run again. + let mut input = frame(2.0, CTRL, events.clone()); + let hits = d.dispatch_filtered(&mut input, &km, &Active::NONE, |hit| hit.command.id != "edit.paste"); + let ran: Vec<_> = hits.iter().map(|h| h.command.id.as_str()).collect(); + assert_eq!(ran, ["edit.copy"]); + assert_eq!(input.events, events[..2]); +} + #[test] fn declined_hits_leave_their_events_in_order() { let km = dispatch_keymap(); From 75a42cb95fc7cab183d86b3449ca4d6c8bddd1c4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 02:40:57 +0000 Subject: [PATCH 17/32] keymap: an import change that cannot take a chord from another command leaves both commands as they were --- crates/keymap/src/import.rs | 29 +++++++++++++++++++++-------- crates/keymap/tests/import.rs | 11 ++++++----- 2 files changed, 27 insertions(+), 13 deletions(-) diff --git a/crates/keymap/src/import.rs b/crates/keymap/src/import.rs index 89e4b2f84..6cafe2b09 100644 --- a/crates/keymap/src/import.rs +++ b/crates/keymap/src/import.rs @@ -279,8 +279,7 @@ pub struct Failed { pub command: CommandRef, pub label: String, pub change: FailedChange, - /// The set's shortcuts for [`FailedChange::Bind`], the one left on the command for - /// [`FailedChange::Unbind`]; empty for [`FailedChange::Clear`]. + /// The set's shortcuts for [`FailedChange::Bind`]; empty for [`FailedChange::Clear`]. pub shortcuts: Vec, } @@ -288,13 +287,11 @@ pub struct Failed { #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum FailedChange { - /// Giving the command the set's bindings. + /// Giving the command the set's bindings, or taking one of them from another command. Bind, /// Leaving the command without shortcuts: the set has it without keys and /// [`NoneDefined::Clear`] applies. Clear, - /// Taking a chord the set gives to another command; both commands keep it. - Unbind, } /// Why keys of an entry were not used. @@ -548,7 +545,8 @@ impl ImportPlan { /// /// A change that finds the overrides full is left out and reported in /// [`ImportReport::failed`]; the others still apply, and a chord it would have taken from an - /// earlier entry stays with that entry. With [`Start::Defaults`] that cannot happen. + /// earlier entry stays with that entry. That includes taking a chord from another command: + /// both commands keep the bindings they had. With [`Start::Defaults`] that cannot happen. pub fn apply(&self, keymap: &mut Keymap) -> ImportReport { let before: Vec> = self.commands.iter().map(|p| keymap.bindings(&p.command)).collect(); // Dropping every entry leaves room for all of them: each catalogue command takes at most one @@ -598,7 +596,10 @@ impl ImportPlan { decided.insert(p.command.key()); } - for (p, list) in self.commands.iter().zip(&accepted) { + // A command that cannot take a chord from another command is dropped, so both keep + // the bindings they had. + let mut unbind_failed = false; + for (c, (p, list)) in self.commands.iter().zip(&accepted).enumerate() { if list.is_empty() || !decided.contains(&p.command.key()) { continue; } @@ -612,10 +613,22 @@ impl ImportPlan { if keymap.remove(&h.command, &h.binding) { report.conflicts_cleared.push(Cleared { command: h.command, label, shortcut }); } else { - report.failed.push(Failed { command: h.command, label, change: FailedChange::Unbind, shortcuts: vec![shortcut] }); + let home = home_of(keymap, &p.command); + let list = in_default_order(keymap, &p.command, list); + let shortcuts = list.iter().map(|b| b.text(&home)).collect(); + dropped.insert( + c, + Failed { command: p.command.clone(), label: label_of(keymap, &p.command), change: FailedChange::Bind, shortcuts }, + ); + unbind_failed = true; + break; } } } + if unbind_failed { + *keymap = start.clone(); + continue 'attempt; + } for (p, from) in self.commands.iter().zip(&before) { if !decided.contains(&p.command.key()) { diff --git a/crates/keymap/tests/import.rs b/crates/keymap/tests/import.rs index e89428b6e..586e02dfb 100644 --- a/crates/keymap/tests/import.rs +++ b/crates/keymap/tests/import.rs @@ -330,10 +330,11 @@ fn changes_that_find_the_overrides_full_are_reported() { }; let options = |start| ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], start, ..ImportOptions::default() }; - // file.close has an entry to rewrite; the other changes each need a new one. + // file.close has an entry to rewrite, but taking Cmd+J from view.goToPage needs a new one, so + // both stay as they were. The other changes each need a new entry too. let mut km = keymap(Platform::Windows).with_overrides(full()); let r = plan(&set, &km, &options(Start::Current)).apply(&mut km); - has(&km, "file.close", &["Cmd+J"]); + has(&km, "file.close", &["Cmd+Q"]); has(&km, "view.goToPage", &["Cmd+J"]); has(&km, "file.save", &["Cmd+S"]); has(&km, "edit.duplicate", &["Cmd+Alt+Shift+D"]); @@ -346,16 +347,16 @@ fn changes_that_find_the_overrides_full_are_reported() { assert_eq!( r.failed, [ + row("file.close", "Close", FailedChange::Bind, &["Cmd+J"]), row("file.save", "Save", FailedChange::Bind, &["Cmd+Alt+S"]), row("edit.duplicate", "Duplicate", FailedChange::Clear, &[]), - row("view.goToPage", "Go to Page…", FailedChange::Unbind, &["Cmd+J"]), ] ); - assert_eq!(r.imported, 1); + assert_eq!(r.imported, 0); assert!(r.conflicts_cleared.is_empty()); let v = serde_json::to_value(&r).unwrap(); assert_eq!( - v["failed"][0], + v["failed"][1], json!({"command": {"id": "file.save", "params": null}, "label": "Save", "change": "bind", "shortcuts": ["Cmd+Alt+S"]}) ); From 890660444cb87c4eb1ccff12a5be6813d996d40e Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 03:24:56 +0000 Subject: [PATCH 18/32] keymap: use US spelling --- README.md | 2 +- crates/keymap/README.md | 18 +++---- crates/keymap/src/egui.rs | 2 +- crates/keymap/src/import.rs | 36 ++++++------- crates/keymap/src/keymap.rs | 96 ++++++++++++++++----------------- crates/keymap/src/lib.rs | 12 ++--- crates/keymap/tests/egui.rs | 4 +- crates/keymap/tests/import.rs | 50 ++++++++--------- crates/keymap/tests/keymap.rs | 92 +++++++++++++++---------------- crates/keymap/tests/settings.rs | 4 +- 10 files changed, 158 insertions(+), 158 deletions(-) diff --git a/README.md b/README.md index 166c3b9e2..0e2b540ff 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ craft- = { git = "https://github.com/storytold/craft-libs", rev = ". +// `catalog` is the app's Vec. let (mut store, _report) = SettingsStore::::open(Location::Auto); -let mut keymap = Keymap::new(catalogue, Scopes::new(), Platform::current()).with_overrides(store.get().shortcuts.clone()); +let mut keymap = Keymap::new(catalog, Scopes::new(), Platform::current()).with_overrides(store.get().shortcuts.clone()); // Entries for unknown commands and texts that do not parse are kept and listed here. let _problems = keymap.problems(); @@ -177,9 +177,9 @@ assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File - Panel menus: sources list panel-menu items with the panel's name in front (InDesign's Panel Menus area writes `Character: All Caps`; Illustrator and Photoshop sets have similar areas). The reader splits the name into segments and marks the entry `ForeignEntry::in_panel_menu()`. - Such an entry also matches a catalogue path that ends with its segments (with the command's + Such an entry also matches a catalog path that ends with its segments (with the command's label or the path's last segment last), and its last segment alone as a label. The last - segment alone counts only when the first segment, the panel, is a segment of some catalogue + segment alone counts only when the first segment, the panel, is a segment of some catalog path, so `History: New Document` matches nothing in an app without a History panel. An entry without keys that matched only these ways leaves the command's shortcuts alone and is listed in `matched_without_change` (reason `PanelMenu`). diff --git a/crates/keymap/src/egui.rs b/crates/keymap/src/egui.rs index 70330db6e..fd5d27941 100644 --- a/crates/keymap/src/egui.rs +++ b/crates/keymap/src/egui.rs @@ -164,7 +164,7 @@ pub const DOUBLE_PRESS: f64 = 0.6; pub struct Hit { /// The command to run; for tools sharing the chord, the first of `cycle`. pub command: CommandRef, - /// Tools of one group sharing the chord, in catalogue order (the app picks the next one); + /// Tools of one group sharing the chord, in catalog order (the app picks the next one); /// empty for a plain command. pub cycle: Vec, /// The chord whose binding matched, with `double` set when the double binding ran. diff --git a/crates/keymap/src/import.rs b/crates/keymap/src/import.rs index 6cafe2b09..daf8b81ea 100644 --- a/crates/keymap/src/import.rs +++ b/crates/keymap/src/import.rs @@ -53,8 +53,8 @@ pub struct ForeignEntry { /// submenu of [`ForeignEntry::menu`], which is usually `None`. Sources write such items as /// `Character: All Caps` (InDesign's Panel Menus area, the panel-menu areas of Illustrator and /// Photoshop sets); the reader splits them into segments. Such an entry also matches a - /// catalogue path that ends with its path, and its last segment alone when its first segment - /// is a segment of some catalogue path. Without keys, an entry matched only these ways + /// catalog path that ends with its path, and its last segment alone when its first segment + /// is a segment of some catalog path. Without keys, an entry matched only these ways /// changes nothing ([`ImportReport::matched_without_change`]). pub panel_menu: bool, } @@ -94,7 +94,7 @@ impl ForeignEntry { self.menu.iter().chain(&self.path).map(String::as_str).collect::>().join(" > ") } - /// The key of [`ImportOptions::remembered`] for this entry: the normalised menu and path + /// The key of [`ImportOptions::remembered`] for this entry: the normalized menu and path /// joined by U+001F. pub fn remember_key(&self) -> String { self.menu.iter().chain(&self.path).map(|s| normalize_label(s)).collect::>().join("\u{1f}") @@ -344,7 +344,7 @@ pub struct MatchedWithoutChange { #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum NoChangeReason { - /// The entry matched only through a panel-menu rule (a catalogue path ending with its + /// The entry matched only through a panel-menu rule (a catalog path ending with its /// segments, or its last segment alone). Such a match is close enough to bind the entry's /// keys, not to take a command's shortcuts away. PanelMenu, @@ -407,7 +407,7 @@ pub fn normalize_label(s: &str) -> String { s.split_whitespace().collect::>().join(" ").to_lowercase() } -/// A normalised name without a leading `show/hide `, `show ` or `hide ` when something remains: +/// A normalized name without a leading `show/hide `, `show ` or `hide ` when something remains: /// sources name a toggle by what choosing it does now. Only toggle commands /// ([`Bindable::is_toggle`]) are matched by this form. fn toggle_name(s: &str) -> String { @@ -466,7 +466,7 @@ pub fn plan(set: &ForeignSet, keymap: &Keymap, options: &ImportOptions) -> Impor if by_panel && entry.keys.is_empty() { let (command, label) = - keymap.catalogue().get(i).map(|b| (b.command.clone(), b.label.clone())).unwrap_or_else(|| (CommandRef::new(""), String::new())); + keymap.catalog().get(i).map(|b| (b.command.clone(), b.label.clone())).unwrap_or_else(|| (CommandRef::new(""), String::new())); report.matched_without_change.push(MatchedWithoutChange { command, label, item, line: entry.line, reason: NoChangeReason::PanelMenu }); continue; } @@ -511,7 +511,7 @@ pub fn plan(set: &ForeignSet, keymap: &Keymap, options: &ImportOptions) -> Impor } let at = *planned_at.entry(i).or_insert_with(|| { - let command = keymap.catalogue().get(i).map(|b| b.command.clone()).unwrap_or_else(|| CommandRef::new("")); + let command = keymap.catalog().get(i).map(|b| b.command.clone()).unwrap_or_else(|| CommandRef::new("")); commands.push(Planned { command, item: item.clone(), line, bindings: Vec::new(), none_defined: true }); commands.len() - 1 }); @@ -549,8 +549,8 @@ impl ImportPlan { /// both commands keep the bindings they had. With [`Start::Defaults`] that cannot happen. pub fn apply(&self, keymap: &mut Keymap) -> ImportReport { let before: Vec> = self.commands.iter().map(|p| keymap.bindings(&p.command)).collect(); - // Dropping every entry leaves room for all of them: each catalogue command takes at most one - // entry, and the catalogue holds at most `MAX_COMMANDS`. + // Dropping every entry leaves room for all of them: each catalog command takes at most one + // entry, and the catalog holds at most `MAX_COMMANDS`. if self.start == Start::Defaults { keymap.reset_all(); } @@ -814,10 +814,10 @@ enum Found { None, } -/// Catalogue names in one form, for the match steps. +/// Catalog names in one form, for the match steps. #[derive(Default)] struct Names { - /// Normalised paths joined by U+001F. + /// Normalized paths joined by U+001F. paths: HashMap>, /// The last two or more segments of paths, also with the label as the last one, joined by /// U+001F: for panel-menu entries. @@ -870,9 +870,9 @@ impl Names { } } - /// The lists the match steps look up for an entry's normalised menu and path, most specific + /// The lists the match steps look up for an entry's normalized menu and path, most specific /// first, each with whether it is a panel-menu step. `panel` is `Some(known)` for a panel-menu - /// entry, `known` saying whether the catalogue has its panel; only then does its last segment + /// entry, `known` saying whether the catalog has its panel; only then does its last segment /// alone match. fn steps(&self, menu: Option<&String>, segs: &[String], panel: Option) -> Vec<(Option<&Vec>, bool)> { let Some(last) = segs.last() else { return Vec::new() }; @@ -900,7 +900,7 @@ impl Names { } } -/// The catalogue by normalised path and label, for the match steps. +/// The catalog by normalized path and label, for the match steps. struct Index { tool: Vec, /// Binding keys, for remembered answers. @@ -908,14 +908,14 @@ struct Index { names: Names, /// Toggle commands by their names without a leading Show/Hide ([`toggle_name`]). toggles: Names, - /// Every normalised segment of every catalogue path: the panels and menus the app has. + /// Every normalized segment of every catalog path: the panels and menus the app has. segments: HashSet, } impl Index { fn new(keymap: &Keymap) -> Index { let mut ix = Index { tool: Vec::new(), keys: HashMap::new(), names: Names::default(), toggles: Names::default(), segments: HashSet::new() }; - for (i, b) in keymap.catalogue().iter().enumerate() { + for (i, b) in keymap.catalog().iter().enumerate() { ix.tool.push(matches!(b.kind, Kind::Tool { .. })); ix.keys.insert(b.command.key(), i); ix.names.add(i, b, str::to_string); @@ -939,7 +939,7 @@ impl Index { /// The match steps in order; the first that finds exactly one command decides. The steps run /// on the names as written, then on toggle commands with the entry's label and theirs /// without a leading Show/Hide. A panel-menu entry's last segment alone matches only when - /// its first segment, the panel, is a segment of some catalogue path. + /// its first segment, the panel, is a segment of some catalog path. fn find(&self, entry: &ForeignEntry, tool: bool, remembered: &BTreeMap) -> Found { if let Some(c) = remembered.get(&entry.remember_key()) && let Some(&i) = self.keys.get(&c.key()) @@ -978,7 +978,7 @@ struct ToSuggest { /// Fuzzy candidates for unmatched entries, among commands of the same kind. fn suggest(keymap: &Keymap, entries: &[ToSuggest]) -> Vec { - let pool = |tool: bool| -> Vec<&Bindable> { keymap.catalogue().iter().filter(|b| matches!(b.kind, Kind::Tool { .. }) == tool).collect() }; + let pool = |tool: bool| -> Vec<&Bindable> { keymap.catalog().iter().filter(|b| matches!(b.kind, Kind::Tool { .. }) == tool).collect() }; let matcher = |pool: &[&Bindable]| { let candidates: Vec = pool .iter() diff --git a/crates/keymap/src/keymap.rs b/crates/keymap/src/keymap.rs index 4ceb76d16..4c3f23fc4 100644 --- a/crates/keymap/src/keymap.rs +++ b/crates/keymap/src/keymap.rs @@ -1,4 +1,4 @@ -//! A command catalogue with default bindings, the user's overrides, dispatch and conflicts. +//! A command catalog with default bindings, the user's overrides, dispatch and conflicts. pub(crate) mod overrides; @@ -14,7 +14,7 @@ use crate::scope::{Active, Scope, ScopeKind, Scopes}; pub use overrides::Overrides; pub use overrides::list as overrides_list; -/// Most commands a catalogue or an [`Overrides`] holds. +/// Most commands a catalog or an [`Overrides`] holds. pub const MAX_COMMANDS: usize = 4096; /// Most bindings per command. pub const MAX_BINDINGS: usize = 16; @@ -226,7 +226,7 @@ impl TypingRule { pub enum Lookup { None, Run(CommandRef), - /// Tools of one group share the chord: the app picks the next one (catalogue order). + /// Tools of one group share the chord: the app picks the next one (catalog order). Cycle(Vec), } @@ -272,7 +272,7 @@ pub enum AssignError { TooMany, /// Other commands hold the chord ([`Policy::Refuse`]). Taken(Vec), - /// A scope that is neither registered in [`Scopes`] nor used by the catalogue. + /// A scope that is neither registered in [`Scopes`] nor used by the catalog. UnknownScope(Scope), /// The change needs a new [`Overrides`] entry and it already holds [`MAX_COMMANDS`]. Full, @@ -311,13 +311,13 @@ pub enum DropReason { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Problem { - /// No command in the catalogue has this key; the entry is kept. + /// No command in the catalog has this key; the entry is kept. UnknownCommand { key: String }, /// A text that does not parse; the entry keeps it. BadBinding { key: String, text: String, error: BindingError }, /// A reserved chord; not bound. Reserved { key: String, text: String }, - /// A scope that is neither registered in [`Scopes`] nor used by the catalogue; not bound. + /// A scope that is neither registered in [`Scopes`] nor used by the catalog; not bound. UnknownScope { key: String, text: String }, /// Another entry names the same command; this one is ignored. DuplicateKey { key: String }, @@ -366,10 +366,10 @@ struct Group<'a> { /// one's command and binding. type Pair<'a> = (usize, usize, bool, (usize, &'a Bound), (usize, &'a Bound)); -/// The catalogue, the scope registry, the platform and the user's overrides. +/// The catalog, the scope registry, the platform and the user's overrides. #[derive(Clone, Debug)] pub struct Keymap { - catalogue: Vec, + catalog: Vec, keys: Vec, index: HashMap, defaults: Vec>, @@ -381,8 +381,8 @@ pub struct Keymap { /// Whether the overrides hold a hand-written variant of a command's key /// (`window.panel { "panel": "layers" }`); only loading adds them. variants: bool, - /// Home and default scopes of the catalogue. - catalogue_scopes: HashSet, + /// Home and default scopes of the catalog. + catalog_scopes: HashSet, scopes: Scopes, platform: Platform, typing: TypingRule, @@ -393,9 +393,9 @@ pub struct Keymap { impl Keymap { /// A keymap with default bindings. Entries past [`MAX_COMMANDS`], with a key over /// [`MAX_KEY`] bytes, or repeating an earlier key are left out. - pub fn new(catalogue: Vec, scopes: Scopes, platform: Platform) -> Keymap { + pub fn new(catalog: Vec, scopes: Scopes, platform: Platform) -> Keymap { let mut km = Keymap { - catalogue: Vec::new(), + catalog: Vec::new(), keys: Vec::new(), index: HashMap::new(), defaults: Vec::new(), @@ -403,27 +403,27 @@ impl Keymap { by_trigger: HashMap::new(), stored: Vec::new(), variants: false, - catalogue_scopes: HashSet::new(), + catalog_scopes: HashSet::new(), scopes, platform, typing: TypingRule::default(), reserved: Vec::new(), overrides: Overrides::new(), }; - for b in catalogue { + for b in catalog { let key = b.command.key(); - if km.catalogue.len() >= MAX_COMMANDS || key.len() > MAX_KEY || km.index.contains_key(&key) { + if km.catalog.len() >= MAX_COMMANDS || key.len() > MAX_KEY || km.index.contains_key(&key) { continue; } let defaults = km.normalize(b.defaults.iter().cloned(), &b.scope); - km.catalogue_scopes.insert(b.scope.clone()); - km.catalogue_scopes.extend(defaults.iter().map(|(_, s)| s.clone())); - km.index.insert(key.clone(), km.catalogue.len()); + km.catalog_scopes.insert(b.scope.clone()); + km.catalog_scopes.extend(defaults.iter().map(|(_, s)| s.clone())); + km.index.insert(key.clone(), km.catalog.len()); km.keys.push(key); km.current.push(defaults.clone()); km.defaults.push(defaults); km.stored.push(None); - km.catalogue.push(b); + km.catalog.push(b); } km.rebuild_index(); km @@ -468,12 +468,12 @@ impl Keymap { self.typing } - pub fn catalogue(&self) -> &[Bindable] { - &self.catalogue + pub fn catalog(&self) -> &[Bindable] { + &self.catalog } pub fn bindable(&self, command: &CommandRef) -> Option<&Bindable> { - self.find(command).map(|i| &self.catalogue[i]) + self.find(command).map(|i| &self.catalog[i]) } /// The effective bindings of a command; empty for an unknown one. @@ -492,9 +492,9 @@ impl Keymap { } /// Whether bindings may use `scope`: the application, a scope registered in [`Scopes`], or a - /// home or default scope of the catalogue. + /// home or default scope of the catalog. pub fn knows_scope(&self, scope: &Scope) -> bool { - scope.is_app() || self.scopes.knows(scope) || self.catalogue_scopes.contains(scope) + scope.is_app() || self.scopes.knows(scope) || self.catalog_scopes.contains(scope) } /// The command `chord` (pressed twice when `double`) runs with `active` focus. @@ -502,7 +502,7 @@ impl Keymap { let want = Trigger { chord: chord.effective(self.platform), double }; let held = active.typing && !self.typing.fires(&want.chord); let Some(holders) = self.by_trigger.get(&want) else { return Lookup::None }; - // Each command's nearest rank; `holders` is in catalogue order. + // Each command's nearest rank; `holders` is in catalog order. let mut ranks: Vec<(usize, u8)> = Vec::new(); for &(i, k) in holders { let Some(r) = self.at(i, k).and_then(|(_, s)| self.scopes.rank(s, active)) else { continue }; @@ -519,12 +519,12 @@ impl Keymap { let winners: Vec = ranks.iter().filter(|(_, r)| *r == best).map(|(i, _)| *i).collect(); match winners.as_slice() { [] => Lookup::None, - [i] => Lookup::Run(self.catalogue[*i].command.clone()), + [i] => Lookup::Run(self.catalog[*i].command.clone()), [first, rest @ ..] => { if rest.iter().all(|j| self.same_group(*first, *j)) { - Lookup::Cycle(winners.iter().map(|i| self.catalogue[*i].command.clone()).collect()) + Lookup::Cycle(winners.iter().map(|i| self.catalog[*i].command.clone()).collect()) } else { - Lookup::Run(self.catalogue[*first].command.clone()) + Lookup::Run(self.catalog[*first].command.clone()) } } } @@ -548,7 +548,7 @@ impl Keymap { if bindings.len() > MAX_BINDINGS { return Err(AssignError::TooMany); } - let home = self.catalogue[i].scope.clone(); + let home = self.catalog[i].scope.clone(); let list = self.normalize(bindings, &home); let new: Vec = list.iter().filter(|b| !self.current[i].iter().any(|c| self.same(c, b))).cloned().collect(); self.apply(i, list, &new, policy) @@ -588,14 +588,14 @@ impl Keymap { } /// Pairs of commands on one chord, at most [`MAX_CONFLICTS`], in chord order, then in - /// catalogue order. Tools of one group and bindings of panels that are never active together + /// catalog order. Tools of one group and bindings of panels that are never active together /// are left out; with panel fallthrough two unrelated panels on one chord tie in a third panel, /// which is reported as a [`ConflictKind::Shadow`]. /// /// When the cap cuts a chord's pairs, the pairs kept are the first found comparing the /// chord's holders grouped by scope and tool group, group by group in the order each group - /// first appears in the catalogue; the kept pairs are still returned in chord order, then - /// catalogue order. + /// first appears in the catalog; the kept pairs are still returned in chord order, then + /// catalog order. pub fn conflicts(&self) -> Vec { let mut chords: Vec<(&Trigger, &BTreeSet<(usize, usize)>)> = self.by_trigger.iter().filter(|(_, h)| h.len() > 1).collect(); chords.sort_by_key(|(t, _)| **t); @@ -609,7 +609,7 @@ impl Keymap { } /// The conflicts [`Keymap::conflicts`] reports for one command's bindings, with that command - /// as `a`, in the order of its bindings, then catalogue order. Empty for an unknown command. + /// as `a`, in the order of its bindings, then catalog order. Empty for an unknown command. pub fn conflicts_with(&self, command: &CommandRef) -> Vec { let Some(i) = self.find(command) else { return Vec::new() }; let mut out = Vec::new(); @@ -624,8 +624,8 @@ impl Keymap { let Some(clash) = self.conflict_relation(&a.1, &b.1) else { continue }; out.push(Conflict { chord, - a: (self.catalogue[i].command.clone(), self.public(i, a)), - b: (self.catalogue[j].command.clone(), self.public(j, b)), + a: (self.catalog[i].command.clone(), self.public(i, a)), + b: (self.catalog[j].command.clone(), self.public(j, b)), kind: if clash { ConflictKind::Clash } else { ConflictKind::Shadow }, in_defaults: self.defaults[i].contains(a) && self.defaults[j].contains(b), }); @@ -647,7 +647,7 @@ impl Keymap { out.push(Problem::DuplicateKey { key: key.to_string() }); continue; } - let home = &self.catalogue[i].scope; + let home = &self.catalog[i].scope; for text in texts { let (key, text) = (key.to_string(), text.clone()); match Binding::parse(&text) { @@ -666,7 +666,7 @@ impl Keymap { pub(crate) fn clashing(&self, command: &CommandRef, bindings: &[Binding]) -> Vec { let Some(i) = self.find(command) else { return Vec::new() }; let new: Vec = bindings.iter().map(|b| self.bound(i, b)).collect(); - self.clashes(i, &new).into_iter().map(|(j, b)| Holder { command: self.catalogue[j].command.clone(), binding: self.public(j, &b) }).collect() + self.clashes(i, &new).into_iter().map(|(j, b)| Holder { command: self.catalog[j].command.clone(), binding: self.public(j, &b) }).collect() } /// Whether binding `x` of command `a` and binding `y` of another command `b` clash, by the @@ -694,11 +694,11 @@ impl Keymap { } fn bound(&self, i: usize, binding: &Binding) -> Bound { - (binding.trigger, binding.scope_or(&self.catalogue[i].scope).clone()) + (binding.trigger, binding.scope_or(&self.catalog[i].scope).clone()) } fn public(&self, i: usize, (trigger, scope): &Bound) -> Binding { - let scope = (*scope != self.catalogue[i].scope).then(|| scope.clone()); + let scope = (*scope != self.catalog[i].scope).then(|| scope.clone()); Binding { trigger: *trigger, scope } } @@ -724,7 +724,7 @@ impl Keymap { } fn same_group(&self, i: usize, j: usize) -> bool { - match (&self.catalogue[i].kind, &self.catalogue[j].kind) { + match (&self.catalog[i].kind, &self.catalog[j].kind) { (Kind::Tool { group: a }, Kind::Tool { group: b }) => a == b, _ => false, } @@ -774,7 +774,7 @@ impl Keymap { let mut group_of: HashMap<(&Scope, Option<&Option>), usize> = HashMap::new(); for (pos, &(i, k)) in holders.iter().enumerate() { let Some(b) = self.at(i, k) else { continue }; - let tools = match &self.catalogue[i].kind { + let tools = match &self.catalog[i].kind { Kind::Tool { group } => Some(group), _ => None, }; @@ -814,8 +814,8 @@ impl Keymap { for (_, _, clash, (i, a), (j, b)) in found { out.push(Conflict { chord, - a: (self.catalogue[i].command.clone(), self.public(i, a)), - b: (self.catalogue[j].command.clone(), self.public(j, b)), + a: (self.catalog[i].command.clone(), self.public(i, a)), + b: (self.catalog[j].command.clone(), self.public(j, b)), kind: if clash { ConflictKind::Clash } else { ConflictKind::Shadow }, in_defaults: self.defaults[i].contains(a) && self.defaults[j].contains(b), }); @@ -830,13 +830,13 @@ impl Keymap { if let Some((t, _)) = new.iter().find(|(t, _)| self.is_reserved(&t.chord)) { return Err(AssignError::Reserved(*t)); } - let home = &self.catalogue[i].scope; + let home = &self.catalog[i].scope; if let Some((_, s)) = new.iter().find(|(_, s)| !self.usable_scope(s, home)) { return Err(AssignError::UnknownScope(s.clone())); } let clashes = self.clashes(i, new); let holders: Vec = - clashes.iter().map(|(j, b)| Holder { command: self.catalogue[*j].command.clone(), binding: self.public(*j, b) }).collect(); + clashes.iter().map(|(j, b)| Holder { command: self.catalog[*j].command.clone(), binding: self.public(*j, b) }).collect(); let mut done = Assigned::default(); let mut writes: Vec<(usize, Vec)> = Vec::new(); match policy { @@ -890,7 +890,7 @@ impl Keymap { kept.truncate(MAX_BINDINGS.saturating_sub(list.len())); self.remove_entries(i); if !kept.is_empty() || !self.is_default(i, &list) { - let home = &self.catalogue[i].scope; + let home = &self.catalog[i].scope; let mut texts: Vec = list.iter().map(|b| self.public(i, b).text(home)).collect(); texts.extend(kept); if self.overrides.insert(self.keys[i].clone(), texts) { @@ -930,7 +930,7 @@ impl Keymap { /// version, a scope this app lacks, a chord this platform reserves. fn unusable_texts(&self, i: usize) -> Vec { let Some(texts) = self.stored[i].as_deref().and_then(|key| self.overrides.get(key)) else { return Vec::new() }; - let home = &self.catalogue[i].scope; + let home = &self.catalog[i].scope; texts.iter().filter(|t| !Binding::parse(t).is_ok_and(|b| self.usable(&b, home))).cloned().collect() } @@ -985,7 +985,7 @@ impl Keymap { if !taken.insert(i) { continue; } - let home = &self.catalogue[i].scope; + let home = &self.catalog[i].scope; let usable = texts.iter().filter_map(|t| Binding::parse(t).ok()).filter(|b| self.usable(b, home)); let list = self.normalize(usable, home); // An entry none of whose texts is usable here (a key name from a newer version, a scope diff --git a/crates/keymap/src/lib.rs b/crates/keymap/src/lib.rs index e673848c7..9fbcfa2ea 100644 --- a/crates/keymap/src/lib.rs +++ b/crates/keymap/src/lib.rs @@ -5,7 +5,7 @@ //! [`chord`] holds the key and modifier types, the canonical text form that settings and control //! protocols store, display text per platform, and a reader for other applications' key text. //! [`command`] names what a binding runs, [`scope`] where it works, and [`keymap`] holds an app's -//! catalogue with default bindings, the user's [`Overrides`], dispatch ([`Keymap::lookup`]), +//! catalog with default bindings, the user's [`Overrides`], dispatch ([`Keymap::lookup`]), //! editing and conflicts. [`reserved`] lists the chords each operating system takes; a keymap //! reserves no chord unless the app opts in with [`Keymap::with_reserved`], e.g. //! `with_reserved(reserved::system(platform))`. [`import`] brings in other applications' shortcut @@ -22,7 +22,7 @@ //! assert_eq!(chord.display(Platform::Windows), "Ctrl+Shift+Z"); //! ``` //! -//! # A catalogue and dispatch +//! # A catalog and dispatch //! //! The app lists every command it can bind. A command with parameters has the key //! `window.panel {"panel":"layers"}` in settings and reports. Tools of one group share a key and @@ -35,7 +35,7 @@ //! let key = |text: &str| Binding::parse(text).unwrap(); //! let layers = CommandRef::with_params("window.panel", json!({"panel": "layers"})); //! let select = Kind::Tool { group: Some("select".into()) }; -//! let catalogue = vec![ +//! let catalog = vec![ //! Bindable::new("file.save", "Save", Scope::app()).with_path(vec!["File".into(), "Save".into()]).with_default(key("Cmd+S")), //! Bindable::new(layers.clone(), "Layers", Scope::app()).with_path(vec!["Window".into(), "Layers".into()]).with_default(key("F7")), //! Bindable::new("tool.marquee", "Marquee Tool", Scope::app()).with_kind(select.clone()).with_default(key("M")), @@ -46,7 +46,7 @@ //! // An app command whose binding works only in the Text context. //! Bindable::new("type.bold", "Bold", Scope::app()).with_default(key("Text: Cmd+B")), //! ]; -//! let keymap = Keymap::new(catalogue, Scopes::new().with_panel("Timeline").with_context("Text"), Platform::Mac); +//! let keymap = Keymap::new(catalog, Scopes::new().with_panel("Timeline").with_context("Text"), Platform::Mac); //! assert_eq!(layers.key(), r#"window.panel {"panel":"layers"}"#); //! //! // Dispatch: the chord pressed, whether it is a double press, and what has the keyboard. @@ -87,9 +87,9 @@ //! const SCHEMA_VERSION: u32 = 1; //! } //! -//! # let catalogue = Vec::new(); +//! # let catalog = Vec::new(); //! let (mut store, _report) = SettingsStore::::open(Location::Auto); -//! let mut keymap = Keymap::new(catalogue, Scopes::new(), Platform::current()).with_overrides(store.get().shortcuts.clone()); +//! let mut keymap = Keymap::new(catalog, Scopes::new(), Platform::current()).with_overrides(store.get().shortcuts.clone()); //! // Entries for unknown commands and texts that do not parse are kept and listed here. //! let _problems = keymap.problems(); //! diff --git a/crates/keymap/tests/egui.rs b/crates/keymap/tests/egui.rs index 567a852e7..04a4ee518 100644 --- a/crates/keymap/tests/egui.rs +++ b/crates/keymap/tests/egui.rs @@ -78,7 +78,7 @@ const CTRL: Modifiers = Modifiers { ctrl: true, command: true, ..Modifiers::NONE fn dispatch_keymap() -> Keymap { let app = |id: &str, keys: &[&str]| keys.iter().fold(Bindable::new(id, id, Scope::app()), |e, k| e.with_default(Binding::parse(k).unwrap())); let tool = |id: &str| app(id, &["M"]).with_kind(Kind::Tool { group: Some("select".into()) }); - let catalogue = vec![ + let catalog = vec![ app("edit.copy", &["Cmd+C", "Cmd+Insert"]), app("edit.paste", &["Cmd+V", "Shift+Insert"]), app("app.quit", &["Cmd+Alt+Q"]), @@ -94,7 +94,7 @@ fn dispatch_keymap() -> Keymap { app("reveal.one", &["U"]), app("reveal.all", &["U U"]), ]; - Keymap::new(catalogue, Scopes::new().with_panel("Timeline"), Platform::Windows) + Keymap::new(catalog, Scopes::new().with_panel("Timeline"), Platform::Windows) } fn press(key: EguiKey, modifiers: Modifiers) -> Event { diff --git a/crates/keymap/tests/import.rs b/crates/keymap/tests/import.rs index 586e02dfb..e1d72833f 100644 --- a/crates/keymap/tests/import.rs +++ b/crates/keymap/tests/import.rs @@ -34,7 +34,7 @@ fn panel(name: &str) -> CommandRef { CommandRef::with_params("window.panel", json!({ "panel": name })) } -fn catalogue() -> Vec { +fn catalog() -> Vec { vec![ command("file.new", "Document…", &["File", "New", "Document…"], &["Cmd+N"]), command("dialog.newDocument", "New Document Dialog", &[], &["Cmd+N"]), @@ -65,7 +65,7 @@ fn catalogue() -> Vec { } fn keymap(platform: Platform) -> Keymap { - Keymap::new(catalogue(), Scopes::new().with_context("Text"), platform).with_reserved(reserved::system(platform)) + Keymap::new(catalog(), Scopes::new().with_context("Text"), platform).with_reserved(reserved::system(platform)) } fn key(flavor: Flavor, context: &str, text: &str) -> ForeignKey { @@ -139,7 +139,7 @@ fn has(km: &Keymap, id: impl Into, texts: &[&str]) { } #[test] -fn labels_normalise_for_matching() { +fn labels_normalize_for_matching() { assert_eq!(normalize_label("Check Spelling..."), "check spelling"); assert_eq!(normalize_label("Check Spelling…"), "check spelling"); assert_eq!(normalize_label("Grids && Guides"), "grids guides"); @@ -152,7 +152,7 @@ fn labels_normalise_for_matching() { fn every_match_step_finds_its_command() { let (km, r) = import_windows(); assert_eq!(r.set.as_deref(), Some("My Set")); - // 1: full path, with `&`, case and spacing normalised, and Show/Hide dropped for a toggle. + // 1: full path, with `&`, case and spacing normalized, and Show/Hide dropped for a toggle. has(&km, "view.guides", &["Cmd+Alt+;"]); // 2: joined segments `Text Frame Options` in Object. has(&km, "object.textFrameOptions", &["Cmd+Alt+B"]); @@ -463,12 +463,12 @@ fn hostile_sets_are_capped_and_counted() { #[test] #[ignore = "worst-case timing; run with --ignored"] fn hostile_sets_finish_in_time() { - // A full catalogue whose labels share words with every unmatched entry below, so each + // A full catalog whose labels share words with every unmatched entry below, so each // suggestion scores every command. - let mut catalogue = catalogue(); - let filler = MAX_COMMANDS - catalogue.len(); - catalogue.extend((0..filler).map(|i| command(format!("filler.c{i}").as_str(), &format!("Filler Command {i}"), &[], &[]))); - let mut km = Keymap::new(catalogue, Scopes::new().with_context("Text"), Platform::Windows).with_reserved(reserved::system(Platform::Windows)); + let mut catalog = catalog(); + let filler = MAX_COMMANDS - catalog.len(); + catalog.extend((0..filler).map(|i| command(format!("filler.c{i}").as_str(), &format!("Filler Command {i}"), &[], &[]))); + let mut km = Keymap::new(catalog, Scopes::new().with_context("Text"), Platform::Windows).with_reserved(reserved::system(Platform::Windows)); let long: String = "ä€𝄞 x".repeat(MAX_IMPORT_TEXT); // Odd entries have keys and long labels that match nothing, so they reach the suggestions: // words in the whole label, or two words and symbols, which score high enough to suggest. @@ -593,8 +593,8 @@ fn report_json_uses_camel_case_names() { assert_eq!(v["changed"][0]["from"], json!(["Cmd+W"])); } -fn import_into(catalogue: Vec, entries: Vec, options: &ImportOptions) -> (Keymap, ImportReport) { - let mut km = Keymap::new(catalogue, Scopes::new(), Platform::Windows); +fn import_into(catalog: Vec, entries: Vec, options: &ImportOptions) -> (Keymap, ImportReport) { + let mut km = Keymap::new(catalog, Scopes::new(), Platform::Windows); let report = plan(&ForeignSet { name: None, entries }, &km, options).apply(&mut km); (km, report) } @@ -609,7 +609,7 @@ fn unmatched(r: &ImportReport) -> Vec<(&str, UnmatchedReason)> { #[test] fn panel_menu_entries_match_by_path_end_or_label() { - let catalogue = vec![ + let catalog = vec![ command("type.allCaps", "All Caps", &["Panels", "Character", "All Caps"], &[]), command("pages.overrideAll", "Override All Parent Items", &["Pages", "Override All Parent Page Items"], &[]), command("paragraph.justification", "Justification…", &[], &[]), @@ -637,10 +637,10 @@ fn panel_menu_entries_match_by_path_end_or_label() { panel_entry(&["Character", "Small Caps"], "Ctrl+F5"), // No path end fits and the label alone fits two commands. panel_entry(&["Color", "New Swatch"], "Ctrl+F6"), - // Without the mark, a path with no menu matches only a whole catalogue path. + // Without the mark, a path with no menu matches only a whole catalog path. entry(None, &["Character", "All Caps"], &[(d, "Ctrl+F7")], Flavor::Windows), ]; - let (km, r) = import_into(catalogue, entries, &default_context()); + let (km, r) = import_into(catalog, entries, &default_context()); has(&km, "type.allCaps", &["Cmd+F1"]); has(&km, "pages.overrideAll", &["Cmd+F2"]); has(&km, "paragraph.justification", &["Cmd+F3"]); @@ -659,7 +659,7 @@ fn panel_menu_entries_match_by_path_end_or_label() { #[test] fn aliases_match_like_labels() { - let catalogue = vec![ + let catalog = vec![ command("app.quit", "Quit DesignCraft", &["File", "Quit DesignCraft"], &[]).with_alias("Exit"), command("app.preferences", "Preferences…", &["Edit", "Preferences…"], &[]).with_alias("Preferences: General…"), command("type.bold", "Bold", &["Type", "Style", "Bold"], &[]).with_alias("Apply bold"), @@ -672,7 +672,7 @@ fn aliases_match_like_labels() { entry(None, &["Apply Bold"], &[(d, "Ctrl+Shift+B")], Flavor::Windows), win("Bearbeiten", &["Einfügen"], &[(d, "Ctrl+Shift+V")]), ]; - let (km, r) = import_into(catalogue, entries, &default_context()); + let (km, r) = import_into(catalog, entries, &default_context()); has(&km, "app.quit", &["Cmd+Q"]); has(&km, "app.preferences", &["Cmd+K"]); has(&km, "type.bold", &["Cmd+Shift+B"]); @@ -682,7 +682,7 @@ fn aliases_match_like_labels() { #[test] fn show_and_hide_are_read_off_only_for_toggles() { - let catalogue = vec![ + let catalog = vec![ command(panel("conveyor"), "Conveyor", &["Window", "Conveyor"], &[]), command("view.rulers", "Rulers", &["View", "Rulers"], &[]).toggle(), command("view.frameEdges", "Show Frame Edges", &["View", "Extras", "Show Frame Edges"], &[]).toggle(), @@ -700,7 +700,7 @@ fn show_and_hide_are_read_off_only_for_toggles() { win("Type", &["Show Hidden Characters"], &[(d, "Ctrl+Alt+I")]), win("Type", &["Hide Hidden Characters"], &[(d, "Ctrl+Alt+H")]), ]; - let (km, r) = import_into(catalogue, entries, &default_context()); + let (km, r) = import_into(catalog, entries, &default_context()); has(&km, panel("conveyor"), &[]); has(&km, "view.rulers", &["Cmd+R", "Cmd+Shift+R"]); has(&km, "view.frameEdges", &["Cmd+H"]); @@ -713,7 +713,7 @@ fn show_and_hide_are_read_off_only_for_toggles() { #[test] fn only_entries_with_keys_to_bind_count_toward_suggestions() { - let catalogue = vec![command("edit.checkSpelling", "Check Spelling…", &["Edit", "Check Spelling…"], &[])]; + let catalog = vec![command("edit.checkSpelling", "Check Spelling…", &["Edit", "Check Spelling…"], &[])]; let d = "Default"; // Twice the cap of unmatched entries without keys, or with keys only in a skipped context, // before one with a key. @@ -726,7 +726,7 @@ fn only_entries_with_keys_to_bind_count_toward_suggestions() { suggest: true, ..ImportOptions::default() }; - let (_, r) = import_into(catalogue, entries, &options); + let (_, r) = import_into(catalog, entries, &options); assert_eq!(r.unmatched_without_shortcut, 2 * MAX_SUGGESTIONS); assert_eq!(r.unmatched.len(), 1); assert_eq!(r.unmatched[0].keys, "Default: Ctrl+K", "keys in a skipped context are left out"); @@ -735,7 +735,7 @@ fn only_entries_with_keys_to_bind_count_toward_suggestions() { assert_eq!(r.truncated, 0); } -fn pages_catalogue() -> Vec { +fn pages_catalog() -> Vec { vec![ command("app.newDocumentDialog", "New Document…", &["File", "New Document…"], &["Cmd+N"]), command("layout.pages.insert", "Insert Pages…", &["Layout", "Pages", "Insert Pages…"], &["Cmd+Shift+P"]), @@ -754,7 +754,7 @@ fn panel_menu_entries_without_keys_change_nothing() { // The same for the last segment alone, with a panel the app has. none(&["Pages", "New Document"]), ]; - let (km, r) = import_into(pages_catalogue(), entries, &default_context()); + let (km, r) = import_into(pages_catalog(), entries, &default_context()); has(&km, "app.newDocumentDialog", &["Cmd+N"]); has(&km, "layout.pages.insert", &["Cmd+Shift+P"]); assert!(r.changed.is_empty(), "{:?}", r.changed); @@ -781,7 +781,7 @@ fn an_entry_without_keys_never_clears_keys_another_entry_gives() { let keyed = || win("Layout", &["Pages", "Insert Pages..."], &[(d, "Ctrl+Alt+P")]); let keyless = || win("Layout", &["Insert Pages..."], &[]); for entries in [vec![keyed(), keyless()], vec![keyless(), keyed()]] { - let (km, _) = import_into(pages_catalogue(), entries, &default_context()); + let (km, _) = import_into(pages_catalog(), entries, &default_context()); has(&km, "layout.pages.insert", &["Cmd+Alt+P"]); } @@ -790,14 +790,14 @@ fn an_entry_without_keys_never_clears_keys_another_entry_gives() { ForeignEntry::new(None, ["Pages", "Insert Pages..."]).in_panel_menu(), win("Layout", &["Pages", "Insert Pages..."], &[(d, "Ctrl+Shift+P")]), ]; - let (km, r) = import_into(pages_catalogue(), entries, &default_context()); + let (km, r) = import_into(pages_catalog(), entries, &default_context()); has(&km, "layout.pages.insert", &["Cmd+Shift+P"]); assert_eq!(r.matched_without_change.len(), 1); // The later entry still takes the chord from another command; the entry without keys does // not clear the command that lost it. let entries = vec![keyless(), keyed(), win("File", &["Close"], &[(d, "Ctrl+Alt+P")])]; - let (km, r) = import_into(pages_catalogue(), entries, &default_context()); + let (km, r) = import_into(pages_catalog(), entries, &default_context()); has(&km, "file.close", &["Cmd+Alt+P"]); has(&km, "layout.pages.insert", &["Cmd+Shift+P"]); assert_eq!(r.skipped.iter().map(|s| (s.command.id.as_str(), s.reason)).collect::>(), [("layout.pages.insert", SkipReason::Taken)]); diff --git a/crates/keymap/tests/keymap.rs b/crates/keymap/tests/keymap.rs index 502c3cedc..3a8a24831 100644 --- a/crates/keymap/tests/keymap.rs +++ b/crates/keymap/tests/keymap.rs @@ -54,14 +54,14 @@ fn command_keys_are_canonical_whatever_the_map_order() { #[test] fn lookup_picks_the_nearest_scope() { - let catalogue = vec![ + let catalog = vec![ app("edit.copy", &["Cmd+C"]), in_scope("timeline.copy", "Timeline", &["Cmd+C"]), app("file.bake", &["Cmd+B"]), in_scope("text.bold", "Text", &["Cmd+B", "Cmd+I"]), in_scope("timeline.loop", "Timeline", &["L"]), ]; - let km = Keymap::new(catalogue.clone(), scopes(), Platform::Mac); + let km = Keymap::new(catalog.clone(), scopes(), Platform::Mac); let text = ["Text"]; assert_eq!(press(&km, "Cmd+C", &Active::NONE), run("edit.copy")); assert_eq!(press(&km, "Cmd+C", &Active::panel("Timeline")), run("timeline.copy")); @@ -73,14 +73,14 @@ fn lookup_picks_the_nearest_scope() { assert_eq!(press(&km, "L", &Active::panel("Effects")), run("timeline.loop"), "fallthrough"); assert_eq!(km.lookup(&chord("L"), true, &Active::panel("Timeline")), Lookup::None, "double press is its own trigger"); - let strict = Keymap::new(catalogue, scopes().with_panel_fallthrough(false), Platform::Mac); + let strict = Keymap::new(catalog, scopes().with_panel_fallthrough(false), Platform::Mac); assert_eq!(press(&strict, "L", &Active::panel("Effects")), Lookup::None); assert_eq!(press(&strict, "L", &Active::panel("Timeline")), run("timeline.loop")); } #[test] fn typing_rules_decide_what_fires_in_a_text_field() { - let catalogue = vec![app("tool.brush", &["B"]), app("edit.copy", &["Cmd+C"]), app("help", &["F1"]), app("view.alt", &["Alt+V"])]; + let catalog = vec![app("tool.brush", &["B"]), app("edit.copy", &["Cmd+C"]), app("help", &["F1"]), app("view.alt", &["Alt+V"])]; let typing = Active { panel: None, contexts: &[], typing: true }; let cases = [ (TypingRule::PlainKeysWait, [false, true, true, true]), @@ -88,7 +88,7 @@ fn typing_rules_decide_what_fires_in_a_text_field() { (TypingRule::AllWait, [false, false, false, false]), ]; for (rule, fires) in cases { - let km = Keymap::new(catalogue.clone(), Scopes::new(), Platform::Windows).with_typing_rule(rule); + let km = Keymap::new(catalog.clone(), Scopes::new(), Platform::Windows).with_typing_rule(rule); for ((key, id), fire) in [("B", "tool.brush"), ("Cmd+C", "edit.copy"), ("F1", "help"), ("Alt+V", "view.alt")].into_iter().zip(fires) { let want = if fire { run(id) } else { Lookup::None }; assert_eq!(press(&km, key, &typing), want, "{rule:?} {key}"); @@ -99,7 +99,7 @@ fn typing_rules_decide_what_fires_in_a_text_field() { #[test] fn bindings_of_an_active_context_fire_while_typing_under_every_rule() { - let catalogue = vec![ + let catalog = vec![ app("text.bold", &["Text: Cmd+B", "Text: B"]), app("file.bake", &["Cmd+B"]), in_scope("timeline.cut", "Timeline", &["Cmd+K"]), @@ -107,7 +107,7 @@ fn bindings_of_an_active_context_fire_while_typing_under_every_rule() { ]; let editing = Active { panel: Some("Timeline"), contexts: &["Text"], typing: true }; let elsewhere = Active { contexts: &[], ..editing }; - let km = Keymap::new(catalogue, scopes(), Platform::Mac).with_typing_rule(TypingRule::AllWait); + let km = Keymap::new(catalog, scopes(), Platform::Mac).with_typing_rule(TypingRule::AllWait); assert_eq!(press(&km, "Cmd+B", &editing), run("text.bold")); assert_eq!(press(&km, "B", &editing), run("text.bold")); assert_eq!(press(&km, "Cmd+K", &editing), Lookup::None, "panel bindings wait"); @@ -134,8 +134,8 @@ fn tools_of_one_group_cycle_and_keep_their_shared_key() { #[test] fn steal_keep_and_refuse() { - let catalogue = vec![app("edit.copy", &["Cmd+C"]), app("edit.duplicate", &["Cmd+D"]), in_scope("timeline.copy", "Timeline", &[])]; - let mut km = Keymap::new(catalogue, scopes(), Platform::Mac); + let catalog = vec![app("edit.copy", &["Cmd+C"]), app("edit.duplicate", &["Cmd+D"]), in_scope("timeline.copy", "Timeline", &[])]; + let mut km = Keymap::new(catalog, scopes(), Platform::Mac); let dup = cmd("edit.duplicate"); let err = km.assign(&dup, b("Cmd+C"), Policy::Refuse).unwrap_err(); @@ -174,8 +174,8 @@ fn twins_keep_their_shared_default_key() { #[test] fn clearing_a_command_frees_its_panel_copies() { // filmcraft#1333: New Bin holds Cmd+B in the application and in the Project panel. - let catalogue = vec![app("project.newBin", &["Cmd+B", "Project: Cmd+B"]), app("clip.bold", &[])]; - let mut km = Keymap::new(catalogue, Scopes::new().with_panel("Project"), Platform::Mac); + let catalog = vec![app("project.newBin", &["Cmd+B", "Project: Cmd+B"]), app("clip.bold", &[])]; + let mut km = Keymap::new(catalog, Scopes::new().with_panel("Project"), Platform::Mac); assert_eq!(press(&km, "Cmd+B", &Active::panel("Project")), run("project.newBin")); assert!(km.clear(&cmd("project.newBin"))); assert!(km.bindings(&cmd("project.newBin")).is_empty()); @@ -185,25 +185,25 @@ fn clearing_a_command_frees_its_panel_copies() { #[test] fn reserved_chords_are_refused() { - let catalogue = vec![app("view.next", &[])]; - let mut mac = Keymap::new(catalogue.clone(), Scopes::new(), Platform::Mac).with_reserved(reserved::system(Platform::Mac)); + let catalog = vec![app("view.next", &[])]; + let mut mac = Keymap::new(catalog.clone(), Scopes::new(), Platform::Mac).with_reserved(reserved::system(Platform::Mac)); let err = mac.assign(&cmd("view.next"), b("Cmd+Tab"), Policy::Steal).unwrap_err(); assert_eq!(err, AssignError::Reserved(Trigger::parse("Cmd+Tab").unwrap())); - let mut win = Keymap::new(catalogue.clone(), Scopes::new(), Platform::Windows).with_reserved(reserved::system(Platform::Windows)); + let mut win = Keymap::new(catalog.clone(), Scopes::new(), Platform::Windows).with_reserved(reserved::system(Platform::Windows)); assert!(matches!(win.assign(&cmd("view.next"), b("Ctrl+Alt+Delete"), Policy::Steal), Err(AssignError::Reserved(_)))); assert!(reserved::system(Platform::Linux).contains(&chord("Cmd+Alt+F12"))); let mut o = Overrides::new(); o.insert("view.next", vec!["Alt+F4".into()]); - let linux = Keymap::new(catalogue, Scopes::new(), Platform::Linux).with_reserved(reserved::system(Platform::Linux)).with_overrides(o); + let linux = Keymap::new(catalog, Scopes::new(), Platform::Linux).with_reserved(reserved::system(Platform::Linux)).with_overrides(o); assert!(linux.bindings(&cmd("view.next")).is_empty()); assert_eq!(linux.problems(), vec![Problem::Reserved { key: "view.next".into(), text: "Alt+F4".into() }]); } #[test] fn conflicts_tell_clashes_from_shadows() { - let catalogue = vec![ + let catalog = vec![ app("edit.copy", &["Cmd+C"]), app("color.copy", &["Cmd+C"]), in_scope("timeline.copy", "Timeline", &["Cmd+C"]), @@ -214,7 +214,7 @@ fn conflicts_tell_clashes_from_shadows() { in_scope("render.find", "Render", &["Cmd+R"]), in_scope("effects.render", "Effects", &["Cmd+R"]), ]; - let mut km = Keymap::new(catalogue, scopes(), Platform::Mac); + let mut km = Keymap::new(catalog, scopes(), Platform::Mac); let summary = |km: &Keymap| -> Vec<(String, String, String, ConflictKind, bool)> { km.conflicts().into_iter().map(|c| (c.chord.to_string(), c.a.0.id, c.b.0.id, c.kind, c.in_defaults)).collect() }; @@ -254,7 +254,7 @@ fn conflicts_tell_clashes_from_shadows() { assert_eq!(with("edit.copy"), [w("Cmd+C", "color.copy", ConflictKind::Clash), w("Cmd+C", "timeline.copy", ConflictKind::Shadow)]); assert_eq!(with("edit.cut"), [w("Cmd+X", "text.cut", ConflictKind::Shadow), w("Cmd+D", "edit.find", ConflictKind::Clash)]); assert!(with("nope").is_empty()); - for entry in km.catalogue() { + for entry in km.catalog() { let id = entry.command.id.as_str(); let mut direct: Vec<_> = km.conflicts_with(&entry.command).into_iter().map(|c| (c.chord, c.a.0.id, c.b.0.id, c.kind, c.in_defaults)).collect(); @@ -275,18 +275,18 @@ fn conflicts_tell_clashes_from_shadows() { assert_eq!(direct, filtered, "{id}"); } - let strict = Keymap::new(km.catalogue().to_vec(), scopes().with_panel_fallthrough(false), Platform::Mac); + let strict = Keymap::new(km.catalog().to_vec(), scopes().with_panel_fallthrough(false), Platform::Mac); assert!(!strict.conflicts().iter().any(|c| c.chord.to_string() == "Cmd+R")); } /// `commands` commands, each with 16 bindings on one chord in 16 panels. fn crowded(commands: usize, scopes: Scopes, kind: Kind) -> (Keymap, Overrides) { - let catalogue: Vec = (0..commands).map(|n| app(&format!("c.{n}"), &[]).with_kind(kind.clone())).collect(); + let catalog: Vec = (0..commands).map(|n| app(&format!("c.{n}"), &[]).with_kind(kind.clone())).collect(); let mut o = Overrides::new(); for n in 0..commands { assert!(o.insert(format!("c.{n}"), (1..=MAX_BINDINGS).map(|p| format!("P{p}: K")).collect())); } - (Keymap::new(catalogue, scopes, Platform::Mac), o) + (Keymap::new(catalog, scopes, Platform::Mac), o) } fn panels(n: usize) -> Scopes { @@ -344,8 +344,8 @@ fn crowded_chords_stay_fast() { #[test] fn assigning_many_commands_stays_fast() { - let catalogue: Vec = (0..MAX_COMMANDS).map(|n| app(&format!("c.{n}"), &[])).collect(); - let mut km = Keymap::new(catalogue, panels(MAX_BINDINGS), Platform::Mac); + let catalog: Vec = (0..MAX_COMMANDS).map(|n| app(&format!("c.{n}"), &[])).collect(); + let mut km = Keymap::new(catalog, panels(MAX_BINDINGS), Platform::Mac); let list: Vec = (1..=MAX_BINDINGS).map(|p| b(&format!("P{p}: K"))).collect(); let t = Instant::now(); for n in 0..MAX_COMMANDS { @@ -377,14 +377,14 @@ fn binding_text_round_trips_for_every_key() { #[test] fn edits_are_refused_when_the_overrides_are_full() { - let catalogue = vec![app("edit.copy", &["Cmd+C"]), app("edit.duplicate", &["Cmd+D"]), app("edit.cut", &[])]; + let catalog = vec![app("edit.copy", &["Cmd+C"]), app("edit.duplicate", &["Cmd+D"]), app("edit.cut", &[])]; let mut o = Overrides::new(); o.insert("edit.cut", vec!["Cmd+X".into()]); for n in 1..MAX_COMMANDS { o.insert(format!("junk.{n}"), vec![]); } assert_eq!(o.len(), MAX_COMMANDS); - let mut km = Keymap::new(catalogue, Scopes::new(), Platform::Mac).with_overrides(o.clone()); + let mut km = Keymap::new(catalog, Scopes::new(), Platform::Mac).with_overrides(o.clone()); let (copy, dup, cut) = (cmd("edit.copy"), cmd("edit.duplicate"), cmd("edit.cut")); assert_eq!(km.assign(&dup, b("Cmd+K"), Policy::Steal), Err(AssignError::Full)); @@ -405,11 +405,11 @@ fn edits_are_refused_when_the_overrides_are_full() { #[test] fn bindings_in_unknown_scopes_are_refused() { - let catalogue = vec![app("edit.copy", &["Cmd+C"]), in_scope("timeline.mark", "Timeline", &["M"])]; - let mut km = Keymap::new(catalogue, Scopes::new().with_context("Text"), Platform::Mac); + let catalog = vec![app("edit.copy", &["Cmd+C"]), in_scope("timeline.mark", "Timeline", &["M"])]; + let mut km = Keymap::new(catalog, Scopes::new().with_context("Text"), Platform::Mac); let copy = cmd("edit.copy"); assert_eq!(km.assign(©, b("Nowhere: Cmd+K"), Policy::Steal), Err(AssignError::UnknownScope(scope("Nowhere")))); - assert!(km.assign(©, b("Timeline: Cmd+K"), Policy::Steal).is_ok(), "a catalogue scope"); + assert!(km.assign(©, b("Timeline: Cmd+K"), Policy::Steal).is_ok(), "a catalog scope"); assert!(km.assign(©, b("Text: Cmd+K"), Policy::Steal).is_ok(), "a registered scope"); let mut o = Overrides::new(); @@ -421,11 +421,11 @@ fn bindings_in_unknown_scopes_are_refused() { #[test] fn unreadable_entries_keep_the_defaults() { - let catalogue = vec![app("edit.copy", &["Cmd+C"]), app("edit.paste", &["Cmd+V"])]; + let catalog = vec![app("edit.copy", &["Cmd+C"]), app("edit.paste", &["Cmd+V"])]; let mut o = Overrides::new(); o.insert("edit.copy", vec!["Cmd+Nope".into()]); o.insert("edit.paste", vec![]); - let mut km = Keymap::new(catalogue, Scopes::new(), Platform::Mac).with_overrides(o); + let mut km = Keymap::new(catalog, Scopes::new(), Platform::Mac).with_overrides(o); assert_eq!(km.bindings(&cmd("edit.copy")), vec![b("Cmd+C")]); assert!(km.bindings(&cmd("edit.paste")).is_empty()); assert_eq!(km.overrides().get("edit.copy"), Some(&["Cmd+Nope".to_string()][..]), "verbatim"); @@ -435,13 +435,13 @@ fn unreadable_entries_keep_the_defaults() { #[test] fn entries_with_nothing_usable_keep_the_defaults() { - let catalogue = vec![app("edit.copy", &["Cmd+C"]), app("edit.cut", &["Cmd+X"]), app("edit.paste", &["Cmd+V"]), app("edit.undo", &["Cmd+Z"])]; + let catalog = vec![app("edit.copy", &["Cmd+C"]), app("edit.cut", &["Cmd+X"]), app("edit.paste", &["Cmd+V"]), app("edit.undo", &["Cmd+Z"])]; let mut o = Overrides::new(); o.insert("edit.copy", vec!["Nowhere: Cmd+K".into()]); o.insert("edit.cut", vec!["Alt+F4".into()]); o.insert("edit.paste", vec!["Nowhere: Cmd+K".into(), "Alt+F4".into(), "Cmd+J".into()]); o.insert("edit.undo", vec![]); - let km = Keymap::new(catalogue, Scopes::new(), Platform::Linux).with_reserved(reserved::system(Platform::Linux)).with_overrides(o); + let km = Keymap::new(catalog, Scopes::new(), Platform::Linux).with_reserved(reserved::system(Platform::Linux)).with_overrides(o); assert_eq!(km.bindings(&cmd("edit.copy")), vec![b("Cmd+C")], "only an unknown scope"); assert_eq!(km.bindings(&cmd("edit.cut")), vec![b("Cmd+X")], "only a reserved chord"); assert_eq!(km.bindings(&cmd("edit.paste")), vec![b("Cmd+J")]); @@ -450,8 +450,8 @@ fn entries_with_nothing_usable_keep_the_defaults() { #[test] fn overrides_hold_only_what_differs_from_the_defaults() { - let catalogue = vec![app("edit.copy", &["Cmd+C"]), in_scope("timeline.mark", "Timeline", &["M"])]; - let mut km = Keymap::new(catalogue, scopes(), Platform::Mac); + let catalog = vec![app("edit.copy", &["Cmd+C"]), in_scope("timeline.mark", "Timeline", &["M"])]; + let mut km = Keymap::new(catalog, scopes(), Platform::Mac); let copy = cmd("edit.copy"); km.assign(©, b("Timeline: Cmd+K"), Policy::Steal).unwrap(); assert_eq!(km.overrides().get("edit.copy"), Some(&["Cmd+C".to_string(), "Timeline: Cmd+K".to_string()][..])); @@ -468,10 +468,10 @@ fn overrides_hold_only_what_differs_from_the_defaults() { #[test] fn edits_keep_the_texts_this_build_cannot_use() { - let catalogue = vec![app("file.quit", &["Cmd+Q"]), app("file.close", &["Cmd+W"]), app("file.save", &["Cmd+S"])]; + let catalog = vec![app("file.quit", &["Cmd+Q"]), app("file.close", &["Cmd+W"]), app("file.save", &["Cmd+S"])]; let mut o = Overrides::new(); o.insert("file.quit", vec!["Cmd+Q".into(), "Cmd+FutureKey".into(), "Nowhere: Cmd+J".into()]); - let mut km = Keymap::new(catalogue.clone(), scopes(), Platform::Mac).with_overrides(o); + let mut km = Keymap::new(catalog.clone(), scopes(), Platform::Mac).with_overrides(o); let quit = cmd("file.quit"); let texts = |km: &Keymap| km.overrides().get("file.quit").map(<[String]>::to_vec); let strings = |t: &[&str]| Some(t.iter().map(|s| s.to_string()).collect::>()); @@ -480,7 +480,7 @@ fn edits_keep_the_texts_this_build_cannot_use() { assert_eq!(texts(&km), strings(&["Cmd+Q", "Cmd+W", "Cmd+FutureKey", "Nowhere: Cmd+J"])); km.assign(&cmd("file.save"), b("Cmd+Q"), Policy::Steal).unwrap(); assert_eq!(texts(&km), strings(&["Cmd+W", "Cmd+FutureKey", "Nowhere: Cmd+J"]), "taken by a Steal"); - let reloaded = Keymap::new(catalogue, scopes(), Platform::Mac).with_overrides(km.overrides().clone()); + let reloaded = Keymap::new(catalog, scopes(), Platform::Mac).with_overrides(km.overrides().clone()); assert_eq!(reloaded.bindings(&quit), vec![b("Cmd+W")]); // An entry of only such texts would load as the defaults, so a cleared command drops them. @@ -500,17 +500,17 @@ fn an_override_equal_to_the_defaults_on_this_platform_is_not_stored() { #[test] fn an_empty_text_in_the_map_form_removes_the_shortcut() { - let catalogue = vec![app("edit.copy", &["Cmd+C"]), app("edit.paste", &["Cmd+V"]), app("edit.cut", &["Cmd+X"])]; + let catalog = vec![app("edit.copy", &["Cmd+C"]), app("edit.paste", &["Cmd+V"]), app("edit.cut", &["Cmd+X"])]; let o: Overrides = serde_json::from_str(r#"{"edit.copy": "", "edit.paste": [""], "edit.cut": "Cmd+K"}"#).unwrap(); assert!(o.load_notes().is_empty(), "{:?}", o.load_notes()); - let km = Keymap::new(catalogue.clone(), Scopes::new(), Platform::Mac).with_overrides(o); + let km = Keymap::new(catalog.clone(), Scopes::new(), Platform::Mac).with_overrides(o); assert!(km.bindings(&cmd("edit.copy")).is_empty(), "a removed default stays removed"); assert!(km.bindings(&cmd("edit.paste")).is_empty()); assert_eq!(km.bindings(&cmd("edit.cut")), vec![b("Cmd+K")]); assert!(km.problems().is_empty()); let saved = serde_json::to_string(km.overrides()).unwrap(); - let again = Keymap::new(catalogue, Scopes::new(), Platform::Mac).with_overrides(serde_json::from_str(&saved).unwrap()); + let again = Keymap::new(catalog, Scopes::new(), Platform::Mac).with_overrides(serde_json::from_str(&saved).unwrap()); assert!(again.bindings(&cmd("edit.copy")).is_empty(), "{saved}"); } @@ -548,9 +548,9 @@ fn overrides_write_the_map_form_unless_a_command_has_several_keys() { #[test] fn ctrl_folds_into_cmd_off_macos() { - let catalogue = vec![app("edit.cut", &["Cmd+X"]), app("mac.cut", &["Ctrl+X"])]; - let win = Keymap::new(catalogue.clone(), Scopes::new(), Platform::Windows); - let mac = Keymap::new(catalogue, Scopes::new(), Platform::Mac); + let catalog = vec![app("edit.cut", &["Cmd+X"]), app("mac.cut", &["Ctrl+X"])]; + let win = Keymap::new(catalog.clone(), Scopes::new(), Platform::Windows); + let mac = Keymap::new(catalog, Scopes::new(), Platform::Mac); let conflicts = win.conflicts(); assert_eq!(conflicts.len(), 1); assert_eq!((conflicts[0].kind, conflicts[0].chord.to_string()), (ConflictKind::Clash, "Cmd+X".to_string())); @@ -606,12 +606,12 @@ fn hostile_overrides_load_without_panic_and_report_problems() { #[test] fn reset_removes_hand_written_variants_of_a_key() { let layers = CommandRef::with_params("window.panel", json!({"panel": "layers"})); - let catalogue = vec![Bindable::new(layers.clone(), "Layers", Scope::app()).with_default(b("F7"))]; + let catalog = vec![Bindable::new(layers.clone(), "Layers", Scope::app()).with_default(b("F7"))]; let load = || { let mut o = Overrides::new(); o.insert(r#"window.panel {"panel":"layers"}"#, vec!["Cmd+L".into()]); o.insert(r#"window.panel { "panel": "layers" }"#, vec!["Cmd+K".into()]); - Keymap::new(catalogue.clone(), Scopes::new(), Platform::Mac).with_overrides(o) + Keymap::new(catalog.clone(), Scopes::new(), Platform::Mac).with_overrides(o) }; let mut km = load(); assert_eq!(km.bindings(&layers), vec![b("Cmd+L")], "the canonical entry wins"); @@ -622,6 +622,6 @@ fn reset_removes_hand_written_variants_of_a_key() { let mut km = load(); km.set_bindings(&layers, vec![b("F7")], Policy::Steal).unwrap(); assert!(km.overrides().is_empty(), "{:?}", km.overrides()); - let again = Keymap::new(catalogue.clone(), Scopes::new(), Platform::Mac).with_overrides(km.overrides().clone()); + let again = Keymap::new(catalog.clone(), Scopes::new(), Platform::Mac).with_overrides(km.overrides().clone()); assert_eq!(again.bindings(&layers), vec![b("F7")]); } diff --git a/crates/keymap/tests/settings.rs b/crates/keymap/tests/settings.rs index 89c744bd0..c05c84486 100644 --- a/crates/keymap/tests/settings.rs +++ b/crates/keymap/tests/settings.rs @@ -33,13 +33,13 @@ fn open(dir: &std::path::Path) -> SettingsStore { } fn keymap(overrides: Overrides) -> Keymap { - let catalogue = vec![ + let catalog = vec![ Bindable::new(CommandRef::with_params("window.panel", json!({"panel": "layers"})), "Layers", Scope::app()), Bindable::new("text.bold", "Bold", Scope::app()), Bindable::new("edit.copy", "Copy", Scope::app()).with_default(Binding::parse("Cmd+C").unwrap()), Bindable::new("edit.paste", "Paste", Scope::app()).with_default(Binding::parse("Cmd+V").unwrap()), ]; - Keymap::new(catalogue, Scopes::new().with_context("Text"), Platform::Mac).with_overrides(overrides) + Keymap::new(catalog, Scopes::new().with_context("Text"), Platform::Mac).with_overrides(overrides) } #[test] From 9b0182a3e0af0cad054451d47913d2e510f21aff Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 04:18:35 +0000 Subject: [PATCH 19/32] keymap: a held web clipboard key with repeats off leaves its clipboard events in place --- crates/keymap/src/egui.rs | 6 ++++++ crates/keymap/tests/egui.rs | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/crates/keymap/src/egui.rs b/crates/keymap/src/egui.rs index fd5d27941..c89447d84 100644 --- a/crates/keymap/src/egui.rs +++ b/crates/keymap/src/egui.rs @@ -306,6 +306,12 @@ impl Dispatcher { } } } + // A repeat that does not run leaves its clipboard event in place with it. + Event::Key { pressed: true, repeat: true, .. } => { + if let Some((j, _)) = causes[i] { + caused_taken[j] = Some(false); + } + } Event::Text(_) if drop_text => { drop_text = false; continue; diff --git a/crates/keymap/tests/egui.rs b/crates/keymap/tests/egui.rs index 04a4ee518..b91e380f9 100644 --- a/crates/keymap/tests/egui.rs +++ b/crates/keymap/tests/egui.rs @@ -218,6 +218,18 @@ fn a_web_paste_carries_its_text_and_takes_its_event() { assert_eq!(input.events, events[..2]); } +#[test] +fn a_held_web_paste_runs_once_when_repeats_are_off() { + let km = dispatch_keymap(); + let mut d = Dispatcher::new().with_clipboard_events(true); + let repeat = Event::Key { key: EguiKey::V, physical_key: Some(EguiKey::V), pressed: true, repeat: true, modifiers: CTRL }; + let paste = || Event::Paste("text".into()); + let events = vec![press(EguiKey::V, CTRL), paste(), repeat.clone(), paste()]; + let (ran, left) = run(&mut d, &km, &Active::NONE, frame(1.0, CTRL, events)); + assert_eq!(ran, ["edit.paste"]); + assert_eq!(left, [repeat, paste()], "the repeat and its event stay in egui's input"); +} + #[test] fn declined_hits_leave_their_events_in_order() { let km = dispatch_keymap(); From 0da8ea8a9f12f76ec9527b0aaa3e1943eac8161d Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:07:49 +0000 Subject: [PATCH 20/32] keymap: run the workflow on craft-settings changes too --- .github/workflows/keymap.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/keymap.yml b/.github/workflows/keymap.yml index 97b1124e2..29bddad65 100644 --- a/.github/workflows/keymap.yml +++ b/.github/workflows/keymap.yml @@ -3,9 +3,9 @@ name: Keymap on: push: branches: [main] - paths: ["crates/keymap/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"] + paths: ["crates/keymap/**", "crates/settings/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"] pull_request: - paths: ["crates/keymap/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"] + paths: ["crates/keymap/**", "crates/settings/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"] workflow_dispatch: permissions: From 056a709d0fc1579f70ee08974ddf42ca130d3dde Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:08:43 +0000 Subject: [PATCH 21/32] keymap: refuse scope names with outer whitespace, which binding text trims --- crates/keymap/src/scope.rs | 12 ++++++++---- crates/keymap/tests/keymap.rs | 9 +++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/keymap/src/scope.rs b/crates/keymap/src/scope.rs index 287413c9b..26b94e496 100644 --- a/crates/keymap/src/scope.rs +++ b/crates/keymap/src/scope.rs @@ -9,17 +9,21 @@ pub const MAX_SCOPE_NAME: usize = 64; const APP: &str = "Application"; -/// The name of a scope. Never empty, at most [`MAX_SCOPE_NAME`] bytes, without `:`. +/// The name of a scope. Never empty, at most [`MAX_SCOPE_NAME`] bytes, without `:` or outer +/// whitespace. #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)] #[serde(transparent)] pub struct Scope(String); impl Scope { - /// `None` for an empty name, one over [`MAX_SCOPE_NAME`] bytes, or one with `:` or a control - /// character. + /// `None` for an empty name, one over [`MAX_SCOPE_NAME`] bytes, one with `:` or a control + /// character, or one with whitespace at either end, which binding text would lose. pub fn new(name: impl Into) -> Option { let name = name.into(); - let ok = !name.is_empty() && name.len() <= MAX_SCOPE_NAME && !name.chars().any(|c| c == ':' || c.is_control()); + let ok = !name.is_empty() + && name.len() <= MAX_SCOPE_NAME + && name.trim() == name + && !name.chars().any(|c| c == ':' || c.is_control()); ok.then_some(Scope(name)) } diff --git a/crates/keymap/tests/keymap.rs b/crates/keymap/tests/keymap.rs index 3a8a24831..74ba8d6e4 100644 --- a/crates/keymap/tests/keymap.rs +++ b/crates/keymap/tests/keymap.rs @@ -375,6 +375,15 @@ fn binding_text_round_trips_for_every_key() { assert_eq!(Binding::parse(": :"), Ok(Binding::new(Trigger::double(Chord::plain(Key::Colon))))); } +#[test] +fn scope_names_with_outer_whitespace_are_refused() { + for name in [" Timeline", "Timeline ", "\u{a0}Timeline", ""] { + assert_eq!(Scope::new(name), None, "{name:?}"); + } + assert_eq!(Scope::new("Time line").map(|s| s.to_string()).as_deref(), Some("Time line")); + assert_eq!(Binding::parse(" Timeline : K").map(|b| b.scope), Ok(Some(scope("Timeline")))); +} + #[test] fn edits_are_refused_when_the_overrides_are_full() { let catalog = vec![app("edit.copy", &["Cmd+C"]), app("edit.duplicate", &["Cmd+D"]), app("edit.cut", &[])]; From f4b04e4ad179eccfe7086def84640a235092315c Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:09:01 +0000 Subject: [PATCH 22/32] keymap: a double press needs both presses in the same panel --- crates/keymap/src/egui.rs | 15 ++++++++++----- crates/keymap/tests/egui.rs | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/crates/keymap/src/egui.rs b/crates/keymap/src/egui.rs index c89447d84..67438a757 100644 --- a/crates/keymap/src/egui.rs +++ b/crates/keymap/src/egui.rs @@ -189,11 +189,13 @@ impl Hit { } } -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Debug)] struct LastPress { chord: Chord, at: f64, ran_double: bool, + /// The focused panel: a press in another panel never completes the pair. + panel: Option, } /// Runs a keymap against egui's input, one call per frame before the UI reads its keys. @@ -251,8 +253,9 @@ impl Dispatcher { /// The commands this frame's key presses run with `active` focus, in press order. /// - /// A chord pressed again within [`DOUBLE_PRESS`] runs its double binding when it has one; - /// the first press has already run the single binding. The press after a double starts over. + /// A chord pressed again within [`DOUBLE_PRESS`] in the same panel runs its double binding + /// when it has one; the first press has already run the single binding. The press after a + /// double starts over. pub fn dispatch(&mut self, input: &mut InputState, keymap: &Keymap, active: &Active) -> Vec { self.dispatch_filtered(input, keymap, active, |_| true) } @@ -351,9 +354,11 @@ impl Dispatcher { if repeat { return find(false); } - let again = self.last.is_some_and(|l| l.chord == first && !l.ran_double && now >= l.at && now - l.at < DOUBLE_PRESS); + let again = self.last.as_ref().is_some_and(|l| { + l.chord == first && !l.ran_double && l.panel.as_deref() == active.panel && now >= l.at && now - l.at < DOUBLE_PRESS + }); let double = if again { find(true) } else { None }; - self.last = Some(LastPress { chord: first, at: now, ran_double: double.is_some() }); + self.last = Some(LastPress { chord: first, at: now, ran_double: double.is_some(), panel: active.panel.map(str::to_owned) }); double.or_else(|| find(false)) } } diff --git a/crates/keymap/tests/egui.rs b/crates/keymap/tests/egui.rs index b91e380f9..4cba357d5 100644 --- a/crates/keymap/tests/egui.rs +++ b/crates/keymap/tests/egui.rs @@ -354,6 +354,24 @@ fn a_second_press_runs_the_double_binding() { assert_eq!(u(&mut d, 2.7), ["reveal.one"]); } +#[test] +fn a_double_press_needs_both_presses_in_one_panel() { + let km = Keymap::new( + vec![ + Bindable::new("x.one", "One", Scope::new("X").unwrap()).with_default(Binding::parse("A").unwrap()), + Bindable::new("y.one", "One", Scope::new("Y").unwrap()).with_default(Binding::parse("A").unwrap()), + Bindable::new("y.two", "Two", Scope::new("Y").unwrap()).with_default(Binding::parse("A A").unwrap()), + ], + Scopes::new().with_panel("X").with_panel("Y").with_panel_fallthrough(false), + Platform::Windows, + ); + let mut d = Dispatcher::new(); + let a = |d: &mut Dispatcher, panel, t| run(d, &km, &Active::panel(panel), frame(t, Modifiers::NONE, vec![press(EguiKey::A, Modifiers::NONE)])).0; + assert_eq!(a(&mut d, "X", 1.0), ["x.one"]); + assert_eq!(a(&mut d, "Y", 1.2), ["y.one"]); + assert_eq!(a(&mut d, "Y", 1.4), ["y.two"]); +} + #[test] fn two_presses_in_one_frame_make_a_double() { let km = dispatch_keymap(); From 79747aeaae6c0ffcf79851078486ed5fca77baf9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:11:21 +0000 Subject: [PATCH 23/32] keymap: remove the Text event a bound press typed, also when the web build sends it first --- crates/keymap/src/egui.rs | 87 ++++++++++++++++++++++++++++----------- 1 file changed, 63 insertions(+), 24 deletions(-) diff --git a/crates/keymap/src/egui.rs b/crates/keymap/src/egui.rs index 67438a757..f1d127fa0 100644 --- a/crates/keymap/src/egui.rs +++ b/crates/keymap/src/egui.rs @@ -220,11 +220,20 @@ struct LastPress { /// Windows and some Linux setups report AltGr as Ctrl+Alt, so AltGr+Q (`@` on a German layout) /// arrives as Ctrl+Alt+Q, and egui-winit sends no Text event while Ctrl is held, so the press /// cannot be told from a command chord. Ctrl+Alt with other keys (F-keys, arrows) still runs. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug)] pub struct Dispatcher { last: Option, repeat: bool, clipboard: bool, + /// Whether a press's Text event comes before it when no text field has focus, as eframe's + /// web build sends them. + text_first: bool, +} + +impl Default for Dispatcher { + fn default() -> Dispatcher { + Dispatcher { last: None, repeat: false, clipboard: false, text_first: cfg!(target_arch = "wasm32") } + } } impl Dispatcher { @@ -269,10 +278,9 @@ impl Dispatcher { let frame_mods = Mods::from_egui(&input.modifiers, platform); let mut hits = Vec::new(); let mut kept = Vec::with_capacity(input.events.len()); - // The Text event egui sends after a key press belongs to that press. - let mut drop_text = false; let events = std::mem::take(&mut input.events); - let typed = if active.typing { typed_text(&events) } else { Vec::new() }; + let text_of = text_of_press(&events, self.text_first && !active.typing); + let mut drop = vec![false; events.len()]; // The web build sends both a clipboard key press and the clipboard event it causes. The // press decides: its event goes with it when it runs a command and stays otherwise. let causes = clipboard_event_follows(&events, platform); @@ -280,17 +288,16 @@ impl Dispatcher { for (i, event) in events.into_iter().enumerate() { match &event { Event::Key { key, pressed: true, repeat, modifiers, .. } if !*repeat || self.repeat => { - drop_text = false; let held = Mods::from_egui(modifiers, platform); if let Some(key) = Key::from_egui(*key) { let clip = clipboard_kind(key, held); let keep = if active.typing { - typed.get(i) == Some(&true) || clip.is_some() || may_be_alt_gr(key, held, platform) + text_of[i].is_some() || clip.is_some() || may_be_alt_gr(key, held, platform) } else { !self.clipboard && causes[i].is_some() }; if keep { - kept.push(event); + kept.push((i, event)); continue; } let caused = causes[i].clone(); @@ -304,7 +311,9 @@ impl Dispatcher { } if let Some(hit) = hit { hits.push(hit); - drop_text = !(held.cmd || held.ctrl); + if let Some(j) = text_of[i].filter(|_| !(held.cmd || held.ctrl)) { + drop[j] = true; + } continue; } } @@ -315,10 +324,6 @@ impl Dispatcher { caused_taken[j] = Some(false); } } - Event::Text(_) if drop_text => { - drop_text = false; - continue; - } // A focused text field copies and pastes on these events itself. Event::Copy | Event::Cut | Event::Paste(_) if self.clipboard && !active.typing => { let (key, held) = clipboard_chord(&event, frame_mods); @@ -338,9 +343,9 @@ impl Dispatcher { } _ => {} } - kept.push(event); + kept.push((i, event)); } - input.events = kept; + input.events = kept.into_iter().filter(|(i, _)| !drop[*i]).map(|(_, e)| e).collect(); hits } @@ -390,17 +395,29 @@ fn clipboard_event_follows(events: &[Event], platform: Platform) -> Vec Vec { - let mut out = vec![false; events.len()]; - let mut text_ahead = false; - for (event, typed) in events.iter().zip(out.iter_mut()).rev() { - match event { - Event::Text(t) if !t.is_empty() => text_ahead = true, - Event::Key { pressed: true, .. } => { - *typed = text_ahead; - text_ahead = false; +/// For each key press, the index of the Text event it typed. egui-winit, and eframe's web text +/// agent while a text field has focus, send the Text after the press, before the next one. +/// With `text_first`, eframe's web build with no text field focused, the Text comes right before +/// its press, and only for a press without Ctrl or Cmd. +fn text_of_press(events: &[Event], text_first: bool) -> Vec> { + let is_text = |e: Option<&Event>| matches!(e, Some(Event::Text(t)) if !t.is_empty()); + let mut out = vec![None; events.len()]; + if text_first { + for (i, event) in events.iter().enumerate().skip(1) { + if let Event::Key { pressed: true, modifiers, .. } = event + && !(modifiers.ctrl || modifiers.command || modifiers.mac_cmd) + && is_text(events.get(i - 1)) + { + out[i] = Some(i - 1); } + } + return out; + } + let mut text_ahead = None; + for (i, event) in events.iter().enumerate().rev() { + match event { + Event::Key { pressed: true, .. } => out[i] = text_ahead.take(), + _ if is_text(Some(event)) => text_ahead = Some(i), _ => {} } } @@ -469,3 +486,25 @@ fn clipboard_chord(event: &Event, held: Mods) -> (Key, Mods) { _ => (Key::C, with_cmd), } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Bindable, Binding, Scope, Scopes}; + + #[test] + fn web_text_before_its_press_goes_with_that_press() { + let km = Keymap::new( + vec![Bindable::new("tool.marquee", "Marquee", Scope::app()).with_default(Binding::parse("M").unwrap())], + Scopes::new(), + Platform::Windows, + ); + let press = |key| Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE }; + let mut input = InputState::default(); + input.events = vec![Event::Text("m".into()), press(EguiKey::M), Event::Text("q".into()), press(EguiKey::Q)]; + let mut d = Dispatcher { text_first: true, ..Dispatcher::new() }; + let hits = d.dispatch(&mut input, &km, &Active::NONE); + assert_eq!(hits.len(), 1); + assert_eq!(input.events, [Event::Text("q".into()), press(EguiKey::Q)]); + } +} From 5160611bad7f29cc6a6fc40c79ee4a041ab41731 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:11:46 +0000 Subject: [PATCH 24/32] keymap: while typing, a Ctrl+Alt press runs unless it typed text in the frame --- crates/keymap/README.md | 6 +++--- crates/keymap/src/egui.rs | 39 +++++-------------------------------- crates/keymap/tests/egui.rs | 27 ++++++++++--------------- 3 files changed, 18 insertions(+), 54 deletions(-) diff --git a/crates/keymap/README.md b/crates/keymap/README.md index 9cc767dde..0b1c0181a 100644 --- a/crates/keymap/README.md +++ b/crates/keymap/README.md @@ -220,9 +220,9 @@ assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File when the press matched through a stand-in (`:` for `Shift+;`, `+` for `=`). `dispatch_filtered` takes a predicate that can decline a hit, for example a chord the native menu has already handled: the press and its text then stay in egui's events, in their place. - While a text field has the keyboard, clipboard key presses, presses followed by text, and off - macOS Ctrl+Alt with a letter, digit, punctuation or Space stay with it: AltGr arrives as - Ctrl+Alt on Windows and some Linux setups, and egui-winit sends no text while Ctrl is held. + While a text field has the keyboard, clipboard key presses and presses that typed text in the + same frame stay with it. That covers AltGr, which a browser on Windows reports as Ctrl+Alt + followed by the text; a Ctrl+Alt press that types nothing is a command chord. `Dispatcher::new().with_repeat(true)` also runs commands on key repeats (held arrows). egui's Copy, Cut and Paste events stay with the app by default. On the desktop, egui-winit diff --git a/crates/keymap/src/egui.rs b/crates/keymap/src/egui.rs index f1d127fa0..4947ad725 100644 --- a/crates/keymap/src/egui.rs +++ b/crates/keymap/src/egui.rs @@ -214,12 +214,10 @@ struct LastPress { /// While [`Active::typing`], the text field keeps, without lookup: /// - clipboard events, and the clipboard key presses the web build sends with them (Cmd+C, Cmd+X, /// Cmd+V, Shift+Delete, Shift+Insert, Ctrl+Insert); -/// - a press followed by a Text event before the next press, since it typed that text (the web -/// build's text agent can send these); -/// - off macOS, a printable key (letter, digit, punctuation, Space) pressed with Ctrl and Alt. -/// Windows and some Linux setups report AltGr as Ctrl+Alt, so AltGr+Q (`@` on a German layout) -/// arrives as Ctrl+Alt+Q, and egui-winit sends no Text event while Ctrl is held, so the press -/// cannot be told from a command chord. Ctrl+Alt with other keys (F-keys, arrows) still runs. +/// - a press with a Text event of its own in the frame, since it typed that text. This covers +/// AltGr: the browser on Windows reports AltGr+Q (`@` on a German layout) as Ctrl+Alt+Q, and +/// the web build's text agent sends the `@` after it. egui-winit reports AltGr with neither Ctrl +/// nor Alt. A Ctrl+Alt press without text is a command chord. #[derive(Clone, Debug)] pub struct Dispatcher { last: Option, @@ -292,7 +290,7 @@ impl Dispatcher { if let Some(key) = Key::from_egui(*key) { let clip = clipboard_kind(key, held); let keep = if active.typing { - text_of[i].is_some() || clip.is_some() || may_be_alt_gr(key, held, platform) + text_of[i].is_some() || clip.is_some() } else { !self.clipboard && causes[i].is_some() }; @@ -424,33 +422,6 @@ fn text_of_press(events: &[Event], text_first: bool) -> Vec> { out } -/// Whether a press could be AltGr typing a character: Ctrl+Alt off macOS on a key that types. -fn may_be_alt_gr(key: Key, held: Mods, platform: Platform) -> bool { - !platform.is_mac() && held.cmd && held.alt && types_text(key) -} - -/// Letters, digits, punctuation and Space. -fn types_text(key: Key) -> bool { - !key.is_function_key() - && !matches!( - key, - Key::Escape - | Key::Tab - | Key::Backspace - | Key::Enter - | Key::Insert - | Key::Delete - | Key::Home - | Key::End - | Key::PageUp - | Key::PageDown - | Key::Up - | Key::Down - | Key::Left - | Key::Right - ) -} - fn event_clip(event: &Event) -> Option { match event { Event::Copy => Some(Clip::Copy), diff --git a/crates/keymap/tests/egui.rs b/crates/keymap/tests/egui.rs index 4cba357d5..4b31b9bfb 100644 --- a/crates/keymap/tests/egui.rs +++ b/crates/keymap/tests/egui.rs @@ -82,6 +82,7 @@ fn dispatch_keymap() -> Keymap { app("edit.copy", &["Cmd+C", "Cmd+Insert"]), app("edit.paste", &["Cmd+V", "Shift+Insert"]), app("app.quit", &["Cmd+Alt+Q"]), + app("type.pageNumber", &["Cmd+Alt+Shift+N"]), app("view.refresh", &["Cmd+Alt+F5"]), app("file.save", &["Cmd+S"]), app("view.zoomIn", &["="]), @@ -283,31 +284,23 @@ fn a_press_that_types_text_stays_with_the_text_field() { } #[test] -fn ctrl_alt_on_a_printable_key_is_left_to_the_text_field() { +fn ctrl_alt_is_left_to_the_text_field_only_when_it_types() { let km = dispatch_keymap(); let mut d = Dispatcher::new(); let typing = Active { typing: true, ..Active::NONE }; - // AltGr+Q on a German layout types `@`; Windows reports it as Ctrl+Alt+Q, and egui-winit sends - // no Text event while Ctrl is held. + // AltGr+Q on a German layout types `@`: the browser on Windows reports Ctrl+Alt+Q and the text + // agent sends the text after it. let alt_gr = Modifiers { alt: true, ..CTRL }; - let events = vec![press(EguiKey::Q, alt_gr)]; + let events = vec![press(EguiKey::Q, alt_gr), Event::Text("@".into())]; let (ran, left) = run(&mut d, &km, &typing, frame(1.0, alt_gr, events.clone())); assert!(ran.is_empty(), "{ran:?}"); assert_eq!(left, events); - let (ran, _) = run(&mut d, &km, &typing, frame(2.0, alt_gr, vec![press(EguiKey::F5, alt_gr)])); - assert_eq!(ran, ["view.refresh"], "a key that types nothing"); - let (ran, left) = run(&mut d, &km, &Active::NONE, frame(3.0, alt_gr, events)); - assert_eq!(ran, ["app.quit"], "outside a text field"); + // A real Ctrl+Alt chord types nothing, so it runs while typing. + let all = Modifiers { shift: true, ..alt_gr }; + let (ran, left) = run(&mut d, &km, &typing, frame(2.0, all, vec![press(EguiKey::N, all)])); + assert_eq!(ran, ["type.pageNumber"]); assert!(left.is_empty()); - - // macOS has no AltGr: Cmd+Option+Q is a command chord while typing. - let mac = Keymap::new( - vec![Bindable::new("app.quit", "Quit", Scope::app()).with_default(Binding::parse("Cmd+Alt+Q").unwrap())], - Scopes::new(), - Platform::Mac, - ); - let cmd_opt = Modifiers { alt: true, mac_cmd: true, command: true, ..Modifiers::NONE }; - let (ran, _) = run(&mut Dispatcher::new(), &mac, &typing, frame(4.0, cmd_opt, vec![press(EguiKey::Q, cmd_opt)])); + let (ran, _) = run(&mut d, &km, &typing, frame(3.0, alt_gr, vec![press(EguiKey::Q, alt_gr)])); assert_eq!(ran, ["app.quit"]); } From 423524c1bce69621850b271b221959cb30fedee2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:18:05 +0000 Subject: [PATCH 25/32] keymap: clipboard chords with more modifiers run their bindings with clipboard events off --- crates/keymap/README.md | 22 +++++---- crates/keymap/src/egui.rs | 93 +++++++++++++++++++++++-------------- crates/keymap/tests/egui.rs | 35 ++++++++++++++ 3 files changed, 106 insertions(+), 44 deletions(-) diff --git a/crates/keymap/README.md b/crates/keymap/README.md index 0b1c0181a..d9d6f225c 100644 --- a/crates/keymap/README.md +++ b/crates/keymap/README.md @@ -220,16 +220,20 @@ assert_eq!((report.unmatched[0].item.as_str(), report.unmatched[0].line), ("File when the press matched through a stand-in (`:` for `Shift+;`, `+` for `=`). `dispatch_filtered` takes a predicate that can decline a hit, for example a chord the native menu has already handled: the press and its text then stay in egui's events, in their place. - While a text field has the keyboard, clipboard key presses and presses that typed text in the + While a text field has the keyboard, plain clipboard key presses and presses that typed text in the same frame stay with it. That covers AltGr, which a browser on Windows reports as Ctrl+Alt followed by the text; a Ctrl+Alt press that types nothing is a command chord. `Dispatcher::new().with_repeat(true)` also runs commands on key repeats (held arrows). - egui's Copy, Cut and Paste events stay with the app by default. On the desktop, egui-winit - sends them in place of the Cmd+C, Cmd+X and Cmd+V presses (Ctrl off macOS), so a binding on - those chords runs only with `with_clipboard_events(true)`. Then the events count as their - chords outside text fields, and a Paste event's text moves to `Hit::pasted`. The web build - sends the key press and then the event; the press runs the command and takes the event, with - its text, along. An app whose - paste command asks egui for a paste gets a Paste event back, which runs that command again; - such an app keeps the default. + On the desktop, egui-winit sends egui's Copy, Cut and Paste events in place of the key press + for any chord of Cmd with C, X or V (Ctrl off macOS); the web build sends the press and then + the event. For the plain chords Cmd+C, Cmd+X and Cmd+V (and Cmd+Insert, Shift+Delete, + Shift+Insert), the events stay with the app by default, so a binding on those chords runs only + with `with_clipboard_events(true)`. Then the events count as their chords outside text fields, + and a Paste event's text moves to `Hit::pasted`. On the web, the press runs the command and + takes the event, with its text, along. An app whose paste command asks egui for a paste gets a + Paste event back, which runs that command again; such an app keeps the default. A clipboard + event with more modifiers held (Cmd+Shift+V, Cmd+Alt+C) always counts as its chord, also while + typing, and stays when that chord has no binding. egui-winit sends no Paste event when the + clipboard is empty or holds an image, so a binding on a Cmd+V chord cannot run then on the + desktop. diff --git a/crates/keymap/src/egui.rs b/crates/keymap/src/egui.rs index 4947ad725..a42e7d9d4 100644 --- a/crates/keymap/src/egui.rs +++ b/crates/keymap/src/egui.rs @@ -173,8 +173,8 @@ pub struct Hit { /// the shifted key for a Shift binding (`:` for `Shift+;`), Shift held to type a symbol, or /// `+` and `=` standing for each other. pub exact: bool, - /// The text of the Paste event that ran the command, or on the web the Paste event that came - /// with the press that ran it ([`Dispatcher::with_clipboard_events`]). + /// The text of the Paste event that ran the command, or on the web of the Paste event that + /// came with the press that ran it. pub pasted: Option, } @@ -204,16 +204,21 @@ struct LastPress { /// that runs a command is removed from the events, together with the text it typed when it has /// no command modifier, so no widget sees it too. Other events stay. /// -/// egui's Copy, Cut and Paste events stay with the app unless -/// [`with_clipboard_events`](Self::with_clipboard_events) is on. On the desktop, egui-winit sends -/// these events in place of the key presses for Cmd+C, Cmd+X and Cmd+V (Ctrl off macOS, plus -/// Shift+Delete, Ctrl+Insert and Shift+Insert on Windows), so bindings on those chords run only -/// with clipboard events on. The web build sends the key press and then the clipboard event; with -/// clipboard events off, such a press stays too. +/// On the desktop, egui-winit sends egui's Copy, Cut and Paste events in place of the key press +/// for any chord of Cmd with C, X or V (Ctrl off macOS; on Windows also Shift+Delete, Ctrl+Insert +/// and Shift+Insert). The web build sends the key press and then the event. For the plain +/// clipboard chords (Cmd+C, Cmd+X, Cmd+V, Cmd+Insert, Shift+Delete, Shift+Insert), the events and +/// their presses stay with the app unless [`with_clipboard_events`](Self::with_clipboard_events) +/// is on, so bindings on those chords run only with it on. An event with more modifiers held +/// counts as its chord, read from the frame's modifiers (Cmd+Shift+V), and runs that chord's +/// binding; without one, it stays. On Windows, egui-winit also sends Cut for Ctrl+Shift+Delete +/// and Copy for Ctrl+Shift+Insert, which read as Cmd+Shift+X and Cmd+Shift+C. +/// +/// egui-winit sends no Paste event when the clipboard is empty or holds no text (an image), so a +/// binding on Cmd+V, or on Cmd and V with more modifiers, cannot run then on the desktop. /// /// While [`Active::typing`], the text field keeps, without lookup: -/// - clipboard events, and the clipboard key presses the web build sends with them (Cmd+C, Cmd+X, -/// Cmd+V, Shift+Delete, Shift+Insert, Ctrl+Insert); +/// - the plain clipboard chords' events and presses (other clipboard chords are looked up); /// - a press with a Text event of its own in the frame, since it typed that text. This covers /// AltGr: the browser on Windows reports AltGr+Q (`@` on a German layout) as Ctrl+Alt+Q, and /// the web build's text agent sends the `@` after it. egui-winit reports AltGr with neither Ctrl @@ -246,13 +251,14 @@ impl Dispatcher { self } - /// Whether egui's Copy, Cut and Paste events count as the chords that cause them (Cmd+C, - /// Cmd+X, Cmd+V; Shift+Delete and Shift+Insert for Cut and Paste with Shift alone) outside text - /// fields. Off by default: the events stay in egui's input for the app's own handlers. With it - /// on, an event that runs a command is removed, and a Paste event's text moves to - /// [`Hit::pasted`]. On the web, the key press runs the command and its clipboard event goes - /// with it the same way; when the press runs nothing, or the hit is declined, both stay. An app that asks egui for a paste (`ViewportCommand::RequestPaste`) to run - /// its paste command gets a Paste event back, which with this on runs that command again. + /// Whether egui's Copy, Cut and Paste events for the plain clipboard chords count as those + /// chords (Cmd+C, Cmd+X, Cmd+V; Shift+Delete and Shift+Insert for Cut and Paste with Shift + /// alone) outside text fields. Off by default: the events stay in egui's input for the app's + /// own handlers. With it on, an event that runs a command is removed, and a Paste event's text + /// moves to [`Hit::pasted`]. On the web, the key press runs the command and its clipboard + /// event goes with it the same way; when the press runs nothing, or the hit is declined, both + /// stay. An app that asks egui for a paste (`ViewportCommand::RequestPaste`) to run its paste + /// command gets a Paste event back, which with this on runs that command again. pub fn with_clipboard_events(mut self, on: bool) -> Dispatcher { self.clipboard = on; self @@ -288,13 +294,16 @@ impl Dispatcher { Event::Key { key, pressed: true, repeat, modifiers, .. } if !*repeat || self.repeat => { let held = Mods::from_egui(modifiers, platform); if let Some(key) = Key::from_egui(*key) { - let clip = clipboard_kind(key, held); + let plain_clip = is_plain_clipboard(key, held); let keep = if active.typing { - text_of[i].is_some() || clip.is_some() + text_of[i].is_some() || plain_clip } else { - !self.clipboard && causes[i].is_some() + !self.clipboard && plain_clip && causes[i].is_some() }; if keep { + if let Some((j, _)) = causes[i] { + caused_taken[j] = Some(false); + } kept.push((i, event)); continue; } @@ -322,23 +331,26 @@ impl Dispatcher { caused_taken[j] = Some(false); } } - // A focused text field copies and pastes on these events itself. - Event::Copy | Event::Cut | Event::Paste(_) if self.clipboard && !active.typing => { - let (key, held) = clipboard_chord(&event, frame_mods); - if let Some(taken) = caused_taken[i] { - if taken { - continue; - } - } else if let Some(mut hit) = self.press(key, held, false, now, keymap, active) { - if let Event::Paste(text) = &event { - hit.pasted = Some(text.clone()); - } - if accept(&hit) { - hits.push(hit); - continue; + // Desktop clipboard events, and web ones whose press stayed or ran nothing. + Event::Copy | Event::Cut | Event::Paste(_) => match caused_taken[i] { + Some(true) => continue, + Some(false) => {} + None => { + let (key, held) = clipboard_chord(&event, frame_mods); + // A focused text field copies and pastes on the plain chords itself. + let look = !is_plain_clipboard(key, held) || (self.clipboard && !active.typing); + let hit = if look { self.press(key, held, false, now, keymap, active) } else { None }; + if let Some(mut hit) = hit { + if let Event::Paste(text) = &event { + hit.pasted = Some(text.clone()); + } + if accept(&hit) { + hits.push(hit); + continue; + } } } - } + }, _ => {} } kept.push((i, event)); @@ -444,6 +456,17 @@ fn clipboard_kind(key: Key, held: Mods) -> Option { } } +/// Whether a chord is one of the plain clipboard chords, which egui's text fields act on: Cmd+C, +/// Cmd+X, Cmd+V, Cmd+Insert, Shift+Delete and Shift+Insert. +fn is_plain_clipboard(key: Key, held: Mods) -> bool { + match key { + Key::C | Key::X | Key::V => held == Mods::CMD, + Key::Insert => held == Mods::CMD || held == Mods::SHIFT, + Key::Delete => held == Mods::SHIFT, + _ => false, + } +} + /// The press a clipboard event stands for, with the modifiers held. Off macOS egui-winit also /// sends Cut for Shift+Delete and Paste for Shift+Insert. fn clipboard_chord(event: &Event, held: Mods) -> (Key, Mods) { diff --git a/crates/keymap/tests/egui.rs b/crates/keymap/tests/egui.rs index 4b31b9bfb..b1fb76307 100644 --- a/crates/keymap/tests/egui.rs +++ b/crates/keymap/tests/egui.rs @@ -81,6 +81,8 @@ fn dispatch_keymap() -> Keymap { let catalog = vec![ app("edit.copy", &["Cmd+C", "Cmd+Insert"]), app("edit.paste", &["Cmd+V", "Shift+Insert"]), + app("edit.pasteInPlace", &["Cmd+Shift+V"]), + app("edit.copyMerged", &["Cmd+Shift+C"]), app("app.quit", &["Cmd+Alt+Q"]), app("type.pageNumber", &["Cmd+Alt+Shift+N"]), app("view.refresh", &["Cmd+Alt+F5"]), @@ -168,6 +170,39 @@ fn clipboard_events_stay_with_the_app_by_default() { assert_eq!(ran, ["edit.copy"]); } +#[test] +fn clipboard_chords_with_more_modifiers_run_their_bindings() { + let km = dispatch_keymap(); + let mut d = Dispatcher::new(); + let typing = Active { typing: true, ..Active::NONE }; + let ctrl_shift = Modifiers { shift: true, ..CTRL }; + // The desktop: egui-winit sends the Paste event in place of Ctrl+Shift+V. + let mut input = frame(1.0, ctrl_shift, vec![Event::Paste("text".into())]); + let hits = d.dispatch(&mut input, &km, &Active::NONE); + let ran: Vec<_> = hits.iter().map(|h| (h.command.id.as_str(), h.pasted.as_deref())).collect(); + assert_eq!(ran, [("edit.pasteInPlace", Some("text"))]); + assert!(input.events.is_empty()); + let (ran, left) = run(&mut d, &km, &typing, frame(2.0, ctrl_shift, vec![Event::Copy])); + assert_eq!(ran, ["edit.copyMerged"]); + assert!(left.is_empty()); + // Ctrl+Shift+X has no binding: the event stays. + let (ran, left) = run(&mut d, &km, &Active::NONE, frame(3.0, ctrl_shift, vec![Event::Cut])); + assert!(ran.is_empty()); + assert_eq!(left, [Event::Cut]); + + // The web: the press decides for itself and its event, also while typing. + for (time, active) in [(4.0, &Active::NONE), (5.0, &typing)] { + let events = vec![press(EguiKey::C, ctrl_shift), Event::Copy]; + let (ran, left) = run(&mut d, &km, active, frame(time, ctrl_shift, events)); + assert_eq!(ran, ["edit.copyMerged"]); + assert!(left.is_empty(), "{left:?}"); + } + let events = vec![press(EguiKey::X, ctrl_shift), Event::Cut]; + let (ran, left) = run(&mut d, &km, &Active::NONE, frame(6.0, ctrl_shift, events.clone())); + assert!(ran.is_empty()); + assert_eq!(left, events); +} + #[test] fn clipboard_events_run_their_chords_outside_text_fields_when_turned_on() { let km = dispatch_keymap(); From 501e2cf1fc87c3785a6bb4fc7e18163d2c2711b7 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:21:54 +0000 Subject: [PATCH 26/32] keymap: while typing, text-editing chords go to the text field unless an active context binds them --- crates/keymap/README.md | 7 ++- crates/keymap/src/egui.rs | 4 ++ crates/keymap/src/keymap.rs | 95 ++++++++++++++++++++++++++++++++--- crates/keymap/src/lib.rs | 2 +- crates/keymap/tests/egui.rs | 17 +++++++ crates/keymap/tests/keymap.rs | 29 +++++++++++ 6 files changed, 146 insertions(+), 8 deletions(-) diff --git a/crates/keymap/README.md b/crates/keymap/README.md index d9d6f225c..15e812dbb 100644 --- a/crates/keymap/README.md +++ b/crates/keymap/README.md @@ -57,7 +57,12 @@ assert_eq!(press("M", &editing), Lookup::None, "plain keys go to the text field" While a text field has the keyboard (`Active::typing`), the keymap's `TypingRule` decides which app and panel bindings wait: plain keys (the default), everything without the command modifier, -or everything. Bindings in an active context always fire, so `Text: Cmd+B` works while typing. +or everything. Under every rule, the platform's text-editing chords (`text_editing_chords`) go +to the field too: undo and redo, select all, and moving and deleting by word, line and text +(Cmd+Z, Alt+Left and Cmd+Backspace on macOS; Ctrl+Z, Ctrl+Y, Ctrl+Left and Ctrl+Home +elsewhere). Other command chords, such as Cmd+S, still fire. Bindings in an active context +always fire, so `Text: Cmd+B` works while typing, and a `Text: Cmd+Z` binding takes undo from +the field. With the `egui` feature, `egui::Dispatcher` does this for a frame's key events (see Features). diff --git a/crates/keymap/src/egui.rs b/crates/keymap/src/egui.rs index a42e7d9d4..fcf113b1c 100644 --- a/crates/keymap/src/egui.rs +++ b/crates/keymap/src/egui.rs @@ -223,6 +223,10 @@ struct LastPress { /// AltGr: the browser on Windows reports AltGr+Q (`@` on a German layout) as Ctrl+Alt+Q, and /// the web build's text agent sends the `@` after it. egui-winit reports AltGr with neither Ctrl /// nor Alt. A Ctrl+Alt press without text is a command chord. +/// +/// Other presses are looked up; the keymap's [`TypingRule`](crate::TypingRule) and +/// [`text_editing_chords`](crate::text_editing_chords) leave plain keys and the text-editing chords +/// (Cmd+Z, word moves) to the field. #[derive(Clone, Debug)] pub struct Dispatcher { last: Option, diff --git a/crates/keymap/src/keymap.rs b/crates/keymap/src/keymap.rs index 4c3f23fc4..1dfcb2395 100644 --- a/crates/keymap/src/keymap.rs +++ b/crates/keymap/src/keymap.rs @@ -7,7 +7,7 @@ use std::fmt; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use crate::chord::{Chord, ParseError, Platform, Trigger}; +use crate::chord::{Chord, Key, Mods, ParseError, Platform, Trigger}; use crate::command::{CommandRef, MAX_KEY}; use crate::scope::{Active, Scope, ScopeKind, Scopes}; @@ -196,8 +196,9 @@ impl Bindable { } } -/// Which chords work while a text field has the keyboard. Bindings in an active context always -/// work: a `Text: Cmd+B` binding is meant for typing. +/// Which chords work while a text field has the keyboard. Under every rule, the +/// [`text_editing_chords`] go to the text field too. Bindings in an active context always work: a +/// `Text: Cmd+B` binding is meant for typing. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum TypingRule { @@ -211,8 +212,11 @@ pub enum TypingRule { } impl TypingRule { - /// Whether `chord` may fire while typing. - pub fn fires(self, chord: &Chord) -> bool { + /// Whether `chord` may fire while typing on `platform`. + pub fn fires(self, chord: &Chord, platform: Platform) -> bool { + if text_editing_chords(platform).contains(&chord.effective(platform)) { + return false; + } match self { TypingRule::PlainKeysWait => !chord.is_plain() || chord.is_function_key(), TypingRule::CommandKeysOnly => chord.has_command() || chord.is_function_key(), @@ -221,6 +225,85 @@ impl TypingRule { } } +const CMD: Mods = Mods::CMD; +const CMD_SHIFT: Mods = Mods { shift: true, ..Mods::CMD }; +const ALT: Mods = Mods::ALT; +const ALT_SHIFT: Mods = Mods { shift: true, ..Mods::ALT }; +const CTRL: Mods = Mods::CTRL; + +// The chords egui's TextEdit acts on that follow the platform's conventions. egui also takes +// Ctrl+H, Ctrl+K, Ctrl+U and Ctrl+W everywhere, but off macOS those are app commands. +const MAC_EDITING: &[Chord] = &[ + // Undo, redo, select all. + Chord::new(CMD, Key::Z), + Chord::new(CMD_SHIFT, Key::Z), + Chord::new(CMD, Key::A), + // Words. + Chord::new(ALT, Key::Left), + Chord::new(ALT, Key::Right), + Chord::new(ALT_SHIFT, Key::Left), + Chord::new(ALT_SHIFT, Key::Right), + Chord::new(ALT, Key::Backspace), + Chord::new(ALT, Key::Delete), + // Line start and end. + Chord::new(CMD, Key::Left), + Chord::new(CMD, Key::Right), + Chord::new(CMD_SHIFT, Key::Left), + Chord::new(CMD_SHIFT, Key::Right), + Chord::new(CMD, Key::Backspace), + Chord::new(CMD, Key::Delete), + // Text start and end. + Chord::new(CMD, Key::Up), + Chord::new(CMD, Key::Down), + Chord::new(CMD_SHIFT, Key::Up), + Chord::new(CMD_SHIFT, Key::Down), + // The Control keys of Cocoa text fields: line start and end, character and line moves, + // deletion. + Chord::new(CTRL, Key::A), + Chord::new(CTRL, Key::E), + Chord::new(CTRL, Key::B), + Chord::new(CTRL, Key::F), + Chord::new(CTRL, Key::P), + Chord::new(CTRL, Key::N), + Chord::new(CTRL, Key::H), + Chord::new(CTRL, Key::K), + Chord::new(CTRL, Key::U), + Chord::new(CTRL, Key::W), +]; + +const PC_EDITING: &[Chord] = &[ + // Undo, redo, select all. + Chord::new(CMD, Key::Z), + Chord::new(CMD, Key::Y), + Chord::new(CMD_SHIFT, Key::Z), + Chord::new(CMD, Key::A), + // Words. + Chord::new(CMD, Key::Left), + Chord::new(CMD, Key::Right), + Chord::new(CMD_SHIFT, Key::Left), + Chord::new(CMD_SHIFT, Key::Right), + Chord::new(CMD, Key::Backspace), + Chord::new(CMD, Key::Delete), + // Text start and end. + Chord::new(CMD, Key::Home), + Chord::new(CMD, Key::End), + Chord::new(CMD_SHIFT, Key::Home), + Chord::new(CMD_SHIFT, Key::End), + Chord::new(CMD, Key::Up), + Chord::new(CMD, Key::Down), + Chord::new(CMD_SHIFT, Key::Up), + Chord::new(CMD_SHIFT, Key::Down), +]; + +/// The chords with modifiers that edit text on `platform`, as effective chords: undo, redo, +/// select all, and moving and deleting by word, line and text. While typing they go to the text +/// field under every [`TypingRule`]; only a binding in an active context takes one. Plain keys +/// (arrows, Home, End, Backspace, Delete, with or without Shift) are not listed, since every rule +/// holds them already. The `egui` dispatcher keeps the clipboard chords for the field itself. +pub fn text_editing_chords(platform: Platform) -> &'static [Chord] { + if platform.is_mac() { MAC_EDITING } else { PC_EDITING } +} + /// What a key press runs. #[derive(Clone, Debug, PartialEq)] pub enum Lookup { @@ -500,7 +583,7 @@ impl Keymap { /// The command `chord` (pressed twice when `double`) runs with `active` focus. pub fn lookup(&self, chord: &Chord, double: bool, active: &Active) -> Lookup { let want = Trigger { chord: chord.effective(self.platform), double }; - let held = active.typing && !self.typing.fires(&want.chord); + let held = active.typing && !self.typing.fires(&want.chord, self.platform); let Some(holders) = self.by_trigger.get(&want) else { return Lookup::None }; // Each command's nearest rank; `holders` is in catalog order. let mut ranks: Vec<(usize, u8)> = Vec::new(); diff --git a/crates/keymap/src/lib.rs b/crates/keymap/src/lib.rs index 9fbcfa2ea..9816ecda5 100644 --- a/crates/keymap/src/lib.rs +++ b/crates/keymap/src/lib.rs @@ -145,6 +145,6 @@ pub use command::{CommandRef, MAX_KEY}; pub use import::{ContextRule, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportPlan, ImportReport, NoneDefined, Start, plan}; pub use keymap::{ AssignError, Assigned, Bindable, Binding, BindingError, Conflict, ConflictKind, DropReason, Holder, Keymap, Kind, Lookup, MAX_BINDING_TEXT, - MAX_BINDINGS, MAX_COMMANDS, MAX_CONFLICTS, Overrides, Policy, Problem, TypingRule, + MAX_BINDINGS, MAX_COMMANDS, MAX_CONFLICTS, Overrides, Policy, Problem, TypingRule, text_editing_chords, }; pub use scope::{Active, MAX_SCOPE_NAME, Scope, ScopeKind, Scopes}; diff --git a/crates/keymap/tests/egui.rs b/crates/keymap/tests/egui.rs index b1fb76307..1e185ba84 100644 --- a/crates/keymap/tests/egui.rs +++ b/crates/keymap/tests/egui.rs @@ -351,6 +351,23 @@ fn typing_blocks_plain_keys_but_not_command_chords() { assert_eq!(left[1], Event::Text("b".into())); } +#[test] +fn undo_goes_to_the_text_field_and_save_still_runs() { + let km = Keymap::new( + vec![ + Bindable::new("edit.undo", "Undo", Scope::app()).with_default(Binding::parse("Cmd+Z").unwrap()), + Bindable::new("file.save", "Save", Scope::app()).with_default(Binding::parse("Cmd+S").unwrap()), + ], + Scopes::new(), + Platform::Windows, + ); + let typing = Active { typing: true, ..Active::NONE }; + let events = vec![press(EguiKey::Z, CTRL), press(EguiKey::S, CTRL)]; + let (ran, left) = run(&mut Dispatcher::new(), &km, &typing, frame(1.0, CTRL, events)); + assert_eq!(ran, ["file.save"]); + assert_eq!(left, [press(EguiKey::Z, CTRL)]); +} + #[test] fn the_focused_panel_wins_and_tool_groups_cycle() { let km = dispatch_keymap(); diff --git a/crates/keymap/tests/keymap.rs b/crates/keymap/tests/keymap.rs index 74ba8d6e4..58a904b0f 100644 --- a/crates/keymap/tests/keymap.rs +++ b/crates/keymap/tests/keymap.rs @@ -97,6 +97,35 @@ fn typing_rules_decide_what_fires_in_a_text_field() { } } +#[test] +fn text_editing_chords_go_to_the_text_field_under_every_rule() { + let catalog = vec![app("edit.undo", &["Cmd+Z"]), app("file.save", &["Cmd+S"]), app("nav.word", &["Alt+Left"]), app("nav.start", &["Cmd+Home"])]; + let typing = Active { typing: true, ..Active::NONE }; + for rule in [TypingRule::PlainKeysWait, TypingRule::CommandKeysOnly] { + for platform in [Platform::Mac, Platform::Windows] { + let km = Keymap::new(catalog.clone(), Scopes::new(), platform).with_typing_rule(rule); + assert_eq!(press(&km, "Cmd+Z", &typing), Lookup::None, "{rule:?} {platform:?}"); + assert_eq!(press(&km, "Cmd+Z", &Active::NONE), run("edit.undo")); + assert_eq!(press(&km, "Cmd+S", &typing), run("file.save"), "{rule:?} {platform:?}"); + } + } + // Word and line keys follow the platform. + let mac = Keymap::new(catalog.clone(), Scopes::new(), Platform::Mac); + let windows = Keymap::new(catalog.clone(), Scopes::new(), Platform::Windows); + assert_eq!(press(&mac, "Alt+Left", &typing), Lookup::None); + assert_eq!(press(&windows, "Alt+Left", &typing), run("nav.word")); + assert_eq!(press(&windows, "Ctrl+Home", &typing), Lookup::None); + assert_eq!(press(&mac, "Cmd+Home", &typing), run("nav.start")); + + // A binding in an active context takes the chord from the field. + let catalog = vec![app("edit.undo", &["Cmd+Z"]), app("text.undo", &["Text: Cmd+Z"])]; + let km = Keymap::new(catalog, scopes(), Platform::Windows); + let editing = Active { contexts: &["Text"], typing: true, ..Active::NONE }; + assert_eq!(press(&km, "Cmd+Z", &editing), run("text.undo")); + assert_eq!(press(&km, "Cmd+Z", &typing), Lookup::None); + assert!(!TypingRule::PlainKeysWait.fires(&chord("Ctrl+Z"), Platform::Linux)); +} + #[test] fn bindings_of_an_active_context_fire_while_typing_under_every_rule() { let catalog = vec![ From 6d96b4f684b61c1aac28fc9fe4804d8505cffb40 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:29:50 +0000 Subject: [PATCH 27/32] keymap: mark public enums and report structs that will grow non_exhaustive --- crates/keymap/src/chord.rs | 3 +++ crates/keymap/src/chord/foreign.rs | 1 + crates/keymap/src/egui.rs | 1 + crates/keymap/src/import.rs | 17 +++++++++++++++++ crates/keymap/src/keymap.rs | 10 ++++++++++ crates/keymap/tests/egui.rs | 3 ++- crates/keymap/tests/import.rs | 28 +++++++++------------------- 7 files changed, 43 insertions(+), 20 deletions(-) diff --git a/crates/keymap/src/chord.rs b/crates/keymap/src/chord.rs index 43dcf8ac7..23b1c41cc 100644 --- a/crates/keymap/src/chord.rs +++ b/crates/keymap/src/chord.rs @@ -15,6 +15,7 @@ pub const MAX_CHORD_TEXT: usize = 64; /// The platform a keymap is used on. It decides display text and whether `ctrl` folds into `cmd`. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] +#[non_exhaustive] pub enum Platform { Mac, Windows, @@ -45,6 +46,7 @@ macro_rules! keys { /// /// Digits are the main row; numeric keypad keys map to the same keys. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] + #[non_exhaustive] pub enum Key { $($variant),* } @@ -265,6 +267,7 @@ pub struct Chord { /// Why chord or trigger text was refused. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub enum ParseError { Empty, /// Longer than [`MAX_CHORD_TEXT`]. diff --git a/crates/keymap/src/chord/foreign.rs b/crates/keymap/src/chord/foreign.rs index b7e58a358..0c3a2a735 100644 --- a/crates/keymap/src/chord/foreign.rs +++ b/crates/keymap/src/chord/foreign.rs @@ -48,6 +48,7 @@ pub enum ReadNote { /// Why foreign key text could not be read. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub enum ForeignError { Empty, /// Longer than [`MAX_CHORD_TEXT`]. diff --git a/crates/keymap/src/egui.rs b/crates/keymap/src/egui.rs index fcf113b1c..d50797d65 100644 --- a/crates/keymap/src/egui.rs +++ b/crates/keymap/src/egui.rs @@ -161,6 +161,7 @@ pub const DOUBLE_PRESS: f64 = 0.6; /// A command a key press runs. #[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] pub struct Hit { /// The command to run; for tools sharing the chord, the first of `cycle`. pub command: CommandRef, diff --git a/crates/keymap/src/import.rs b/crates/keymap/src/import.rs index daf8b81ea..a387ad67c 100644 --- a/crates/keymap/src/import.rs +++ b/crates/keymap/src/import.rs @@ -181,6 +181,7 @@ pub struct ImportOptions { /// One planned binding, with the entry it came from. #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct PlannedBinding { pub binding: Binding, pub item: String, @@ -192,6 +193,7 @@ pub struct PlannedBinding { /// What the set says about one command, over every entry matched to it. #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct Planned { pub command: CommandRef, /// The first entry matched to it, and its line. @@ -209,6 +211,7 @@ pub struct Planned { /// [`plan`] and keeps its caps. #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct ImportPlan { /// In the order of their first entry. pub commands: Vec, @@ -223,6 +226,7 @@ pub struct ImportPlan { /// A command whose bindings the import changed. Shortcuts are binding texts. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct Changed { pub command: CommandRef, pub label: String, @@ -236,6 +240,7 @@ pub struct Changed { /// A binding taken from a command outside the set. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct Cleared { pub command: CommandRef, pub label: String, @@ -245,6 +250,7 @@ pub struct Cleared { /// Why a key of the set was not bound. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub enum SkipReason { /// A later entry of the set takes the chord. Taken, @@ -258,6 +264,7 @@ pub enum SkipReason { /// A key of the set that was not bound. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct Skipped { pub command: CommandRef, pub item: String, @@ -275,6 +282,7 @@ pub struct Skipped { /// [`AssignError::Full`]: crate::AssignError::Full #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct Failed { pub command: CommandRef, pub label: String, @@ -286,6 +294,7 @@ pub struct Failed { /// What a [`Failed`] change was. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub enum FailedChange { /// Giving the command the set's bindings, or taking one of them from another command. Bind, @@ -297,6 +306,7 @@ pub enum FailedChange { /// Why keys of an entry were not used. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub enum UnmatchedReason { NoMatch, /// Several commands fit and no match step picked one. @@ -310,6 +320,7 @@ pub enum UnmatchedReason { /// An entry with keys that was not used, or keys of a matched entry in unlisted contexts. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct Unmatched { pub item: String, pub line: Option, @@ -321,6 +332,7 @@ pub struct Unmatched { /// Keys of a matched entry that could not be read. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct Unreadable { pub item: String, pub line: Option, @@ -332,6 +344,7 @@ pub struct Unreadable { /// An entry without keys that matched a command and left its shortcuts alone. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct MatchedWithoutChange { pub command: CommandRef, pub label: String, @@ -343,6 +356,7 @@ pub struct MatchedWithoutChange { /// Why a [`MatchedWithoutChange`] entry did not clear its command. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub enum NoChangeReason { /// The entry matched only through a panel-menu rule (a catalog path ending with its /// segments, or its last segment alone). Such a match is close enough to bind the entry's @@ -353,6 +367,7 @@ pub enum NoChangeReason { /// Likely commands for an unmatched entry, best first. Never applied. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct Suggestion { pub item: String, pub line: Option, @@ -363,6 +378,7 @@ pub struct Suggestion { /// the main key of the same name. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct Approximated { pub item: String, pub line: Option, @@ -375,6 +391,7 @@ pub struct Approximated { /// `line` the entry's [`ForeignEntry::line`]. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct ImportReport { pub set: Option, /// Commands of the set whose bindings changed. diff --git a/crates/keymap/src/keymap.rs b/crates/keymap/src/keymap.rs index 1dfcb2395..fff50a2eb 100644 --- a/crates/keymap/src/keymap.rs +++ b/crates/keymap/src/keymap.rs @@ -26,6 +26,7 @@ pub const MAX_CONFLICTS: usize = 4096; /// What a binding does when pressed. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub enum Kind { #[default] Command, @@ -44,6 +45,7 @@ pub struct Binding { /// Why binding text was refused. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub enum BindingError { TooLong, /// The part before `": "` is not a scope name. @@ -201,6 +203,7 @@ impl Bindable { /// `Text: Cmd+B` binding is meant for typing. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub enum TypingRule { /// Plain chords (no cmd, ctrl or alt) go to the text; function keys still fire. #[default] @@ -306,6 +309,7 @@ pub fn text_editing_chords(platform: Platform) -> &'static [Chord] { /// What a key press runs. #[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] pub enum Lookup { None, Run(CommandRef), @@ -337,6 +341,7 @@ pub struct Holder { /// The result of an assignment. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct Assigned { /// Bindings removed from other commands ([`Policy::Steal`]). pub taken_from: Vec, @@ -347,6 +352,7 @@ pub struct Assigned { /// Why an assignment was refused. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub enum AssignError { UnknownCommand, /// The system takes this chord. @@ -379,6 +385,7 @@ impl std::error::Error for AssignError {} /// Why loading dropped part of an [`Overrides`] entry. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub enum DropReason { KeyTooLong, /// The value is not a list of texts. @@ -393,6 +400,7 @@ pub enum DropReason { /// Something wrong in the stored overrides. Load reports these instead of failing. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub enum Problem { /// No command in the catalog has this key; the entry is kept. UnknownCommand { key: String }, @@ -413,6 +421,7 @@ pub enum Problem { /// How two bindings on one chord relate. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub enum ConflictKind { /// Only one of the two can run. Clash, @@ -423,6 +432,7 @@ pub enum ConflictKind { /// Two commands on one chord. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] +#[non_exhaustive] pub struct Conflict { /// The effective trigger on the keymap's platform. pub chord: Trigger, diff --git a/crates/keymap/tests/egui.rs b/crates/keymap/tests/egui.rs index 1e185ba84..c1452e473 100644 --- a/crates/keymap/tests/egui.rs +++ b/crates/keymap/tests/egui.rs @@ -380,7 +380,8 @@ fn the_focused_panel_wins_and_tool_groups_cycle() { let hits = d.dispatch(&mut input, &km, &Active::NONE); let tools = vec![CommandRef::new("tool.marquee"), CommandRef::new("tool.ellipse")]; let trigger = Trigger::single(chord("M")); - assert_eq!(hits, [Hit { command: tools[0].clone(), cycle: tools, trigger, exact: true, pasted: None }]); + let got: Vec<_> = hits.iter().map(|h: &Hit| (&h.command, &h.cycle, h.trigger, h.exact, h.pasted.as_deref())).collect(); + assert_eq!(got, [(&tools[0], &tools, trigger, true, None)]); } #[test] diff --git a/crates/keymap/tests/import.rs b/crates/keymap/tests/import.rs index e1d72833f..c9c67dc31 100644 --- a/crates/keymap/tests/import.rs +++ b/crates/keymap/tests/import.rs @@ -338,14 +338,12 @@ fn changes_that_find_the_overrides_full_are_reported() { has(&km, "view.goToPage", &["Cmd+J"]); has(&km, "file.save", &["Cmd+S"]); has(&km, "edit.duplicate", &["Cmd+Alt+Shift+D"]); - let row = |id: &str, label: &str, change, shortcuts: &[&str]| Failed { - command: id.into(), - label: label.into(), - change, - shortcuts: shortcuts.iter().map(|s| s.to_string()).collect(), + let rows = |failed: &[Failed]| -> Vec<(String, String, FailedChange, Vec)> { + failed.iter().map(|f| (f.command.id.clone(), f.label.clone(), f.change, f.shortcuts.clone())).collect() }; + let row = |id: &str, label: &str, change, shortcuts: &[&str]| (id.to_string(), label.to_string(), change, shortcuts.iter().map(|s| s.to_string()).collect::>()); assert_eq!( - r.failed, + rows(&r.failed), [ row("file.close", "Close", FailedChange::Bind, &["Cmd+J"]), row("file.save", "Save", FailedChange::Bind, &["Cmd+Alt+S"]), @@ -378,7 +376,7 @@ fn changes_that_find_the_overrides_full_are_reported() { let r = plan(&set, &km, &options(Start::Current)).apply(&mut km); has(&km, "file.close", &["Cmd+Alt+J"]); has(&km, "file.save", &["Cmd+S"]); - assert_eq!(r.failed, [row("file.save", "Save", FailedChange::Bind, &["Cmd+Alt+J"])]); + assert_eq!(rows(&r.failed), [row("file.save", "Save", FailedChange::Bind, &["Cmd+Alt+J"])]); assert!(r.skipped.is_empty(), "{:?}", r.skipped); assert_eq!(r.imported, 1); } @@ -397,17 +395,8 @@ fn keys_in_unknown_scopes_are_skipped_and_the_rest_apply() { let mut km = keymap(Platform::Windows); let r = plan(&set, &km, &options).apply(&mut km); has(&km, "file.close", &["Cmd+Q", "Text: Cmd+L"]); - assert_eq!( - r.skipped, - [Skipped { - command: "file.close".into(), - item: "File > Close".into(), - line: None, - shortcut: "Story: Cmd+K".into(), - kept_by: None, - reason: SkipReason::UnknownScope - }] - ); + let skipped: Vec<_> = r.skipped.iter().map(|s: &Skipped| (s.command.id.as_str(), s.item.as_str(), s.line, s.shortcut.as_str(), s.kept_by.clone(), s.reason)).collect(); + assert_eq!(skipped, [("file.close", "File > Close", None, "Story: Cmd+K", None, SkipReason::UnknownScope)]); assert_eq!(serde_json::to_value(r.skipped[0].reason).unwrap(), "unknownScope"); } @@ -586,7 +575,8 @@ fn report_json_uses_camel_case_names() { assert_eq!(reasons, ["noMatch", "ambiguous", "context", "tool", "noMatch"]); assert_eq!(sorted(&v["unreadable"][0]), ["item", "keys", "line", "reason"]); assert_eq!(sorted(&v["suggestions"][0]), ["candidates", "item", "line"]); - let approximated = ImportReport { approximated: plan(&numpad_set(), &km, &options).report.approximated, ..ImportReport::default() }; + let mut approximated = ImportReport::default(); + approximated.approximated = plan(&numpad_set(), &km, &options).report.approximated; let a = serde_json::to_value(&approximated).unwrap(); assert_eq!(sorted(&a["approximated"][0]), ["item", "keys", "line", "note"]); assert_eq!(a["approximated"][0]["note"], "numpad"); From 9aaf9dfd3882c12b6aab5604cc2567fc3b64127b Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 20 Oct 2026 15:46:00 +0000 Subject: [PATCH 28/32] keymap: format, and keep the dispatcher's Default clear of clippy's derive lint --- crates/keymap/src/egui.rs | 19 ++++++++++--------- crates/keymap/src/scope.rs | 5 +---- crates/keymap/tests/import.rs | 10 ++++++++-- 3 files changed, 19 insertions(+), 15 deletions(-) diff --git a/crates/keymap/src/egui.rs b/crates/keymap/src/egui.rs index d50797d65..c40bcea8c 100644 --- a/crates/keymap/src/egui.rs +++ b/crates/keymap/src/egui.rs @@ -238,9 +238,12 @@ pub struct Dispatcher { text_first: bool, } +/// eframe's web build sends a press's Text event first when no text field has focus. +const TEXT_FIRST: bool = cfg!(target_arch = "wasm32"); + impl Default for Dispatcher { fn default() -> Dispatcher { - Dispatcher { last: None, repeat: false, clipboard: false, text_first: cfg!(target_arch = "wasm32") } + Dispatcher { last: None, repeat: false, clipboard: false, text_first: TEXT_FIRST } } } @@ -300,11 +303,8 @@ impl Dispatcher { let held = Mods::from_egui(modifiers, platform); if let Some(key) = Key::from_egui(*key) { let plain_clip = is_plain_clipboard(key, held); - let keep = if active.typing { - text_of[i].is_some() || plain_clip - } else { - !self.clipboard && plain_clip && causes[i].is_some() - }; + let keep = + if active.typing { text_of[i].is_some() || plain_clip } else { !self.clipboard && plain_clip && causes[i].is_some() }; if keep { if let Some((j, _)) = causes[i] { caused_taken[j] = Some(false); @@ -374,9 +374,10 @@ impl Dispatcher { if repeat { return find(false); } - let again = self.last.as_ref().is_some_and(|l| { - l.chord == first && !l.ran_double && l.panel.as_deref() == active.panel && now >= l.at && now - l.at < DOUBLE_PRESS - }); + let again = self + .last + .as_ref() + .is_some_and(|l| l.chord == first && !l.ran_double && l.panel.as_deref() == active.panel && now >= l.at && now - l.at < DOUBLE_PRESS); let double = if again { find(true) } else { None }; self.last = Some(LastPress { chord: first, at: now, ran_double: double.is_some(), panel: active.panel.map(str::to_owned) }); double.or_else(|| find(false)) diff --git a/crates/keymap/src/scope.rs b/crates/keymap/src/scope.rs index 26b94e496..90b29e1e3 100644 --- a/crates/keymap/src/scope.rs +++ b/crates/keymap/src/scope.rs @@ -20,10 +20,7 @@ impl Scope { /// character, or one with whitespace at either end, which binding text would lose. pub fn new(name: impl Into) -> Option { let name = name.into(); - let ok = !name.is_empty() - && name.len() <= MAX_SCOPE_NAME - && name.trim() == name - && !name.chars().any(|c| c == ':' || c.is_control()); + let ok = !name.is_empty() && name.len() <= MAX_SCOPE_NAME && name.trim() == name && !name.chars().any(|c| c == ':' || c.is_control()); ok.then_some(Scope(name)) } diff --git a/crates/keymap/tests/import.rs b/crates/keymap/tests/import.rs index c9c67dc31..dd66bcb6e 100644 --- a/crates/keymap/tests/import.rs +++ b/crates/keymap/tests/import.rs @@ -341,7 +341,9 @@ fn changes_that_find_the_overrides_full_are_reported() { let rows = |failed: &[Failed]| -> Vec<(String, String, FailedChange, Vec)> { failed.iter().map(|f| (f.command.id.clone(), f.label.clone(), f.change, f.shortcuts.clone())).collect() }; - let row = |id: &str, label: &str, change, shortcuts: &[&str]| (id.to_string(), label.to_string(), change, shortcuts.iter().map(|s| s.to_string()).collect::>()); + let row = |id: &str, label: &str, change, shortcuts: &[&str]| { + (id.to_string(), label.to_string(), change, shortcuts.iter().map(|s| s.to_string()).collect::>()) + }; assert_eq!( rows(&r.failed), [ @@ -395,7 +397,11 @@ fn keys_in_unknown_scopes_are_skipped_and_the_rest_apply() { let mut km = keymap(Platform::Windows); let r = plan(&set, &km, &options).apply(&mut km); has(&km, "file.close", &["Cmd+Q", "Text: Cmd+L"]); - let skipped: Vec<_> = r.skipped.iter().map(|s: &Skipped| (s.command.id.as_str(), s.item.as_str(), s.line, s.shortcut.as_str(), s.kept_by.clone(), s.reason)).collect(); + let skipped: Vec<_> = r + .skipped + .iter() + .map(|s: &Skipped| (s.command.id.as_str(), s.item.as_str(), s.line, s.shortcut.as_str(), s.kept_by.clone(), s.reason)) + .collect(); assert_eq!(skipped, [("file.close", "File > Close", None, "Story: Cmd+K", None, SkipReason::UnknownScope)]); assert_eq!(serde_json::to_value(r.skipped[0].reason).unwrap(), "unknownScope"); } From 8ce872938f12a25a536f33cbbac9b3bbb2f3da33 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 21 Oct 2026 18:14:21 +0000 Subject: [PATCH 29/32] keymap: a failed import change keeps its shortcuts when a later change frees room The cleanup after an import could remove a chord from a command whose own change had failed, once a later change freed an overrides entry. That command now keeps its bindings, and the change that would have taken its chord is dropped and reported, as when the removal itself fails. --- crates/keymap/src/import.rs | 15 +++++++++++---- crates/keymap/tests/import.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/crates/keymap/src/import.rs b/crates/keymap/src/import.rs index a387ad67c..87d41048a 100644 --- a/crates/keymap/src/import.rs +++ b/crates/keymap/src/import.rs @@ -562,8 +562,9 @@ impl ImportPlan { /// /// A change that finds the overrides full is left out and reported in /// [`ImportReport::failed`]; the others still apply, and a chord it would have taken from an - /// earlier entry stays with that entry. That includes taking a chord from another command: - /// both commands keep the bindings they had. With [`Start::Defaults`] that cannot happen. + /// earlier entry stays with that entry. That includes taking a chord from another command, + /// or from a command whose own change failed: both commands keep the bindings they had. With + /// [`Start::Defaults`] that cannot happen. pub fn apply(&self, keymap: &mut Keymap) -> ImportReport { let before: Vec> = self.commands.iter().map(|p| keymap.bindings(&p.command)).collect(); // Dropping every entry leaves room for all of them: each catalog command takes at most one @@ -582,11 +583,14 @@ impl ImportPlan { let home_of = |km: &Keymap, c: &CommandRef| km.bindable(c).map_or_else(Scope::app, |b| b.scope.clone()); let label_of = |km: &Keymap, c: &CommandRef| km.bindable(c).map(|b| b.label.clone()).unwrap_or_default(); let mut decided: HashSet = HashSet::new(); + // Commands whose change failed keep the bindings they had, whatever later changes free. + let mut failed_here: HashSet = HashSet::new(); for (c, (p, list)) in self.commands.iter().zip(&accepted).enumerate() { let failed = |km: &Keymap, change, shortcuts| Failed { command: p.command.clone(), label: label_of(km, &p.command), change, shortcuts }; if let Some(f) = dropped.get(&c) { report.failed.push(f.clone()); + failed_here.insert(p.command.key()); continue; } if !list.is_empty() { @@ -600,11 +604,13 @@ impl ImportPlan { continue 'attempt; } report.failed.push(f); + failed_here.insert(p.command.key()); continue; } } else if p.none_defined && self.none_defined == NoneDefined::Clear { if !keymap.clear(&p.command) { report.failed.push(failed(keymap, FailedChange::Clear, Vec::new())); + failed_here.insert(p.command.key()); continue; } } else { @@ -614,7 +620,8 @@ impl ImportPlan { } // A command that cannot take a chord from another command is dropped, so both keep - // the bindings they had. + // the bindings they had. That includes a command whose own change failed: freeing an + // entry later must not take its chord away. let mut unbind_failed = false; for (c, (p, list)) in self.commands.iter().zip(&accepted).enumerate() { if list.is_empty() || !decided.contains(&p.command.key()) { @@ -627,7 +634,7 @@ impl ImportPlan { let home = home_of(keymap, &h.command); let label = label_of(keymap, &h.command); let shortcut = h.binding.text(&home); - if keymap.remove(&h.command, &h.binding) { + if !failed_here.contains(&h.command.key()) && keymap.remove(&h.command, &h.binding) { report.conflicts_cleared.push(Cleared { command: h.command, label, shortcut }); } else { let home = home_of(keymap, &p.command); diff --git a/crates/keymap/tests/import.rs b/crates/keymap/tests/import.rs index dd66bcb6e..d2414b570 100644 --- a/crates/keymap/tests/import.rs +++ b/crates/keymap/tests/import.rs @@ -309,6 +309,38 @@ fn start_and_none_defined_options() { assert_eq!(r.imported, 2); } +#[test] +fn a_failed_change_keeps_its_shortcut_when_a_later_change_frees_room() { + // Save's change finds the overrides full. Close's change then frees an entry, and Zoom In + // takes Cmd+S. Removing Cmd+S from Save would fit now, but Save's import failed, so Save + // keeps it and Zoom In stays as it was. + let set = ForeignSet { + name: None, + entries: vec![ + win("File", &["Save"], &[("Default", "Ctrl+Alt+S")]), + win("File", &["Close"], &[("Default", "Ctrl+W")]), + win("View", &["Zoom In"], &[("Default", "Ctrl+S")]), + ], + }; + let mut o = Overrides::new(); + o.insert("file.close", vec!["Cmd+Q".into()]); + o.insert("view.zoomIn", vec!["Cmd+Alt+Z".into()]); + for n in 2..MAX_COMMANDS { + o.insert(format!("junk.{n}"), vec!["Cmd+K".into()]); + } + assert_eq!(o.len(), MAX_COMMANDS); + let options = ImportOptions { contexts: vec![("Default".into(), ContextRule::Home)], ..ImportOptions::default() }; + let mut km = keymap(Platform::Windows).with_overrides(o); + let r = plan(&set, &km, &options).apply(&mut km); + has(&km, "file.save", &["Cmd+S"]); + has(&km, "file.close", &["Cmd+W"]); + has(&km, "view.zoomIn", &["Cmd+Alt+Z"]); + let failed: Vec<(&str, FailedChange)> = r.failed.iter().map(|f| (f.command.id.as_str(), f.change)).collect(); + assert_eq!(failed, [("file.save", FailedChange::Bind), ("view.zoomIn", FailedChange::Bind)]); + assert!(r.conflicts_cleared.is_empty(), "{:?}", r.conflicts_cleared); + assert_eq!(r.imported, 1); +} + #[test] fn changes_that_find_the_overrides_full_are_reported() { let set = ForeignSet { From e6b54fa8aa256c12cb05e330f766a7bc3c86797f Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 23 Oct 2026 05:03:07 +0000 Subject: [PATCH 30/32] keymap: leave the token out of .git/config after checkout in the keymap workflow --- .github/workflows/keymap.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/keymap.yml b/.github/workflows/keymap.yml index 29bddad65..e935a7841 100644 --- a/.github/workflows/keymap.yml +++ b/.github/workflows/keymap.yml @@ -22,6 +22,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - uses: dtolnay/rust-toolchain@stable with: components: rustfmt, clippy @@ -46,6 +48,8 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 with: @@ -57,6 +61,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - uses: dtolnay/rust-toolchain@stable with: targets: wasm32-unknown-unknown From af6eb6ae1eef8868f34af385195dc34f7a83820c Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 23 Oct 2026 05:16:16 +0000 Subject: [PATCH 31/32] Revert "keymap: leave the token out of .git/config after checkout in the keymap workflow" This reverts commit e6b54fa8aa256c12cb05e330f766a7bc3c86797f. --- .github/workflows/keymap.yml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/.github/workflows/keymap.yml b/.github/workflows/keymap.yml index e935a7841..29bddad65 100644 --- a/.github/workflows/keymap.yml +++ b/.github/workflows/keymap.yml @@ -22,8 +22,6 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - with: - persist-credentials: false - uses: dtolnay/rust-toolchain@stable with: components: rustfmt, clippy @@ -48,8 +46,6 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - with: - persist-credentials: false - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 with: @@ -61,8 +57,6 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - with: - persist-credentials: false - uses: dtolnay/rust-toolchain@stable with: targets: wasm32-unknown-unknown From 457da42c5f133ae94efe94e160ee8ed20469fc93 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 23 Oct 2026 05:28:19 +0000 Subject: [PATCH 32/32] keymap: pin the workflow's toolchain and cache actions to main's commits, and keep the token out of .git/config after checkout --- .github/workflows/keymap.yml | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/.github/workflows/keymap.yml b/.github/workflows/keymap.yml index 29bddad65..2f0bdb9f4 100644 --- a/.github/workflows/keymap.yml +++ b/.github/workflows/keymap.yml @@ -22,10 +22,12 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: components: rustfmt, clippy - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: craft-keymap-linux - run: cargo fmt -p craft-keymap --check @@ -46,8 +48,10 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - - uses: Swatinem/rust-cache@v2 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: craft-keymap-${{ matrix.os }} - run: cargo test -p craft-keymap --all-features --locked @@ -57,10 +61,12 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable with: targets: wasm32-unknown-unknown - - uses: Swatinem/rust-cache@v2 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: key: craft-keymap-wasm - run: cargo check -p craft-keymap --all-features --locked --target wasm32-unknown-unknown