mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 19:51:26 -05:00
shortcuts-w6: net change of 1 commits
- shortcuts-w6: written from its sheet
This commit is contained in:
@@ -7,39 +7,41 @@
|
||||
//! command (or a text field its own undo). A few chords never reach a page at all (Safari's
|
||||
//! `Cmd+L`, Chrome's `Cmd+T`, `Cmd+W` and `Cmd+N`): the browser keeps those.
|
||||
|
||||
use craft::keymap::Chord;
|
||||
// PLAN: assumed path `craft::ui::runtime::commands` for the ui contract's `commands` module.
|
||||
use craft::ui::runtime::commands;
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
/// Whether the browser's own action for a key press is cancelled. `key` is the event's `key` (the
|
||||
/// character typed), `code` its `code` (the key's position), `modifiers` as eframe reports them,
|
||||
/// and `alt_graph` whether AltGr is held.
|
||||
/// The chord of a key press the browser's own action may be cancelled for. `key` is the event's
|
||||
/// `key` (the character typed), `code` its `code` (the key's position), `modifiers` as eframe
|
||||
/// reports them, and `alt_graph` whether AltGr is held.
|
||||
///
|
||||
/// Only Cmd and Ctrl presses: a plain or Shift press types (cancelling it would drop the
|
||||
/// character it types), and so does AltGr, which Windows reports as Ctrl and Alt held. Cut, Copy
|
||||
/// and Paste (with any other modifiers) are left to the browser, whose clipboard events carry
|
||||
/// their text, and Reload too, as eframe leaves them.
|
||||
pub(crate) fn kept_from_browser(key: &str, code: &str, modifiers: Modifiers, alt_graph: bool) -> bool {
|
||||
pub(crate) fn browser_chord(key: &str, code: &str, modifiers: Modifiers, alt_graph: bool) -> Option<Chord> {
|
||||
if !(modifiers.ctrl || modifiers.mac_cmd) || alt_graph {
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
if matches!(Key::from_name(key).or(Key::from_name(code)), Some(Key::C | Key::V | Key::X | Key::R)) {
|
||||
return false;
|
||||
let key = Key::from_name(key).or(Key::from_name(code))?;
|
||||
if matches!(key, Key::C | Key::V | Key::X | Key::R) {
|
||||
return None;
|
||||
}
|
||||
vectorcraft_ui_egui::shortcuts::runs_a_shortcut(key, code, modifiers)
|
||||
vectorcraft_ui_egui::keymap::chord_of_press(key, modifiers, vectorcraft_ui_egui::keymap::platform())
|
||||
}
|
||||
|
||||
/// Leave a paste to its Paste event (#5555). eframe's web runner reports a Cmd+V press both as the
|
||||
/// key press and, with the clipboard's text, as a Paste event (the browser's `paste` comes in the
|
||||
/// same task as the `keydown`, so both are in one frame's input); the app pastes on each, as egui's
|
||||
/// window integration sends only the Paste. With a Paste in `events`, the paste key's press is
|
||||
/// dropped; its release stays, so the paste chord is still followed (`PasteChord`). A Cmd+V without
|
||||
/// a Paste (a clipboard with no text) keeps its press.
|
||||
pub(crate) fn drop_paste_key_presses(events: &mut Vec<egui::Event>) {
|
||||
if !events.iter().any(|e| matches!(e, egui::Event::Paste(_))) {
|
||||
return;
|
||||
}
|
||||
events.retain(|e| !matches!(e, egui::Event::Key { key: Key::V, pressed: true, modifiers, .. } if modifiers.command));
|
||||
/// Whether the browser's own action for a key press is cancelled: the keymap in effect, the
|
||||
/// user's shortcuts included, binds its chord. Before the first frame nothing is bound.
|
||||
pub(crate) fn kept_from_browser(ctx: &egui::Context, key: &str, code: &str, modifiers: Modifiers, alt_graph: bool) -> bool {
|
||||
browser_chord(key, code, modifiers, alt_graph).is_some_and(|chord| commands::holder(ctx, &chord).is_some())
|
||||
}
|
||||
|
||||
/// The egui context of the running app; empty until the first start fills it, and filled again by
|
||||
/// every restart after the graphics were lost.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) type ContextSlot = std::rc::Rc<std::cell::RefCell<Option<egui::Context>>>;
|
||||
|
||||
/// The modifiers of a key event as eframe reports them to egui (its `modifiers_from_kb_event`).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn modifiers(e: &web_sys::KeyboardEvent) -> Modifiers {
|
||||
@@ -63,17 +65,19 @@ fn to_the_app(e: &web_sys::KeyboardEvent) -> bool {
|
||||
}
|
||||
|
||||
/// Cancel the page's default action for [`kept_from_browser`] presses, before eframe's listener
|
||||
/// sees the event (it doesn't stop it).
|
||||
/// sees the event (it doesn't stop it). The framework cancels no browser default itself, so this
|
||||
/// listener stays; it reads the context from `ctx` because it is installed before the first frame.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn keep_app_keys() {
|
||||
pub(crate) fn keep_app_keys(ctx: ContextSlot) {
|
||||
use wasm_bindgen::JsCast as _;
|
||||
let Some(window) = web_sys::window() else { return };
|
||||
let on_key = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::KeyboardEvent)>::new(|e: web_sys::KeyboardEvent| {
|
||||
let on_key = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::KeyboardEvent)>::new(move |e: web_sys::KeyboardEvent| {
|
||||
// An IME's keys are its own until it commits.
|
||||
if e.is_composing() || !to_the_app(&e) {
|
||||
return;
|
||||
}
|
||||
if kept_from_browser(&e.key(), &e.code(), modifiers(&e), e.get_modifier_state("AltGraph")) {
|
||||
let Some(ctx) = ctx.borrow().clone() else { return };
|
||||
if kept_from_browser(&ctx, &e.key(), &e.code(), modifiers(&e), e.get_modifier_state("AltGraph")) {
|
||||
e.prevent_default();
|
||||
}
|
||||
});
|
||||
@@ -87,6 +91,7 @@ pub(crate) fn keep_app_keys() {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft::keymap::{Key as ChordKey, Mods};
|
||||
|
||||
/// Cmd as egui reports it on this platform: the Command key on macOS, Ctrl elsewhere.
|
||||
fn cmd() -> Modifiers {
|
||||
@@ -95,15 +100,15 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_keymaps_chords_are_kept_from_the_browser() {
|
||||
for (key, code, mods) in [
|
||||
("=", "Equal", cmd()),
|
||||
("-", "Minus", cmd()),
|
||||
("0", "Digit0", cmd()),
|
||||
("z", "KeyZ", cmd()),
|
||||
("Z", "KeyZ", cmd() | Modifiers::SHIFT),
|
||||
("[", "BracketLeft", cmd()),
|
||||
for (key, code, mods, want) in [
|
||||
("=", "Equal", cmd(), Chord::new(Mods::CMD, ChordKey::Equals)),
|
||||
("-", "Minus", cmd(), Chord::parse("Cmd+-").unwrap()),
|
||||
("0", "Digit0", cmd(), Chord::parse("Cmd+0").unwrap()),
|
||||
("z", "KeyZ", cmd(), Chord::parse("Cmd+Z").unwrap()),
|
||||
("Z", "KeyZ", cmd() | Modifiers::SHIFT, Chord::parse("Cmd+Shift+Z").unwrap()),
|
||||
("[", "BracketLeft", cmd(), Chord::parse("Cmd+[").unwrap()),
|
||||
] {
|
||||
assert!(kept_from_browser(key, code, mods, false), "{key} ({code}) {mods:?}");
|
||||
assert_eq!(browser_chord(key, code, mods, false), Some(want), "{key} ({code}) {mods:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,38 +126,11 @@ mod tests {
|
||||
("V", "KeyV", cmd() | Modifiers::SHIFT),
|
||||
("r", "KeyR", cmd()),
|
||||
] {
|
||||
assert!(!kept_from_browser(key, code, mods, false), "{key} ({code}) {mods:?}");
|
||||
assert!(browser_chord(key, code, mods, false).is_none(), "{key} ({code}) {mods:?}");
|
||||
}
|
||||
// AltGr+Z types ż on a Polish layout, reported as Ctrl and Alt held on Windows.
|
||||
let ctrl_alt = Modifiers::CTRL | Modifiers::COMMAND | Modifiers::ALT;
|
||||
assert!(!kept_from_browser("ż", "KeyZ", ctrl_alt, true));
|
||||
assert!(!kept_from_browser("}", "Digit0", ctrl_alt, true));
|
||||
}
|
||||
|
||||
fn key(key: Key, pressed: bool, modifiers: Modifiers) -> egui::Event {
|
||||
egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paste_chord_pastes_once() {
|
||||
// Cmd+V and Cmd+Shift+V (Paste in Place): the press goes, the Paste and the release stay.
|
||||
for mods in [cmd(), cmd() | Modifiers::SHIFT] {
|
||||
let mut events = vec![key(Key::V, true, mods), egui::Event::Paste("<svg/>".into()), key(Key::V, false, mods)];
|
||||
drop_paste_key_presses(&mut events);
|
||||
assert_eq!(events, vec![egui::Event::Paste("<svg/>".into()), key(Key::V, false, mods)], "{mods:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_without_a_paste_stay() {
|
||||
// No text on the clipboard: no Paste event, so the press is the paste chord's only report.
|
||||
let mut events = vec![key(Key::V, true, cmd()), key(Key::V, false, cmd())];
|
||||
drop_paste_key_presses(&mut events);
|
||||
assert_eq!(events.len(), 2);
|
||||
// Typing V, and other chords, beside a paste.
|
||||
let typed = vec![key(Key::V, true, Modifiers::NONE), key(Key::C, true, cmd()), egui::Event::Paste("a".into())];
|
||||
let mut events = typed.clone();
|
||||
drop_paste_key_presses(&mut events);
|
||||
assert_eq!(events, typed);
|
||||
assert!(browser_chord("ż", "KeyZ", ctrl_alt, true).is_none());
|
||||
assert!(browser_chord("}", "Digit0", ctrl_alt, true).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
+273
-413
@@ -1,17 +1,17 @@
|
||||
//! VectorCraft's keymap on [`craft_keymap`]: the catalogue of everything a shortcut can run, the
|
||||
//! bridge between VectorCraft's chord spellings and the crate's, and the stored form of the
|
||||
//! user's overrides.
|
||||
//! bridge between VectorCraft's chord spellings and the crate's, and the loader of the user's
|
||||
//! saved shortcut sets.
|
||||
//!
|
||||
//! Entry keys are VectorCraft's everywhere outside this module: a command id, `tool:<id>`, or
|
||||
//! `panel:<id>` for the Window menu item showing a panel (`window.panel {panel}`), `effect:<id>`
|
||||
//! for an Effect menu item, or `plugin:<id>` for a filter plug-in's Object › Plug-ins item
|
||||
//! (`plugin.dialog {id}`). Chord texts outside it are VectorCraft's too (`Cmd+Shift+]`, `Comma`,
|
||||
//! `Period`, `~` for the backtick key, `=` for Plus with modifiers). Inside an [`Overrides`] keys
|
||||
//! and texts are the crate's.
|
||||
//! (`plugin.dialog {id}`). Chord texts read by [`stored`] are VectorCraft's (`Cmd+Shift+]`,
|
||||
//! `Comma`, `Period`, `~` for the backtick key, `=` for Plus with modifiers). Inside an
|
||||
//! [`Overrides`] keys and texts are the crate's.
|
||||
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
use std::sync::RwLock;
|
||||
|
||||
use craft_keymap::{Bindable, Binding, Chord, CommandRef, Key, Keymap, Kind, Lookup, Mods, Overrides, Platform, Scope, Scopes};
|
||||
use craft_keymap::{Binding, Chord, CommandDef, CommandKind, CommandRef, Key, Mods, Overrides, Platform, Scope};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::shortcut_editor::{self, EffectItem, Entry, Snapshot};
|
||||
@@ -106,26 +106,12 @@ pub fn stored_key(key: &str) -> String {
|
||||
|
||||
/// An Effect menu item's [`Overrides`] key under the command its item does not run now
|
||||
/// (`effect.apply` for one that opens its dialog, and the other way round).
|
||||
fn other_stored_key(key: &str) -> Option<String> {
|
||||
pub(crate) fn other_stored_key(key: &str) -> Option<String> {
|
||||
let effect = key.strip_prefix("effect:")?;
|
||||
let other = if command_of(key).id == "effect.apply" { "effect.dialog" } else { "effect.apply" };
|
||||
Some(CommandRef::with_params(other, json!({ "effect": effect })).key())
|
||||
}
|
||||
|
||||
/// The texts of an entry's override, saved under its [`stored_key`] or, for an Effect menu item,
|
||||
/// under its [`other_stored_key`].
|
||||
pub(crate) fn stored_texts<'a>(overrides: &'a Overrides, key: &str) -> Option<&'a [String]> {
|
||||
overrides.get(&stored_key(key)).or_else(|| other_stored_key(key).and_then(|k| overrides.get(&k)))
|
||||
}
|
||||
|
||||
/// Removes an entry's override, under either key an Effect menu item's can have.
|
||||
pub(crate) fn remove_override(overrides: &mut Overrides, key: &str) {
|
||||
overrides.remove(&stored_key(key));
|
||||
if let Some(k) = other_stored_key(key) {
|
||||
overrides.remove(&k);
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry key of an [`Overrides`] key.
|
||||
pub fn entry_of_stored(key: &str) -> String {
|
||||
CommandRef::parse_key(key)
|
||||
@@ -135,65 +121,54 @@ pub fn entry_of_stored(key: &str) -> String {
|
||||
|
||||
// ---------- chord texts ----------
|
||||
|
||||
/// Reads VectorCraft chord text. `+` and `=` are one key: Plus alone, Equals with modifiers.
|
||||
pub fn vc_chord(text: &str) -> Option<Chord> {
|
||||
let sc = crate::shortcuts::parse(text.trim())?;
|
||||
let key = Key::from_egui(sc.logical_key)?;
|
||||
let m = sc.modifiers;
|
||||
let mods = Mods { cmd: m.command || m.mac_cmd, ctrl: m.ctrl, alt: m.alt, shift: m.shift };
|
||||
let key = match key {
|
||||
/// Plus alone is Plus; with modifiers the key is Equals (`+` is Shift+`=` on many layouts, so a
|
||||
/// `Cmd+=` chord answers `+` however it is typed). Every reader of a chord's key goes through it.
|
||||
fn plus_rule(mods: Mods, key: Key) -> Key {
|
||||
match key {
|
||||
Key::Plus | Key::Equals if mods.is_none() => Key::Plus,
|
||||
Key::Plus | Key::Equals => Key::Equals,
|
||||
k => k,
|
||||
};
|
||||
Some(Chord::new(mods, key))
|
||||
}
|
||||
|
||||
/// VectorCraft's text of a chord, as `shortcut_editor::format` writes it.
|
||||
pub fn vc_format(chord: &Chord) -> String {
|
||||
let m = chord.mods;
|
||||
let mods = egui::Modifiers { alt: m.alt, ctrl: m.ctrl, shift: m.shift, mac_cmd: false, command: m.cmd };
|
||||
shortcut_editor::format(&egui::KeyboardShortcut::new(mods, chord.key.to_egui()))
|
||||
}
|
||||
|
||||
/// VectorCraft's text of a binding; a scoped or double binding (hand-written) keeps the crate's.
|
||||
pub fn binding_text(b: &Binding) -> String {
|
||||
if b.scope.is_none() && !b.trigger.double { vc_format(&b.trigger.chord) } else { b.to_string() }
|
||||
}
|
||||
|
||||
/// VectorCraft text → the crate's. Text both read as one chord stays as written (`Comma`,
|
||||
/// `Ctrl+Cmd+H`), so it is saved back as the user wrote it; text neither reads is kept for
|
||||
/// `Keymap::problems`.
|
||||
pub fn vc_to_crate(text: &str) -> String {
|
||||
if text.trim().is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
match vc_chord(text) {
|
||||
Some(c) if Binding::parse(text).is_ok_and(|b| b == Binding::new(c)) => text.to_string(),
|
||||
Some(c) => c.to_string(),
|
||||
None => text.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The crate's text → VectorCraft's. The crate's canonical text is rewritten; other text is
|
||||
/// what [`vc_to_crate`] kept as written, or text that does not parse.
|
||||
pub fn crate_to_vc(text: &str) -> String {
|
||||
match Binding::parse(text) {
|
||||
Ok(b) if b.to_string() == text => binding_text(&b),
|
||||
_ => text.to_string(),
|
||||
}
|
||||
/// The chord a key press with `modifiers` makes on `platform`; `None` for a key the crate does
|
||||
/// not name.
|
||||
pub fn chord_of_press(key: egui::Key, modifiers: egui::Modifiers, platform: Platform) -> Option<Chord> {
|
||||
let key = Key::from_egui(key)?;
|
||||
let mods = Mods::from_egui(&modifiers, platform);
|
||||
Some(Chord::new(mods, plus_rule(mods, key)))
|
||||
}
|
||||
|
||||
/// A default shortcut of the catalogue.
|
||||
fn vc_binding(text: &str) -> Option<Binding> {
|
||||
vc_chord(text).map(Binding::new)
|
||||
/// A VectorCraft chord text as the menus show it on this platform; text that is no chord is
|
||||
/// shown as written.
|
||||
pub(crate) fn chord_text(s: &str) -> String {
|
||||
stored::parse_vc(s).map_or_else(|| s.to_string(), |c| c.display(platform()))
|
||||
}
|
||||
|
||||
// ---------- catalogue ----------
|
||||
|
||||
/// A default shortcut of the catalogue.
|
||||
fn vc_binding(text: &str) -> Option<Binding> {
|
||||
stored::parse_vc(text).map(Binding::new)
|
||||
}
|
||||
|
||||
/// The default bindings of an entry on `p`: its default text, then the aliases the registry
|
||||
/// spec does not carry, without repeats.
|
||||
fn defaults_of(key: &str, p: Platform) -> Vec<Binding> {
|
||||
let mut texts: Vec<&str> = shortcut_editor::default_on(key, p).into_iter().collect();
|
||||
texts.extend(default_aliases(key, p).iter().copied());
|
||||
let mut out: Vec<Binding> = vec![];
|
||||
for b in texts.into_iter().filter_map(vc_binding) {
|
||||
if !out.contains(&b) {
|
||||
out.push(b);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every listed entry as the crate sees it, in dispatch priority: commands (engine, then UI),
|
||||
/// panels, tools. Each tool is its own group: tools never cycle.
|
||||
fn catalogue(snapshot: &Snapshot, p: Platform) -> Vec<Bindable> {
|
||||
pub(crate) fn catalog_defs(platform: Platform, snapshot: &Snapshot) -> Vec<CommandDef> {
|
||||
let rank = |e: &Entry| {
|
||||
if e.is_tool {
|
||||
2
|
||||
@@ -210,22 +185,14 @@ fn catalogue(snapshot: &Snapshot, p: Platform) -> Vec<Bindable> {
|
||||
.map(|e| {
|
||||
let mut path: Vec<String> = e.group.split(" › ").filter(|s| !s.is_empty()).map(str::to_string).collect();
|
||||
path.push(e.label.clone());
|
||||
let mut b = Bindable::new(command_in(&e.key, &snapshot.effects), e.label.clone(), Scope::app()).with_path(path);
|
||||
let mut def = CommandDef::new(command_in(&e.key, &snapshot.effects), e.label.clone(), Scope::app()).with_path(path);
|
||||
if let Some(tool) = e.key.strip_prefix("tool:") {
|
||||
b = b.with_kind(Kind::Tool { group: Some(tool.to_string()) });
|
||||
def = def.with_kind(CommandKind::Tool { group: Some(tool.to_string()) });
|
||||
}
|
||||
if TOGGLES.contains(&e.key.as_str()) {
|
||||
b = b.toggle();
|
||||
def = def.toggle();
|
||||
}
|
||||
if let Some(d) = shortcut_editor::default_on(&e.key, p).and_then(vc_binding) {
|
||||
b = b.with_default(d);
|
||||
}
|
||||
for alias in default_aliases(&e.key, p) {
|
||||
if let Some(d) = vc_binding(alias) {
|
||||
b = b.with_default(d);
|
||||
}
|
||||
}
|
||||
b
|
||||
defaults_of(&e.key, platform).into_iter().fold(def, CommandDef::with_default)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -238,6 +205,7 @@ fn default_aliases(key: &str, p: Platform) -> &'static [&'static str] {
|
||||
"edit.paste" if !p.is_mac() => &["F4"],
|
||||
"paint.lastColor" => &["Shift+,"],
|
||||
"paint.lastGradient" => &["Shift+."],
|
||||
"edit.clear" => &["Backspace"],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
@@ -269,173 +237,141 @@ pub fn note_os(ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The keymap with the default shortcuts for [`platform`] and the plug-ins installed now.
|
||||
pub fn template() -> Arc<Keymap> {
|
||||
template_for(&shortcut_editor::snapshot())
|
||||
}
|
||||
|
||||
/// The keymap with the default shortcuts for [`platform`] and the entries of `snapshot`, built
|
||||
/// once per platform and plug-in revision. Each platform has its own cell, because the web build
|
||||
/// learns the browser's platform only after the first frame.
|
||||
pub(crate) fn template_for(snapshot: &Snapshot) -> Arc<Keymap> {
|
||||
/// A template and the plug-in revision it was built for.
|
||||
type Built = Option<(u64, Arc<Keymap>)>;
|
||||
static TEMPLATES: Mutex<[Built; 3]> = Mutex::new([None, None, None]);
|
||||
let p = platform();
|
||||
let at = match p {
|
||||
Platform::Mac => 0,
|
||||
Platform::Windows => 1,
|
||||
_ => 2,
|
||||
};
|
||||
let cached = TEMPLATES.lock().unwrap_or_else(|e| e.into_inner())[at].clone();
|
||||
if let Some((_, km)) = cached.filter(|(revision, _)| *revision == snapshot.revision) {
|
||||
return km;
|
||||
}
|
||||
let km = Arc::new(keymap_for(p, snapshot));
|
||||
let mut cells = TEMPLATES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if cells[at].as_ref().is_none_or(|(revision, _)| *revision <= snapshot.revision) {
|
||||
cells[at] = Some((snapshot.revision, km.clone()));
|
||||
}
|
||||
km
|
||||
}
|
||||
|
||||
/// The default keymap of `p` with the entries of `snapshot`. The chords the operating system
|
||||
/// takes can't be assigned.
|
||||
pub(crate) fn keymap_for(p: Platform, snapshot: &Snapshot) -> Keymap {
|
||||
Keymap::new(catalogue(snapshot, p), Scopes::new(), p).with_reserved(craft_keymap::reserved::system(p))
|
||||
}
|
||||
|
||||
/// The keymap with `overrides` applied.
|
||||
pub fn keymap_with(overrides: &Overrides) -> Keymap {
|
||||
keymap_in(&shortcut_editor::snapshot(), overrides)
|
||||
}
|
||||
|
||||
/// The keymap of `snapshot`'s entries with `overrides` applied, each Effect menu item's shortcut
|
||||
/// under the command its item runs now.
|
||||
pub(crate) fn keymap_in(snapshot: &Snapshot, overrides: &Overrides) -> Keymap {
|
||||
let defaults = template_for(snapshot);
|
||||
let moved = effect_keys_in(overrides, &snapshot.effects);
|
||||
let resolved = edit_alias_overrides(&moved, defaults.platform());
|
||||
defaults.as_ref().clone().with_overrides(resolved)
|
||||
}
|
||||
|
||||
/// When a saved override assigns F2, F3 or F4 elsewhere without changing its edit command,
|
||||
/// keep only that edit command's primary shortcut so the saved assignment runs.
|
||||
pub(crate) fn edit_alias_overrides(overrides: &Overrides, p: Platform) -> Overrides {
|
||||
let mut resolved = overrides.clone();
|
||||
if p.is_mac() {
|
||||
return resolved;
|
||||
}
|
||||
for (key, primary, alias) in EDIT_FUNCTION_KEYS {
|
||||
if overrides.get(key).is_some() {
|
||||
continue;
|
||||
}
|
||||
let Some(binding) = vc_binding(alias) else { continue };
|
||||
let assigned_elsewhere = overrides.iter().any(|(other, texts)| {
|
||||
other != key
|
||||
&& shortcut_editor::entry(&entry_of_stored(other)).is_some()
|
||||
&& texts.iter().any(|text| Binding::parse(text).is_ok_and(|b| b == binding))
|
||||
});
|
||||
if assigned_elsewhere {
|
||||
let _ = resolved.insert(key, vec![vc_to_crate(primary)]);
|
||||
}
|
||||
}
|
||||
resolved
|
||||
}
|
||||
|
||||
/// The command a chord runs, the first for tools sharing it.
|
||||
pub fn lookup(km: &Keymap, chord: &Chord) -> Option<CommandRef> {
|
||||
match km.lookup(chord, false, &craft_keymap::Active::NONE) {
|
||||
Lookup::None => None,
|
||||
Lookup::Run(c) => Some(c),
|
||||
Lookup::Cycle(v) => v.into_iter().next(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Effective shortcut text of an entry key under `km`: the default's own text while the entry
|
||||
/// has its defaults. An entry the catalogue lacks reads its stored text.
|
||||
pub fn effective_with(km: &Keymap, key: &str) -> Option<String> {
|
||||
let command = command_of(key);
|
||||
if km.bindable(&command).is_none() {
|
||||
return match stored_texts(km.overrides(), key) {
|
||||
Some(texts) => texts.first().filter(|t| !t.trim().is_empty()).map(|t| crate_to_vc(t)),
|
||||
None => shortcut_editor::default_of(key).map(str::to_string),
|
||||
};
|
||||
}
|
||||
let now = km.bindings(&command);
|
||||
if now == km.default_bindings(&command) {
|
||||
return shortcut_editor::default_of(key).map(str::to_string);
|
||||
}
|
||||
let first = now.first()?;
|
||||
// The text as stored, when it is this binding's: the user's spelling.
|
||||
let stored = km.overrides().get(&stored_key(key)).and_then(|t| t.first()).filter(|t| Binding::parse(t).is_ok_and(|b| b == *first));
|
||||
Some(stored.map_or_else(|| binding_text(first), |t| crate_to_vc(t)))
|
||||
}
|
||||
|
||||
// ---------- overrides ----------
|
||||
|
||||
/// Sets an entry's shortcut in VectorCraft's terms: `""` for none.
|
||||
pub fn set_override(overrides: &mut Overrides, key: &str, text: &str) {
|
||||
let texts = if text.trim().is_empty() { vec![] } else { vec![vc_to_crate(text)] };
|
||||
if let Some(k) = other_stored_key(key) {
|
||||
overrides.remove(&k);
|
||||
}
|
||||
// Only an over-long key or text is refused; such an entry could not be stored anyway.
|
||||
let _ = overrides.insert(stored_key(key), texts);
|
||||
}
|
||||
|
||||
/// Overrides holding `(entry key, shortcut)` pairs in VectorCraft's terms.
|
||||
pub fn overrides_from(pairs: &[(&str, &str)]) -> Overrides {
|
||||
let mut out = Overrides::new();
|
||||
for (k, t) in pairs {
|
||||
set_override(&mut out, k, t);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An entry's stored shortcut in VectorCraft's terms (`""` for none), when it has an override.
|
||||
pub fn override_text(overrides: &Overrides, key: &str) -> Option<String> {
|
||||
stored_texts(overrides, key).map(|t| t.first().map(|t| crate_to_vc(t)).unwrap_or_default())
|
||||
}
|
||||
|
||||
pub fn has_override(overrides: &Overrides, key: &str) -> bool {
|
||||
stored_texts(overrides, key).is_some()
|
||||
}
|
||||
|
||||
/// Serde for [`Overrides`] in VectorCraft's own form, which every earlier version reads: a map
|
||||
/// of entry key → one shortcut text (`""` for none), with `panel:` keys and VectorCraft's
|
||||
/// spellings. Loading never fails: what cannot be used is dropped or kept for
|
||||
/// `Keymap::problems`, and only an entry's first text is kept.
|
||||
pub mod stored {
|
||||
use craft_keymap::Overrides;
|
||||
/// The loader of saved shortcut sets. [`profiles`] is the form this version writes; [`legacy`]
|
||||
/// reads the three keys earlier versions wrote (`shortcut_overrides`, `shortcut_set`,
|
||||
/// `shortcut_holds`), in VectorCraft's own spelling. Loading never fails: what cannot be used is
|
||||
/// dropped or kept for `Keymap::problems`, and only an entry's first text is kept.
|
||||
pub(crate) mod stored {
|
||||
use craft_keymap::{Binding, Chord, Key, Mods, Overrides, Platform, Profiles};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use super::{crate_to_vc, entry_of_stored, stored_key, vc_to_crate};
|
||||
use super::{EDIT_FUNCTION_KEYS, entry_of_stored, plus_rule, stored_key, vc_binding};
|
||||
use crate::shortcut_editor;
|
||||
|
||||
pub fn serialize<S: Serializer>(overrides: &Overrides, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.collect_map(overrides.iter().map(|(k, texts)| (entry_of_stored(k), texts.first().map(|t| crate_to_vc(t)).unwrap_or_default())))
|
||||
/// Serde `with` module of the saved [`Profiles`]: the crate's own form.
|
||||
pub(crate) mod profiles {
|
||||
use super::{Deserialize, Deserializer, Profiles, Serialize, Serializer};
|
||||
|
||||
/// Writes the sets.
|
||||
pub(crate) fn serialize<S: Serializer>(profiles: &Profiles, s: S) -> Result<S::Ok, S::Error> {
|
||||
profiles.serialize(s)
|
||||
}
|
||||
|
||||
/// Reads the sets.
|
||||
pub(crate) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Profiles, D::Error> {
|
||||
Profiles::deserialize(d)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Overrides, D::Error> {
|
||||
Ok(from_value(Value::deserialize(d)?))
|
||||
/// The sets that the three keys of earlier versions hold: the overrides on top of the set in
|
||||
/// use become a user set, through the crate's own name and size checks.
|
||||
pub(crate) fn legacy(overrides: &Value, set: Option<&str>, holds: &Value) -> Profiles {
|
||||
legacy_on(overrides, set, holds, super::platform())
|
||||
}
|
||||
|
||||
pub fn to_value(overrides: &Overrides) -> Value {
|
||||
struct Stored<'a>(&'a Overrides);
|
||||
impl Serialize for Stored<'_> {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
serialize(self.0, s)
|
||||
/// [`legacy`] on platform `p`.
|
||||
pub(super) fn legacy_on(overrides: &Value, set: Option<&str>, holds: &Value, p: Platform) -> Profiles {
|
||||
let mut ov = from_value(overrides.clone());
|
||||
add_holds(&mut ov, holds);
|
||||
pin_edit_primaries(&mut ov, p);
|
||||
let mut profiles = Profiles::default();
|
||||
if let Some(name) = set {
|
||||
// A name no built-in set has (a custom one) leaves the default set in use.
|
||||
let _ = profiles.select(shortcut_editor::set_name(name), &shortcut_editor::BUILTINS);
|
||||
}
|
||||
if !ov.is_empty() {
|
||||
// Refused only over the crate's limits, which drop the entries that exceed them.
|
||||
let _ = profiles.store(ov, &shortcut_editor::BUILTINS, shortcut_editor::CUSTOM);
|
||||
}
|
||||
profiles
|
||||
}
|
||||
|
||||
/// Adds each old hold shortcut (`"P"` under an entry) to that entry's list as `Hold P`. An
|
||||
/// entry with no override keeps its default shortcuts beside the hold.
|
||||
pub(crate) fn add_holds(overrides: &mut Overrides, holds: &Value) {
|
||||
let Some(holds) = holds.as_object() else { return };
|
||||
for (entry, text) in holds {
|
||||
let Some(text) = text.as_str() else { continue };
|
||||
let key = stored_key(entry);
|
||||
let mut texts: Vec<String> = match overrides.get(&key) {
|
||||
Some(t) => t.to_vec(),
|
||||
None => super::defaults_of(entry, super::platform()).iter().map(ToString::to_string).collect(),
|
||||
};
|
||||
texts.push(format!("Hold {}", parse_vc(text).map_or_else(|| text.to_string(), |c| c.to_string())));
|
||||
// Refused only over the crate's limits.
|
||||
let _ = overrides.insert(key, texts);
|
||||
}
|
||||
}
|
||||
|
||||
/// When a saved override assigns F2, F3 or F4 elsewhere without changing its edit command,
|
||||
/// keep only that edit command's primary shortcut so the saved assignment runs.
|
||||
fn pin_edit_primaries(overrides: &mut Overrides, p: Platform) {
|
||||
if p.is_mac() {
|
||||
return;
|
||||
}
|
||||
for (key, primary, alias) in EDIT_FUNCTION_KEYS {
|
||||
if overrides.get(key).is_some() {
|
||||
continue;
|
||||
}
|
||||
let Some(binding) = vc_binding(alias) else { continue };
|
||||
let assigned_elsewhere = overrides.iter().any(|(other, texts)| {
|
||||
other != key
|
||||
&& shortcut_editor::entry(&entry_of_stored(other)).is_some()
|
||||
&& texts.iter().any(|text| Binding::parse(text).is_ok_and(|b| b == binding))
|
||||
});
|
||||
if assigned_elsewhere {
|
||||
let _ = overrides.insert(key, vec![vc_to_crate(primary)]);
|
||||
}
|
||||
}
|
||||
serde_json::to_value(Stored(overrides)).unwrap_or_else(|_| Value::Object(Map::new()))
|
||||
}
|
||||
|
||||
pub fn from_value(v: Value) -> Overrides {
|
||||
/// Reads VectorCraft chord text. `~` is the backtick key; `+` and `=` are one key: Plus alone,
|
||||
/// Equals with modifiers.
|
||||
pub(crate) fn parse_vc(text: &str) -> Option<Chord> {
|
||||
let text = text.trim();
|
||||
let (prefix, key) = if text == "+" {
|
||||
("", "+")
|
||||
} else if let Some(mods) = text.strip_suffix("++") {
|
||||
(mods.trim_end_matches('+'), "+")
|
||||
} else {
|
||||
text.rsplit_once('+').unwrap_or(("", text))
|
||||
};
|
||||
let with = |k: &str| if prefix.is_empty() { k.to_string() } else { format!("{prefix}+{k}") };
|
||||
let chord = match key {
|
||||
"+" | "=" => {
|
||||
let mods = if prefix.is_empty() {
|
||||
Mods { cmd: false, ctrl: false, alt: false, shift: false }
|
||||
} else {
|
||||
Chord::parse(&with("A")).ok()?.mods
|
||||
};
|
||||
Chord::new(mods, Key::Equals)
|
||||
}
|
||||
"~" => Chord::parse(&with("`")).ok()?,
|
||||
_ => Chord::parse(text).ok()?,
|
||||
};
|
||||
Some(Chord::new(chord.mods, plus_rule(chord.mods, chord.key)))
|
||||
}
|
||||
|
||||
/// VectorCraft text → the crate's. Text both read as one chord stays as written (`Comma`,
|
||||
/// `Ctrl+Cmd+H`), so it is saved back as the user wrote it; text neither reads is kept for
|
||||
/// `Keymap::problems`.
|
||||
fn vc_to_crate(text: &str) -> String {
|
||||
if text.trim().is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
match parse_vc(text) {
|
||||
Some(c) if Binding::parse(text).is_ok_and(|b| b == Binding::new(c)) => text.to_string(),
|
||||
Some(c) => c.to_string(),
|
||||
None => text.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The overrides of the map form (`entry key → one text`) or the crate's list form
|
||||
/// (`[{command, keys}]`).
|
||||
pub(crate) fn from_value(v: Value) -> Overrides {
|
||||
let entries: Vec<(String, Value)> = match v {
|
||||
Value::Object(m) => m.into_iter().collect(),
|
||||
// The crate's list form, `[{command, keys}]`, as a newer version might write it.
|
||||
Value::Array(items) => items
|
||||
.into_iter()
|
||||
.filter_map(|item| {
|
||||
@@ -468,221 +404,145 @@ pub mod stored {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::state::UiState;
|
||||
use std::collections::BTreeMap;
|
||||
use craft_keymap::{Active, Keymap, Lookup, Scopes, Trigger};
|
||||
|
||||
/// Earlier versions read the overrides as a map of one string per entry; a file this
|
||||
/// version writes must stay that.
|
||||
/// The settings of an earlier version: the three old keys in place of `shortcut_sets`.
|
||||
fn old_file(keys: Value, set: Option<&str>) -> UiState {
|
||||
let mut raw = serde_json::to_value(UiState::default()).unwrap();
|
||||
if let Some(o) = raw.as_object_mut() {
|
||||
o.remove("shortcut_sets");
|
||||
}
|
||||
raw["shortcut_overrides"] = keys;
|
||||
if let Some(set) = set {
|
||||
raw["shortcut_set"] = json!(set);
|
||||
}
|
||||
serde_json::from_value(raw).unwrap()
|
||||
}
|
||||
|
||||
fn active(ui: &UiState) -> &Overrides {
|
||||
ui.shortcut_sets.active_overrides(&shortcut_editor::BUILTINS)
|
||||
}
|
||||
|
||||
fn texts<'a>(ov: &'a Overrides, key: &str) -> Option<Vec<&'a str>> {
|
||||
ov.get(key).map(|t| t.iter().map(String::as_str).collect())
|
||||
}
|
||||
|
||||
/// A settings file in each earlier form loads into the same sets, and this version's file
|
||||
/// loads back equal.
|
||||
#[test]
|
||||
fn older_versions_read_the_saved_overrides() {
|
||||
let mut ui = UiState::default();
|
||||
set_override(&mut ui.shortcut_overrides, "tool:pen", "Shift+9");
|
||||
set_override(&mut ui.shortcut_overrides, "edit.preferences", "");
|
||||
set_override(&mut ui.shortcut_overrides, "panel:layers", "Cmd+Alt+Shift+F7");
|
||||
set_override(&mut ui.shortcut_overrides, "view.grid", "Cmd+Period");
|
||||
// An entry holding two texts (the crate keeps texts it cannot use after the binding).
|
||||
ui.shortcut_overrides.insert("tool:curvature", vec!["Shift+`".into(), "Hyper+K".into()]);
|
||||
let saved = serde_json::to_value(&ui).unwrap();
|
||||
let old: BTreeMap<String, String> = serde_json::from_value(saved["shortcut_overrides"].clone()).unwrap();
|
||||
let want: BTreeMap<String, String> = [
|
||||
("tool:pen", "Shift+9"),
|
||||
("edit.preferences", ""),
|
||||
("panel:layers", "Cmd+Alt+Shift+F7"),
|
||||
("view.grid", "Cmd+Period"),
|
||||
("tool:curvature", "Shift+~"),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(k, v)| (k.to_string(), v.to_string()))
|
||||
.collect();
|
||||
assert_eq!(old, want);
|
||||
let back: UiState = serde_json::from_value(saved).unwrap();
|
||||
assert_eq!(override_text(&back.shortcut_overrides, "panel:layers").as_deref(), Some("Cmd+Alt+Shift+F7"));
|
||||
assert_eq!(override_text(&back.shortcut_overrides, "tool:curvature").as_deref(), Some("Shift+~"));
|
||||
let map = json!({
|
||||
"tool:pen": "Shift+9",
|
||||
"edit.preferences": "",
|
||||
"panel:layers": "Cmd+Alt+Shift+F7",
|
||||
"view.grid": "Cmd+Period",
|
||||
"tool:curvature": "Shift+~",
|
||||
});
|
||||
let list = json!([
|
||||
{"command": "tool:pen", "keys": ["Shift+9"]},
|
||||
{"command": "edit.preferences", "keys": []},
|
||||
{"command": "panel:layers", "keys": ["Cmd+Alt+Shift+F7"]},
|
||||
{"command": "view.grid", "keys": ["Cmd+Period"]},
|
||||
{"command": "tool:curvature", "keys": ["Shift+~"]},
|
||||
]);
|
||||
let old_name = shortcut_editor::LEGACY_PRESETS[0].0;
|
||||
let named = old_file(map.clone(), Some(old_name));
|
||||
for ui in [old_file(map, None), old_file(list, None), named.clone()] {
|
||||
let ov = active(&ui);
|
||||
assert_eq!(texts(ov, "tool:pen"), Some(vec!["Shift+9"]));
|
||||
assert!(ov.get("edit.preferences").is_none_or(|t| t.iter().all(String::is_empty)));
|
||||
assert_eq!(texts(ov, &stored_key("panel:layers")), Some(vec!["Cmd+Alt+Shift+F7"]));
|
||||
assert_eq!(texts(ov, "tool:curvature"), Some(vec!["Shift+`"]));
|
||||
}
|
||||
let back: UiState = serde_json::from_value(serde_json::to_value(&named).unwrap()).unwrap();
|
||||
assert_eq!(back.shortcut_sets.active(), named.shortcut_sets.active());
|
||||
assert_eq!(active(&back), active(&named));
|
||||
}
|
||||
|
||||
/// A hand-edited value that is not text drops that entry, not every preference.
|
||||
#[test]
|
||||
fn a_bad_override_value_keeps_the_other_preferences() {
|
||||
let mut saved = serde_json::to_value(UiState { toolbar: false, ..Default::default() }).unwrap();
|
||||
saved["shortcut_overrides"] = json!({"x": 5, "tool:pen": "Shift+9"});
|
||||
let ui: UiState = serde_json::from_value(saved).unwrap();
|
||||
let mut raw = serde_json::to_value(UiState { toolbar: false, ..Default::default() }).unwrap();
|
||||
if let Some(o) = raw.as_object_mut() {
|
||||
o.remove("shortcut_sets");
|
||||
}
|
||||
raw["shortcut_overrides"] = json!({"x": 5, "tool:pen": "Shift+9"});
|
||||
let ui: UiState = serde_json::from_value(raw).unwrap();
|
||||
assert!(!ui.toolbar);
|
||||
assert!(!has_override(&ui.shortcut_overrides, "x"));
|
||||
assert_eq!(override_text(&ui.shortcut_overrides, "tool:pen").as_deref(), Some("Shift+9"));
|
||||
assert!(active(&ui).get("x").is_none());
|
||||
assert_eq!(texts(active(&ui), "tool:pen"), Some(vec!["Shift+9"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curvature_keeps_shift_tilde_and_plus_is_one_key() {
|
||||
let km = &*template();
|
||||
let curvature = vc_chord("Shift+~").unwrap();
|
||||
assert_eq!(curvature, Chord::parse("Shift+`").unwrap());
|
||||
assert_eq!(lookup(km, &curvature), Some(CommandRef::new("tool:curvature")));
|
||||
assert_eq!(effective_with(km, "tool:curvature").as_deref(), Some("Shift+~"));
|
||||
// Plus alone is the Add Anchor Point tool's, however it is written; with modifiers the
|
||||
// key is `=`.
|
||||
let ov = stored::from_value(json!({"tool:curvature": "Shift+~", "tool:addAnchor": "=", "view.zoomIn": "Cmd++"}));
|
||||
assert_eq!(texts(&ov, "tool:curvature"), Some(vec!["Shift+`"]));
|
||||
assert_eq!(stored::parse_vc("Shift+~"), Some(Chord::parse("Shift+`").unwrap()));
|
||||
for t in ["+", "="] {
|
||||
assert_eq!(vc_chord(t), Some(Chord::plain(Key::Plus)), "{t}");
|
||||
assert_eq!(stored::parse_vc(t), Some(Chord::plain(Key::Plus)), "{t}");
|
||||
}
|
||||
for t in ["Cmd++", "Cmd+="] {
|
||||
assert_eq!(vc_chord(t), Some(Chord::new(Mods::CMD, Key::Equals)), "{t}");
|
||||
assert_eq!(stored::parse_vc(t), Some(Chord::new(Mods::CMD, Key::Equals)), "{t}");
|
||||
}
|
||||
assert_eq!(lookup(km, &Chord::plain(Key::Plus)), Some(CommandRef::new("tool:addAnchor")));
|
||||
assert_eq!(lookup(km, &Chord::new(Mods::CMD, Key::Equals)), Some(CommandRef::new("view.zoomIn")));
|
||||
assert_eq!(vc_format(&Chord::new(Mods::CMD, Key::Comma)), "Cmd+Comma");
|
||||
let one = |key: &str| ov.get(key).and_then(|t| t.first()).and_then(|t| stored::parse_vc(t));
|
||||
assert_eq!(one("tool:addAnchor"), Some(Chord::plain(Key::Plus)));
|
||||
assert_eq!(one("view.zoomIn"), Some(Chord::new(Mods::CMD, Key::Equals)));
|
||||
assert_eq!(chord_text("Cmd+,"), Chord::new(Mods::CMD, Key::Comma).display(platform()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_shortcuts_do_not_conflict() {
|
||||
// One snapshot: tests running beside this one install and remove plug-ins.
|
||||
let snapshot = shortcut_editor::snapshot();
|
||||
let template = template_for(&snapshot);
|
||||
assert_eq!(template.conflicts(), vec![]);
|
||||
assert_eq!(template.problems(), vec![]);
|
||||
assert_eq!(template.catalog().len(), snapshot.entries.len(), "every entry is bindable");
|
||||
// A default the bridge can't read would show in the menus but never run.
|
||||
let unbound: Vec<(&str, &str)> = snapshot
|
||||
.entries
|
||||
.iter()
|
||||
.filter_map(|e| shortcut_editor::default_of(&e.key).map(|d| (e.key.as_str(), d)))
|
||||
.filter(|(key, d)| {
|
||||
let mut expected: Vec<Binding> = vc_binding(d).into_iter().collect();
|
||||
expected.extend(default_aliases(key, platform()).iter().filter_map(|alias| vc_binding(alias)));
|
||||
expected != template.default_bindings(&command_in(key, &snapshot.effects))
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(unbound, vec![], "every default text becomes the entry's binding");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_defaults_have_two_bindings_and_reset_restores_both() {
|
||||
for (key, plain, shifted) in [("paint.lastColor", ",", "Shift+,"), ("paint.lastGradient", ".", "Shift+.")] {
|
||||
let command = command_of(key);
|
||||
let defaults = template().default_bindings(&command);
|
||||
assert_eq!(defaults, vec![vc_binding(plain).unwrap(), vc_binding(shifted).unwrap()], "{key}");
|
||||
assert_eq!(
|
||||
shortcut_editor::entry(key).as_ref().map(|e| e.label.as_str()),
|
||||
Some(if key == "paint.lastColor" { "Apply Last Color" } else { "Apply Last Gradient" })
|
||||
);
|
||||
assert_eq!(effective_with(&template(), key).as_deref(), Some(plain));
|
||||
let mut overrides = Overrides::new();
|
||||
set_override(&mut overrides, key, "Shift+;");
|
||||
assert_eq!(keymap_with(&overrides).bindings(&command), vec![vc_binding("Shift+;").unwrap()]);
|
||||
shortcut_editor::reset_one(&mut overrides, key);
|
||||
assert_eq!(keymap_with(&overrides).bindings(&command), defaults);
|
||||
for p in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
let km = Keymap::new(catalog_defs(p, &snapshot), Scopes::new(), p).with_reserved(craft_keymap::reserved::system(p));
|
||||
assert_eq!(km.conflicts(), vec![], "{p:?}");
|
||||
assert_eq!(km.problems(), vec![], "{p:?}");
|
||||
assert_eq!(km.catalog().len(), snapshot.entries.len(), "{p:?}: every entry is bindable");
|
||||
for e in &snapshot.entries {
|
||||
// A default that no longer reads would show in the menus but never run.
|
||||
assert!(shortcut_editor::default_on(&e.key, p).is_none_or(|d| stored::parse_vc(d).is_some()), "{p:?} {}", e.key);
|
||||
let want = defaults_of(&e.key, p);
|
||||
let got = km.default_bindings(&command_in(&e.key, &snapshot.effects));
|
||||
assert_eq!(got, want, "{p:?} {}", e.key);
|
||||
assert!(want.iter().all(|b| !km.is_reserved(&b.trigger.chord)), "{p:?} {}: a default on a reserved chord", e.key);
|
||||
}
|
||||
let clear = km.default_bindings(&command_of("edit.clear"));
|
||||
assert!(clear.contains(&vc_binding("Backspace").unwrap()), "{p:?}: Clear has Backspace");
|
||||
}
|
||||
assert!(template().conflicts().is_empty());
|
||||
}
|
||||
|
||||
/// The alias rule of the loader: Cut, Copy and Paste carry F2, F3 and F4 off macOS, unless a
|
||||
/// saved assignment gives the key to another command without touching them.
|
||||
#[test]
|
||||
fn edit_function_keys_follow_platform_and_reset_restores_both_bindings() {
|
||||
let snapshot = shortcut_editor::snapshot();
|
||||
let run = |km: &Keymap, text: &str| match km.lookup(&stored::parse_vc(text).unwrap(), false, &Active::NONE) {
|
||||
Lookup::Run(c) => Some(c),
|
||||
_ => None,
|
||||
};
|
||||
for p in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
let km = keymap_for(p, &shortcut_editor::snapshot());
|
||||
for (key, primary, alternate) in [("edit.cut", "Cmd+X", "F2"), ("edit.copy", "Cmd+C", "F3"), ("edit.paste", "Cmd+V", "F4")] {
|
||||
let command = command_of(key);
|
||||
let mut expected = vec![vc_binding(primary).unwrap()];
|
||||
if !p.is_mac() {
|
||||
expected.push(vc_binding(alternate).unwrap());
|
||||
}
|
||||
assert_eq!(km.default_bindings(&command), expected, "{p:?} {key}");
|
||||
assert_eq!(lookup(&km, &vc_chord(primary).unwrap()), Some(command.clone()), "{p:?} {primary}");
|
||||
assert_eq!(lookup(&km, &vc_chord(alternate).unwrap()), (!p.is_mac()).then_some(command.clone()), "{p:?} {alternate}");
|
||||
assert_eq!(effective_with(&km, key).as_deref(), Some(primary));
|
||||
let mut changed = km.clone();
|
||||
shortcut_editor::assign_in(&mut changed, key, Some("Ctrl+Alt+Shift+F12"), true).unwrap();
|
||||
assert_eq!(changed.bindings(&command), vec![vc_binding("Ctrl+Alt+Shift+F12").unwrap()]);
|
||||
changed.reset(&command);
|
||||
assert_eq!(changed.bindings(&command), expected, "{p:?} {key} reset");
|
||||
let mut overrides = Overrides::new();
|
||||
set_override(&mut overrides, key, "Ctrl+Alt+Shift+F12");
|
||||
shortcut_editor::reset_one(&mut overrides, key);
|
||||
assert_eq!(km.clone().with_overrides(overrides).bindings(&command), expected, "{p:?} {key} use default");
|
||||
}
|
||||
assert!(km.conflicts().is_empty(), "{p:?}");
|
||||
assert!(km.problems().is_empty(), "{p:?}");
|
||||
|
||||
for (alias, edit, primary) in [("F2", "edit.cut", "Cmd+X"), ("F3", "edit.copy", "Cmd+C"), ("F4", "edit.paste", "Cmd+V")] {
|
||||
let mut saved = Overrides::new();
|
||||
set_override(&mut saved, "tool:pen", alias);
|
||||
let assigned = keymap_for(p, &shortcut_editor::snapshot()).with_overrides(edit_alias_overrides(&saved, p));
|
||||
assert_eq!(lookup(&assigned, &vc_chord(alias).unwrap()), Some(command_of("tool:pen")), "{p:?} saved {alias} assignment");
|
||||
assert_eq!(lookup(&assigned, &vc_chord(primary).unwrap()), Some(command_of(edit)), "{p:?} primary {edit} binding");
|
||||
shortcut_editor::reset_one(&mut saved, "tool:pen");
|
||||
let reset = keymap_for(p, &shortcut_editor::snapshot()).with_overrides(edit_alias_overrides(&saved, p));
|
||||
assert_eq!(lookup(&reset, &vc_chord(alias).unwrap()), (!p.is_mac()).then_some(command_of(edit)), "{p:?} reset saved {alias}");
|
||||
let keymap = |sets: &craft_keymap::Profiles| {
|
||||
Keymap::new(catalog_defs(p, &snapshot), Scopes::new(), p).with_overrides(sets.active_overrides(&shortcut_editor::BUILTINS).clone())
|
||||
};
|
||||
let kept = keymap(&stored::legacy_on(&json!({}), None, &Value::Null, p));
|
||||
assert_eq!(run(&kept, alias), (!p.is_mac()).then(|| command_of(edit)), "{p:?} {alias} default");
|
||||
assert_eq!(run(&kept, primary), Some(command_of(edit)), "{p:?} {primary}");
|
||||
let moved = keymap(&stored::legacy_on(&json!({"tool:pen": alias}), None, &Value::Null, p));
|
||||
assert_eq!(run(&moved, alias), Some(command_of("tool:pen")), "{p:?} saved {alias}");
|
||||
assert_eq!(run(&moved, primary), Some(command_of(edit)), "{p:?} primary {edit} stays");
|
||||
}
|
||||
let mut unknown = Overrides::new();
|
||||
set_override(&mut unknown, "missing.command", "F2");
|
||||
let km = keymap_for(p, &shortcut_editor::snapshot()).with_overrides(edit_alias_overrides(&unknown, p));
|
||||
assert_eq!(lookup(&km, &vc_chord("F2").unwrap()), (!p.is_mac()).then_some(command_of("edit.cut")), "{p:?} unknown saved entry");
|
||||
}
|
||||
}
|
||||
|
||||
/// The chords the operating system takes are refused, and no default uses one.
|
||||
#[test]
|
||||
fn system_shortcuts_are_refused() {
|
||||
let snapshot = shortcut_editor::snapshot();
|
||||
for (p, os_chord) in [(Platform::Mac, "Cmd+Tab"), (Platform::Windows, "Alt+F4"), (Platform::Linux, "Ctrl+Alt+F2")] {
|
||||
let mut km = keymap_for(p, &snapshot);
|
||||
assert_eq!((km.conflicts(), km.problems()), (vec![], vec![]), "{p:?}");
|
||||
let reserved: Vec<String> = snapshot
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|e| km.bindings(&command_of(&e.key)).iter().any(|b| km.is_reserved(&b.trigger.chord)))
|
||||
.map(|e| e.key.clone())
|
||||
.collect();
|
||||
assert_eq!(reserved, Vec::<String>::new(), "{p:?}: defaults on reserved chords");
|
||||
let err = shortcut_editor::assign_in(&mut km, "edit.undo", Some(os_chord), true).unwrap_err();
|
||||
assert!(err.ends_with("is reserved by the system"), "{p:?}: {err}");
|
||||
// A saved override on a reserved chord keeps the default.
|
||||
let mut ov = Overrides::new();
|
||||
let _ = ov.insert(stored_key("edit.undo"), vec![os_chord.to_string()]);
|
||||
let km = keymap_for(p, &snapshot).with_overrides(ov);
|
||||
assert_eq!(km.bindings(&command_of("edit.undo")), km.default_bindings(&command_of("edit.undo")), "{p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Select Last Selection Tool is Ctrl+` on Windows and Linux. macOS takes Cmd+` to switch
|
||||
/// between an app's windows, so there the command has no default and takes a chord the user
|
||||
/// assigns.
|
||||
#[test]
|
||||
fn last_selection_tool_default_follows_the_platform() {
|
||||
let snapshot = shortcut_editor::snapshot();
|
||||
let command = command_of("tool.selectLastSelection");
|
||||
let chord = vc_chord("Cmd+~").unwrap();
|
||||
for p in [Platform::Windows, Platform::Linux] {
|
||||
let km = keymap_for(p, &snapshot);
|
||||
assert_eq!(lookup(&km, &chord), Some(command.clone()), "{p:?}");
|
||||
assert_eq!(shortcut_editor::default_on("tool.selectLastSelection", p), Some("Cmd+~"), "{p:?}");
|
||||
}
|
||||
let mut mac = keymap_for(Platform::Mac, &snapshot);
|
||||
assert_eq!(mac.bindings(&command), vec![], "no default on macOS");
|
||||
assert_eq!(shortcut_editor::default_on("tool.selectLastSelection", Platform::Mac), None);
|
||||
shortcut_editor::assign_in(&mut mac, "tool.selectLastSelection", Some("Alt+~"), true).unwrap();
|
||||
assert_eq!(lookup(&mac, &vc_chord("Alt+~").unwrap()), Some(command));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_entries_bridge_to_window_panel() {
|
||||
let c = command_of("panel:layers");
|
||||
assert_eq!((c.id.as_str(), c.params.clone()), ("window.panel", json!({"panel": "layers"})));
|
||||
assert_eq!(entry_key(&c), "panel:layers");
|
||||
assert_eq!(entry_of_stored(&stored_key("panel:layers")), "panel:layers");
|
||||
assert_eq!(stored_key("tool:pen"), "tool:pen");
|
||||
let template = template();
|
||||
let paths = &template.bindable(&c).unwrap().paths;
|
||||
assert_eq!(paths, &vec![vec!["Window".to_string(), "Layers".to_string()]], "import matches panels by name");
|
||||
}
|
||||
|
||||
/// Each toggle's menu label reads Show or Hide.
|
||||
#[test]
|
||||
fn toggles_show_and_hide() {
|
||||
let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
for id in TOGGLES {
|
||||
let label = crate::menus::dynamic_label(&app, id, "");
|
||||
assert!(label.starts_with("Show ") || label.starts_with("Hide "), "{id}: {label}");
|
||||
let template = template();
|
||||
let listed = template.bindable(&CommandRef::new(*id));
|
||||
assert!(listed.is_none_or(|b| b.is_toggle), "{id}");
|
||||
}
|
||||
fn old_hold_shortcuts_load_as_hold_bindings() {
|
||||
let sets = stored::legacy(&json!({}), Some(shortcut_editor::LEGACY_PRESETS[0].0), &json!({"tool:pen": "P"}));
|
||||
let ov = sets.active_overrides(&shortcut_editor::BUILTINS);
|
||||
let pen = texts(ov, "tool:pen").unwrap();
|
||||
assert!(pen.len() > 1, "the single binding stays beside the hold: {pen:?}");
|
||||
assert_eq!(pen.last(), Some(&"Hold P"));
|
||||
assert!(Trigger::parse("Hold P").is_ok_and(|t| t.is_hold()));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user