Merge #164: Add craft-keymap: shared keyboard bindings and shortcut-set import

This commit is contained in:
aiongg
2026-10-24 02:29:52 +00:00
22 changed files with 7275 additions and 0 deletions
+72
View File
@@ -0,0 +1,72 @@
name: Keymap
on:
push:
branches: [main]
paths: ["crates/keymap/**", "crates/settings/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"]
pull_request:
paths: ["crates/keymap/**", "crates/settings/**", "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
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
with:
components: rustfmt, clippy
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
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
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
wasm:
timeout-minutes: 10
name: Keymap WASM
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
with:
targets: wasm32-unknown-unknown
- 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
Generated
+11
View File
@@ -834,6 +834,17 @@ dependencies = [
"writeable",
]
[[package]]
name = "craft-keymap"
version = "0.1.0"
dependencies = [
"craft-settings",
"egui",
"serde",
"serde_json",
"tempfile",
]
[[package]]
name = "craft-media"
version = "0.1.0"
+1
View File
@@ -26,6 +26,7 @@ craft-cms = { path = "crates/cms" }
craft-docpath = { path = "crates/docpath" }
craft-fonts-build = { path = "crates/fonts-build" }
craft-i18n = { path = "crates/i18n" }
craft-keymap = { path = "crates/keymap" }
craft-media = { path = "crates/media" }
craft-print = { path = "crates/print" }
craft-quit = { path = "crates/quit" }
+4
View File
@@ -44,6 +44,10 @@ craft-<name> = { git = "https://github.com/storytold/craft-libs", rev = "<commit
lookup with fallback (`pt-br` → `pt` → English), plurals, language names, the system locale and
a pseudo locale. The catalogs stay a fully optional build input; apps keep `tl!` and their
language setting.
- [`craft-keymap`](crates/keymap/README.md): keyboard bindings: chords and their text forms,
scopes, conflicts, user overrides stored through craft-settings and import of other
applications' shortcut sets. Command catalogs, file readers and the shortcut editor UI stay
in each app.
- [`craft-media`](crates/media/README.md): bit-level I/O (`bitstream`), clean-room MP4/MOV
(`isobmff`) and Matroska/WebM (`matroska`) demuxers and muxers, from FilmCraft, and an ISO BMFF
box reader. Containers only; codecs stay in each app.
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "craft-keymap"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
description = "Keyboard bindings for the Craft suite: chords, keymaps, conflicts, overrides and shortcut-set import"
[lints]
workspace = true
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
egui = { workspace = true, optional = true }
[dev-dependencies]
craft-settings = { workspace = true }
tempfile = "3"
[features]
egui = ["dep:egui"]
+244
View File
@@ -0,0 +1,244 @@
# Craft Keymap
`craft-keymap` holds the data and logic for keyboard bindings in the Craft apps: chords and their
text forms, bindings from chords to commands, scopes, conflicts, user overrides, and an import
pipeline for other applications' shortcut sets. Each application supplies its command catalog,
its file-format readers and its UI.
## Boundaries
- Data and logic only. The apps keep the command catalog (ids, labels, menu paths, defaults),
the readers for other applications' files, the shortcut editor UI and running the commands.
- Never crashes: no panics, no `unsafe`. Loading settings never fails; what cannot be used is
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 catalog and dispatch
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.
```rust
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 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")),
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(catalog, Scopes::new().with_panel("Timeline").with_context("Text"), Platform::Mac);
// 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");
```
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. 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).
## Chords
A [`Chord`](src/chord.rs) is a key plus the modifiers `cmd`, `ctrl`, `alt` and `shift`. `cmd` is
the command modifier: ⌘ on macOS, Ctrl on Windows and Linux. `ctrl` is the Mac Control key; off
macOS it folds into `cmd` (`Chord::effective`).
- Canonical text, as stored and sent: `Cmd+Ctrl+Alt+Shift+K`, `Cmd++` for Plus, `A A` for a
double press.
- `Chord::parse` also reads common aliases (`⇧⌘Z`, `opt+left`, `Ctrl+Cmd+M`).
- `Chord::display(Platform)` gives `⇧⌘Z` on macOS and `Ctrl+Shift+Z` elsewhere.
- `chord::foreign::read_foreign` reads key text written by other applications (Windows or Mac
modifier names, numeric keypad keys).
## Storing overrides
`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.
`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 {
#[serde(with = "craft_keymap::keymap::overrides_list")]
shortcuts: Overrides,
}
impl Settings for Prefs {
const APP_ID: &'static str = "acmecraft";
const SCHEMA_VERSION: u32 = 1;
}
// `catalog` is the app's Vec<Bindable>.
let (mut store, _report) = SettingsStore::<Prefs>::open(Location::Auto);
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();
// After each change in the shortcut editor:
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
[`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 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 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 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`).
- 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
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. 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`);
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
- `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. 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, 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).
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.
+589
View File
@@ -0,0 +1,589 @@
//! 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")]
#[non_exhaustive]
pub enum Platform {
Mac,
Windows,
Linux,
}
impl Platform {
/// 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
} 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)]
#[non_exhaustive]
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> {
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<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.name())
}
}
impl<'de> Deserialize<'de> for Key {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Key, D::Error> {
let text = <std::borrow::Cow<'de, str>>::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")]
#[non_exhaustive]
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<Modifier> {
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<Chord, ParseError> {
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<Key> 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, ParseError> {
Chord::parse(s)
}
}
impl Serialize for Chord {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for Chord {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Chord, D::Error> {
let text = <std::borrow::Cow<'de, str>>::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<Trigger, ParseError> {
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<Chord> 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, ParseError> {
Trigger::parse(s)
}
}
impl Serialize for Trigger {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for Trigger {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Trigger, D::Error> {
let text = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
Trigger::parse(&text).map_err(serde::de::Error::custom)
}
}
+196
View File
@@ -0,0 +1,196 @@
//! 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<I, S>(texts: I) -> Flavor
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
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")]
#[non_exhaustive]
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<ReadNote>), 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::<String>().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))
}
+127
View File
@@ -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<String>) -> CommandRef {
CommandRef { id: id.into(), params: Value::Null }
}
pub fn with_params(id: impl Into<String>, 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<CommandRef> {
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('"');
}
+510
View File
@@ -0,0 +1,510 @@
//! 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. [`platform`] gives
//! the platform to build a keymap for, the browser's operating system included on the web.
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<OperatingSystem> 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 {
($($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<Key> {
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<Chord> {
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
}
/// 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)]
#[non_exhaustive]
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 catalog order (the app picks the next one);
/// empty for a plain command.
pub cycle: Vec<CommandRef>,
/// 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, or on the web of the Paste event that
/// came with the press that ran it.
pub pasted: Option<String>,
}
impl Hit {
fn from_lookup(lookup: Lookup, trigger: Trigger, exact: bool) -> Option<Hit> {
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 })
}
}
#[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<String>,
}
/// 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). 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.
///
/// 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:
/// - 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
/// 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<LastPress>,
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,
}
/// 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: TEXT_FIRST }
}
}
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
}
/// 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
}
/// The commands this frame's key presses run with `active` focus, in press order.
///
/// 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<Hit> {
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<Hit> {
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());
let events = std::mem::take(&mut input.events);
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);
let mut caused_taken: Vec<Option<bool>> = 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 => {
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() };
if keep {
if let Some((j, _)) = causes[i] {
caused_taken[j] = Some(false);
}
kept.push((i, event));
continue;
}
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) = hit {
hits.push(hit);
if let Some(j) = text_of[i].filter(|_| !(held.cmd || held.ctrl)) {
drop[j] = true;
}
continue;
}
}
}
// 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);
}
}
// 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));
}
input.events = kept.into_iter().filter(|(i, _)| !drop[*i]).map(|(_, e)| e).collect();
hits
}
fn press(&mut self, key: Key, held: Mods, repeat: bool, now: f64, keymap: &Keymap, active: &Active) -> Option<Hit> {
let chords = candidates(key, held, keymap.platform());
let first = *chords.first()?;
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);
}
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))
}
}
/// A clipboard event: Copy, Cut or Paste.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Clip {
Copy,
Cut,
Paste,
}
/// 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<Option<(usize, Option<String>)>> {
let mut out = vec![None; events.len()];
let mut ahead: [Option<usize>; 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 = 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(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));
}
}
}
out
}
/// 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<Option<usize>> {
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),
_ => {}
}
}
out
}
fn event_clip(event: &Event) -> Option<Clip> {
match event {
Event::Copy => Some(Clip::Copy),
Event::Cut => Some(Clip::Cut),
Event::Paste(_) => Some(Clip::Paste),
_ => None,
}
}
/// The clipboard event a backend sends for a press, if any.
fn clipboard_kind(key: Key, held: Mods) -> Option<Clip> {
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,
}
}
/// 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) {
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),
}
}
#[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)]);
}
}
File diff suppressed because it is too large Load Diff
+351
View File
@@ -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<String>,
}
/// 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<usize>),
}
/// 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<String> {
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<String> {
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<char> = 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<String>,
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<String>,
id: String,
labels: Vec<Text>,
}
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<Prepared>,
/// Candidates by their joined id words and their labels' letters and digits.
exact: HashMap<String, Vec<usize>>,
/// Candidates by a word of their id or labels.
by_word: HashMap<String, Vec<usize>>,
/// Candidates by a character pair of their labels.
by_pair: HashMap<(char, char), Vec<usize>>,
}
impl Matcher {
/// Prepares `candidates` once for many [`Matcher::propose`] calls.
pub fn new(candidates: &[Candidate]) -> Self {
let prepared: Vec<Prepared> = candidates.iter().map(Prepared::of).collect();
let (mut exact, mut by_word, mut by_pair) = (HashMap::new(), HashMap::new(), HashMap::new());
fn add<K: std::hash::Hash + Eq>(map: &mut HashMap<K, Vec<usize>>, 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<Candidate> {
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"]);
}
}
File diff suppressed because it is too large Load Diff
+370
View File
@@ -0,0 +1,370 @@
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 in key order as a map of one text per command (`{ "<key>": "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
/// are reported by [`Keymap::problems`](super::Keymap::problems).
#[derive(Clone, Debug, Default)]
pub struct Overrides {
map: BTreeMap<String, Vec<String>>,
notes: Vec<Problem>,
}
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<Item = (&str, &[String])> {
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<String>, texts: Vec<String>) -> 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<Vec<String>> {
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);
}
}
}
// 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<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
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<S: Serializer>(overrides: &Overrides, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_seq(overrides.map.iter().map(|(command, keys)| Item { command, keys }))
}
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Overrides, D::Error> {
Overrides::deserialize(deserializer)
}
}
#[derive(Serialize)]
struct Item<'a> {
command: &'a str,
keys: &'a [String],
}
impl<'de> Deserialize<'de> for Overrides {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Overrides, D::Error> {
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<String>, Vec<String>) = 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<E: de::Error>(self, _: $t) -> Result<Overrides, E> {
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<E: de::Error>(self) -> Result<Overrides, E> {
Ok(not_a_list())
}
fn visit_none<E: de::Error>(self) -> Result<Overrides, E> {
Ok(not_a_list())
}
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Overrides, D::Error> {
deserializer.deserialize_any(OverridesVisitor)
}
/// The array form, `[{ command = "…", keys = […] }, …]`.
fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Overrides, A::Error> {
let mut b = Builder::default();
while let Some(item) = access.next_element::<Value>()? {
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<A: MapAccess<'de>>(self, mut access: A) -> Result<Overrides, A::Error> {
let mut b = Builder::default();
while let Some(key) = access.next_key::<String>()? {
if b.admits(&key) {
let value = match access.next_value::<Lenient>()? {
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::<IgnoredAny>()?;
}
}
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<String>, other: bool, extra: usize },
Text(String),
Other,
}
impl<'de> Deserialize<'de> for Lenient {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Lenient, D::Error> {
deserializer.deserialize_any(LenientVisitor)
}
}
struct LenientVisitor;
macro_rules! other {
($($name:ident: $t:ty),*) => {
$(fn $name<E: de::Error>(self, _: $t) -> Result<Lenient, E> {
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<E: de::Error>(self, v: &str) -> Result<Lenient, E> {
Ok(Lenient::Text(v.to_string()))
}
fn visit_string<E: de::Error>(self, v: String) -> Result<Lenient, E> {
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<E: de::Error>(self) -> Result<Lenient, E> {
Ok(Lenient::Other)
}
fn visit_none<E: de::Error>(self) -> Result<Lenient, E> {
Ok(Lenient::Other)
}
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Lenient, D::Error> {
deserializer.deserialize_any(LenientVisitor)
}
fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Lenient, A::Error> {
while access.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
Ok(Lenient::Other)
}
fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Lenient, A::Error> {
let mut texts = Vec::new();
let mut other = false;
let mut extra = 0usize;
while let Some(item) = access.next_element::<Lenient>()? {
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 })
}
}
+150
View File
@@ -0,0 +1,150 @@
#![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
//! 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
//! 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 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
//! 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 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")),
//! 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(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.
//! 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, 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};
//! use craft_settings::{Location, Settings, SettingsStore};
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Serialize, Deserialize, Default, Clone, PartialEq)]
//! #[serde(default)]
//! struct Prefs {
//! #[serde(with = "craft_keymap::keymap::overrides_list")]
//! shortcuts: Overrides,
//! }
//!
//! impl Settings for Prefs {
//! const APP_ID: &'static str = "acmecraft";
//! const SCHEMA_VERSION: u32 = 1;
//! }
//!
//! # let catalog = Vec::new();
//! let (mut store, _report) = SettingsStore::<Prefs>::open(Location::Auto);
//! 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();
//!
//! // 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, text_editing_chords,
};
pub use scope::{Active, MAX_SCOPE_NAME, Scope, ScopeKind, Scopes};
+40
View File
@@ -0,0 +1,40 @@
//! 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};
// 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`, for
/// [`Keymap::with_reserved`](crate::Keymap::with_reserved).
pub fn system(platform: Platform) -> Vec<Chord> {
let list = match platform {
Platform::Mac => MAC,
Platform::Windows => WINDOWS,
Platform::Linux => LINUX,
};
list.iter().filter_map(|t| Chord::parse(t).ok()).collect()
}
+206
View File
@@ -0,0 +1,206 @@
//! 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 `:` 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, one with `:` or a control
/// character, or one with whitespace at either end, which binding text would lose.
pub fn new(name: impl Into<String>) -> Option<Scope> {
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());
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<D: Deserializer<'de>>(deserializer: D) -> Result<Scope, D::Error> {
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<String>,
contexts: Vec<String>,
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<u8> {
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<bool> {
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),
}
}
}
+178
View File
@@ -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::<Trigger>(&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::<Chord>("\"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"))));
}
+455
View File
@@ -0,0 +1,455 @@
#![cfg(feature = "egui")]
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};
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 {
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 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"]),
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(catalog, 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<Event>) -> 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<String>, Vec<Event>) {
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_stay_with_the_app_by_default() {
let km = dispatch_keymap();
let mut d = Dispatcher::new();
// 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"]);
}
#[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();
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 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 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 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();
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]
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_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 `@`: 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), 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);
// 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());
let (ran, _) = run(&mut d, &km, &typing, frame(3.0, alt_gr, vec![press(EguiKey::Q, alt_gr)]));
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 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();
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")];
let trigger = Trigger::single(chord("M"));
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]
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 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();
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)]);
}
+832
View File
@@ -0,0 +1,832 @@
//! 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, NoChangeReason, 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<Binding> {
texts.iter().map(|t| b(t)).collect()
}
fn command(id: impl Into<CommandRef>, 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 catalog() -> Vec<Bindable> {
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+;"]).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"]),
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(catalog(), 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<CommandRef>, texts: &[&str]) {
let c = id.into();
assert_eq!(km.bindings(&c), bindings(texts), "{}", c.key());
}
#[test]
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");
assert_eq!(normalize_label("SHOW/HIDE Guides"), "show/hide guides");
assert_eq!(normalize_label("Preferences: General…"), "preferences general");
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 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"]);
// 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 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 {
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, 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+Q"]);
has(&km, "view.goToPage", &["Cmd+J"]);
has(&km, "file.save", &["Cmd+S"]);
has(&km, "edit.duplicate", &["Cmd+Alt+Shift+D"]);
let rows = |failed: &[Failed]| -> Vec<(String, String, FailedChange, Vec<String>)> {
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::<Vec<_>>())
};
assert_eq!(
rows(&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, &[]),
]
);
assert_eq!(r.imported, 0);
assert!(r.conflicts_cleared.is_empty());
let v = serde_json::to_value(&r).unwrap();
assert_eq!(
v["failed"][1],
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", &[]);
// 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!(rows(&r.failed), [row("file.save", "Save", FailedChange::Bind, &["Cmd+Alt+J"])]);
assert!(r.skipped.is_empty(), "{:?}", r.skipped);
assert_eq!(r.imported, 1);
}
#[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"]);
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");
}
#[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() {
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<ForeignEntry> = 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::<String>::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 catalog whose labels share words with every unmatched entry below, so each
// suggestion scores every command.
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.
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<ForeignEntry> = (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::<Vec<_>>();
let mut top = names(&v);
top.sort();
assert_eq!(
top,
[
"approximated",
"changed",
"conflictsCleared",
"failed",
"imported",
"matchedWithoutChange",
"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 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");
assert_eq!(v["changed"][0]["from"], json!(["Cmd+W"]));
}
fn import_into(catalog: Vec<Bindable>, entries: Vec<ForeignEntry>, 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)
}
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 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…", &[], &[]),
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();
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, 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.
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 catalog path.
entry(None, &["Character", "All Caps"], &[(d, "Ctrl+F7")], Flavor::Windows),
];
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"]);
has(&km, "swatches.new", &["Cmd+F4"]);
has(&km, "character.smallCaps", &["Cmd+F5"]);
has(&km, "gradient.new", &[]);
assert_eq!(
unmatched(&r),
[
("History > Justification...", UnmatchedReason::NoMatch),
("Color > New Swatch", UnmatchedReason::Ambiguous),
("Character > All Caps", UnmatchedReason::NoMatch)
]
);
}
#[test]
fn aliases_match_like_labels() {
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"),
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(catalog, 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 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(),
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(catalog, 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 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.
let mut entries: Vec<ForeignEntry> = (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(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");
assert_eq!(r.suggestions.len(), 1);
assert_eq!(r.suggestions[0].candidates, [CommandRef::new("edit.checkSpelling")]);
assert_eq!(r.truncated, 0);
}
fn pages_catalog() -> Vec<Bindable> {
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_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);
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<String> = 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_catalog(), 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_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_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::<Vec<_>>(), [("layout.pages.insert", SkipReason::Taken)]);
}
+665
View File
@@ -0,0 +1,665 @@
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 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(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"));
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(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 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]),
(TypingRule::CommandKeysOnly, [false, true, true, false]),
(TypingRule::AllWait, [false, false, false, false]),
];
for (rule, fires) in cases {
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}");
assert_eq!(press(&km, key, &Active::NONE), run(id), "{rule:?} {key} not typing");
}
}
}
#[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![
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(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");
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 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();
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 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());
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 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(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(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 catalog = 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(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()
};
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<Trigger> = 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:?}");
// 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.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();
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.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 catalog: Vec<Bindable> = (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(catalog, 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_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(MAX_COMMANDS, 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(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(MAX_COMMANDS, 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 catalog: Vec<Bindable> = (0..MAX_COMMANDS).map(|n| app(&format!("c.{n}"), &[])).collect();
let mut km = Keymap::new(catalog, panels(MAX_BINDINGS), Platform::Mac);
let list: Vec<Binding> = (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 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", &[])];
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(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));
assert_eq!(km.set_bindings(&dup, vec![], Policy::Steal), Err(AssignError::Full));
assert!(!km.clear(&copy));
assert!(!km.remove(&copy, &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(&copy), 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 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(&copy, b("Nowhere: Cmd+K"), Policy::Steal), Err(AssignError::UnknownScope(scope("Nowhere"))));
assert!(km.assign(&copy, b("Timeline: Cmd+K"), Policy::Steal).is_ok(), "a catalog scope");
assert!(km.assign(&copy, 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(&copy), 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 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(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");
assert!(km.reset(&cmd("edit.copy")));
assert_eq!(km.overrides().get("edit.copy"), None);
}
#[test]
fn entries_with_nothing_usable_keep_the_defaults() {
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(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")]);
assert!(km.bindings(&cmd("edit.undo")).is_empty());
}
#[test]
fn overrides_hold_only_what_differs_from_the_defaults() {
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(&copy, 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(&copy)[1], Binding::in_scope(Trigger::parse("Cmd+K").unwrap(), scope("Timeline")));
assert!(km.remove(&copy, &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(&copy, vec![b("Cmd+Shift+C")], Policy::Steal).unwrap();
assert!(km.reset(&copy));
assert!(km.overrides().is_empty());
}
#[test]
fn edits_keep_the_texts_this_build_cannot_use() {
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(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::<Vec<_>>());
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(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.
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 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(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(catalog, Scopes::new(), Platform::Mac).with_overrides(serde_json::from_str(&saved).unwrap());
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::<Overrides>(&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::<Overrides>(&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::<Overrides>(&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 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()));
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::<Overrides>(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::<Vec<_>>(), [("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}");
}
}
#[test]
fn reset_removes_hand_written_variants_of_a_key() {
let layers = CommandRef::with_params("window.panel", json!({"panel": "layers"}));
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(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");
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(catalog.clone(), Scopes::new(), Platform::Mac).with_overrides(km.overrides().clone());
assert_eq!(again.bindings(&layers), vec![b("F7")]);
}
+123
View File
@@ -0,0 +1,123 @@
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,
#[serde(with = "craft_keymap::keymap::overrides_list")]
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<Prefs> {
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 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(catalog, 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}");
}
}