From d8529f111d0b9b0115b2c35a89bb1bbc33cb334c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 10:55:29 -0800 Subject: [PATCH] Shortcuts: hold keys keep their order in a frame, and the sheet and CSV list hold shortcuts - When a key with a hold shortcut is pressed and its wait ends in the same frame, the single-key shortcuts typed before it in that frame run first, so the keys act in the order they went down. - The repeats of a key in the frame that starts its wait, and the text they type, are dropped like its later repeats. - Import Shortcut Set started from the VectorCraft defaults clears the working hold shortcuts; Add to the Current Shortcuts keeps them. - Export Text's shortcut sheet and CSV file list a row's hold shortcut after its shortcuts while Hold Shortcuts is on, as the text file does. --- crates/ui-egui/src/dialogs/shortcut_import.rs | 4 + .../src/dialogs/tests_shortcut_import.rs | 18 ++++ crates/ui-egui/src/shortcut_editor.rs | 53 +++++++-- crates/ui-egui/src/shortcuts/hold_keys.rs | 86 +++++++++++++-- .../ui-egui/src/shortcuts/hold_keys/tests.rs | 102 ++++++++++++++++-- 5 files changed, 241 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/dialogs/shortcut_import.rs b/crates/ui-egui/src/dialogs/shortcut_import.rs index 0516695233..e3ca87762a 100644 --- a/crates/ui-egui/src/dialogs/shortcut_import.rs +++ b/crates/ui-egui/src/dialogs/shortcut_import.rs @@ -518,6 +518,10 @@ pub fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } if let Some(k) = app.ui.dialog.as_mut() { k.fields.insert("overrides".into(), crate::keymap::stored::to_value(&shortcut_editor::saved_overrides(km.overrides(), &ov))); + // VectorCraft's defaults have no hold shortcuts; Add to the Current Shortcuts keeps them. + if !current { + k.fields.insert("holds".into(), json!({})); + } k.fields.insert("set".into(), json!(set)); k.fields.insert("__message".into(), json!(tl!("Imported. Press OK to keep the imported set."))); } diff --git a/crates/ui-egui/src/dialogs/tests_shortcut_import.rs b/crates/ui-egui/src/dialogs/tests_shortcut_import.rs index 066f7f4682..a4f8ba9d4b 100644 --- a/crates/ui-egui/src/dialogs/tests_shortcut_import.rs +++ b/crates/ui-egui/src/dialogs/tests_shortcut_import.rs @@ -234,6 +234,24 @@ fn cancel_and_apply_go_back_to_keyboard_shortcuts() { assert_eq!((app.ui.shortcut_set.as_str(), app.ui.shortcut_overrides.len()), ("Acme Keys", 3)); } +/// Started from VectorCraft's defaults, an import leaves no hold shortcut in the working set; added +/// to the current shortcuts, it keeps them. OK keeps what the working set shows. +#[test] +fn an_import_from_the_defaults_clears_the_hold_shortcuts() { + let mut app = app(); + earlier_answers(&mut app); + for (start, kept) in [("defaults", json!({})), ("current", json!({"paint.swap": "X"}))] { + app.ui.shortcut_holds = [("paint.swap".to_string(), "X".to_string())].into(); + shortcut_editor::open(&mut app); + super::shortcut_import::open(&mut app, "/sets/Acme Keys.kys", SET.as_bytes()).unwrap(); + set(&mut app, "start", json!(start)); + confirm(&mut app).unwrap(); + assert_eq!(dialog(&app).fields["holds"], kept, "{start}"); + confirm(&mut app).unwrap(); + assert_eq!(json!(app.ui.shortcut_holds), kept, "{start}: OK keeps it"); + } +} + /// A document's Missing Fonts dialog that Keyboard Shortcuts replaced waits while Cancel goes back /// from Import Shortcut Set to Keyboard Shortcuts, and opens again once Keyboard Shortcuts closes. #[test] diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 8ba8bda125..a1cb43d874 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1375,8 +1375,9 @@ const MENU_COMMANDS: &str = "Menu Commands"; /// Export Text's rows in sections, for the shortcut sheet and the CSV file: Tools, then one section /// per top-level menu in the order the dialog first lists a command of it, with the names and /// shortcuts as the dialog shows them, each name without its top-level menu. Every row the dialog -/// lists is there, with an empty shortcut when it has none. -pub fn export_sections(overrides: &Overrides) -> Vec { +/// lists is there, with an empty shortcut when it has none. A row with a hold shortcut in `holds` +/// ends its shortcuts with `Hold X`, joined as the dialog joins them. +pub fn export_sections(overrides: &Overrides, holds: &Holds) -> Vec { use crate::shortcut_sheet::{Row, Section}; let snapshot = snapshot(); let km = crate::keymap::keymap_in(&snapshot, overrides); @@ -1385,6 +1386,11 @@ pub fn export_sections(overrides: &Overrides) -> Vec = vec![]; for e in snapshot.entries.iter().filter(|e| listed(km.overrides(), e)) { let shortcut = dialog_shortcuts_with(&km, &e.key, backtick.as_deref()).unwrap_or_default(); + let shortcut = match hold_of(holds, &e.key) { + Some(h) if shortcut.is_empty() => format!("{} {}", tl!("Hold"), menus::pretty_shortcut(&h)), + Some(h) => format!("{shortcut} · {} {}", tl!("Hold"), menus::pretty_shortcut(&h)), + None => shortcut, + }; if e.is_tool { tools.rows.push(Row { name: shown_name(e), shortcut }); continue; @@ -1415,9 +1421,9 @@ fn export_text_file( TextFormat::Text => Ok(export_text_with(set, overrides, holds).into_bytes()), TextFormat::Sheet => { let title = format!("{} · {}", tl!("Keyboard Shortcuts"), shown_set_name(set)); - crate::shortcut_sheet::sheet_pdf(&title, &export_sections(overrides), page) + crate::shortcut_sheet::sheet_pdf(&title, &export_sections(overrides, holds), page) } - TextFormat::Csv => Ok(crate::shortcut_sheet::csv(&export_sections(overrides), ["Group", "Command", "Shortcut"]).into_bytes()), + TextFormat::Csv => Ok(crate::shortcut_sheet::csv(&export_sections(overrides, holds), ["Group", "Command", "Shortcut"]).into_bytes()), } } @@ -2712,7 +2718,7 @@ mod tests { tops.push(top); } } - (export_sections(&ov), listed.len(), tops) + (export_sections(&ov, &Holds::new()), listed.len(), tops) }); let titles: Vec<&str> = sections.iter().map(|s| s.title.as_str()).collect(); assert_eq!(titles[0], "Tools"); @@ -2787,7 +2793,7 @@ mod tests { Ok(()) })); app.run("shortcuts.exportText", json!({"path": "/a/list.csv", "format": "csv"})).unwrap(); - (returned, written.borrow().clone(), export_sections(&app.ui.shortcut_overrides)) + (returned, written.borrow().clone(), export_sections(&app.ui.shortcut_overrides, &Holds::new())) }); let [(path, bytes)] = files.as_slice() else { panic!("{} files", files.len()) }; assert_eq!(path, "/a/list.csv"); @@ -3637,6 +3643,41 @@ mod tests { assert_eq!(on.split('\t').nth(2), Some(format!("Hold {}", menus::pretty_shortcut("X")).as_str()), "{on}"); } + /// Export Text…'s shortcut sheet and CSV file also list a hold shortcut while Hold Shortcuts is + /// on, after the row's shortcuts. + #[test] + fn the_sheet_and_csv_list_hold_shortcuts_while_they_act() { + type Files = std::rc::Rc>>>; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let written: Files = Default::default(); + let w = written.clone(); + app.services.write = Some(Box::new(move |_: &str, b: &[u8]| { + w.borrow_mut().push(b.to_vec()); + Ok(()) + })); + app.run("shortcuts.set", json!({"id": "paint.swap", "hold": "X"})).unwrap(); + let hold = format!("Hold {}", menus::pretty_shortcut("X")); + let sections = with_steady_plugins(|| { + written.borrow_mut().clear(); + for on in [false, false, true] { + app.run("prefs.set", json!({"key": "holdShortcuts", "value": on})).unwrap(); + app.run("shortcuts.exportText", json!({"path": "/a.csv", "format": "csv"})).unwrap(); + app.run("shortcuts.exportText", json!({"path": "/a.pdf", "format": "sheet"})).unwrap(); + } + app.run("prefs.set", json!({"key": "holdShortcuts", "value": false})).unwrap(); + export_sections(&app.ui.shortcut_overrides, &app.ui.shortcut_holds) + }); + let files = written.borrow(); + let [csv_off, sheet_off, _, sheet_off_again, csv_on, sheet_on] = files.as_slice() else { panic!("{} files", files.len()) }; + let swap = sections.iter().flat_map(|s| &s.rows).filter(|r| r.shortcut.ends_with(&hold)).collect::>(); + assert_eq!(swap.len(), 1, "one row has the hold: {swap:?}"); + let (csv_off, csv_on) = (String::from_utf8_lossy(csv_off), String::from_utf8_lossy(csv_on)); + assert!(!csv_off.contains(&hold), "off, the CSV file lists no hold"); + assert!(csv_on.contains(&swap[0].shortcut), "on, the CSV file lists it: {}", swap[0].shortcut); + assert_eq!(sheet_off, sheet_off_again, "the sheet is the same each time"); + assert_ne!(sheet_off, sheet_on, "on, the sheet lists the hold"); + } + /// The text the Keyboard Shortcuts dialog draws in its second frame. fn dialog_texts(app: &mut VectorcraftApp) -> Vec { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/shortcuts/hold_keys.rs b/crates/ui-egui/src/shortcuts/hold_keys.rs index eb7c92ab04..b494050bd2 100644 --- a/crates/ui-egui/src/shortcuts/hold_keys.rs +++ b/crates/ui-egui/src/shortcuts/hold_keys.rs @@ -208,13 +208,59 @@ fn tool_takes(app: &mut VectorcraftApp, key: Key, text: &str) -> bool { tool_key.is_some_and(|k| app.session.tool_claims_key(k, view)) } +/// Runs the single-key shortcuts of the texts typed before the event at `start` that no wait took, +/// in order, as the frame's shortcuts would run them, and takes them and their presses from the +/// frame. A text typed with Cmd, Ctrl or Alt, by a key the active tool takes, or with no shortcut, +/// is left to the frame. True when one opened a dialog or the palette. +fn run_typed_before( + app: &mut VectorcraftApp, + ctx: &egui::Context, + events: &[egui::Event], + typed_by: &[Option], + start: usize, + taken: &mut Vec, +) -> bool { + for (k, e) in events.iter().enumerate().take(start) { + let egui::Event::Text(text) = e else { continue }; + let by = typed_by.get(k).copied().flatten(); + if taken.contains(&k) || by.is_some_and(|b| taken.contains(&b)) { + continue; + } + let (key, physical, repeat, m) = match by.and_then(|b| events.get(b)) { + Some(egui::Event::Key { key, physical_key, repeat, modifiers, .. }) => (Some(*key), *physical_key, *repeat, *modifiers), + _ => (None, None, false, ctx.input(|i| i.modifiers)), + }; + if m.command || m.ctrl || m.alt || m.mac_cmd || key.is_some_and(|key| tool_takes(app, key, text)) { + continue; + } + let typed = super::latin(text, physical); + let chords = match key { + Some(key) => tap_chords(&typed, key, m), + None => super::text_chords(&typed, m, None), + }; + // A key with no shortcut stays in the frame for what reads it later (Space for the canvas). + let keymap = crate::shortcut_editor::current(); + if !chords.iter().any(|c| crate::keymap::lookup(&keymap.keymap, c).is_some()) { + continue; + } + taken.push(k); + taken.extend(by); + if super::run_single_key(app, ctx, &chords, key, repeat) { + return true; + } + } + false +} + /// Before the frame's shortcuts run: goes through the frame's events in order. A release of the /// waiting key ends the wait (the hold when the delay has passed, otherwise the tap); a press of /// another key, or a change of Cmd, Ctrl or Alt, ends it first, so the keys act in the order they /// went down; and a new press of a key with a hold shortcut starts a wait, taking the press and -/// its text from the frame. Then a wait whose delay has passed with the key down runs the hold -/// shortcut. True when a result opened a dialog or the palette: the rest of the frame's keys are -/// dropped and no other shortcut runs. +/// its text from the frame, with the key's repeats that follow in the frame and their text. When a +/// wait that started in this frame also ends in it, the keys typed before its key run first +/// ([`run_typed_before`]), so they act in the order they went down. Then a wait +/// whose delay has passed with the key down runs the hold shortcut. True when a result opened a +/// dialog or the palette: the rest of the frame's keys are dropped and no other shortcut runs. pub(super) fn intake(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { // Off (Keyboard Shortcuts › Hold Shortcuts), every key runs on its press. if !app.session.prefs.hold_shortcuts || blocked(app, ctx) { @@ -226,6 +272,9 @@ pub(super) fn intake(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { let text_of = |k: usize| typed_by.iter().position(|by| *by == Some(k)).and_then(|j| events.get(j).map(|e| (j, e))); let mut taken: Vec = vec![]; let mut stop_at = None; + // The press of a wait that started in this frame: when the wait also ends in this frame, the + // keys typed before it run first. + let mut started: Option = None; for (j, e) in events.iter().enumerate() { if let Some(p) = app.hold_keys.pending.as_ref().filter(|p| p.viewport == viewport) { let overdue = now - p.since >= p.delay; @@ -248,11 +297,20 @@ pub(super) fn intake(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { _ => None, } }; - if let Some((hold, down)) = ended - && settle(app, ctx, hold, down) - { - stop_at = Some(j); - break; + if let Some((hold, down)) = ended { + // A key typed before it that opened a dialog or the palette ends the wait without + // running it. + if let Some(start) = started.take() + && run_typed_before(app, ctx, &events, &typed_by, start, &mut taken) + { + cancel(app, ctx); + stop_at = Some(j); + break; + } + if settle(app, ctx, hold, down) { + stop_at = Some(j); + break; + } } } let egui::Event::Key { key, physical_key, pressed: true, repeat: false, modifiers: m } = e else { continue }; @@ -271,7 +329,19 @@ pub(super) fn intake(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { if tool_takes(app, *key, text) { continue; } + started = Some(j); taken.extend([j, t]); + // The key's repeats in this frame, and the text they type, stay out of the frame too. + for (r, later) in events.iter().enumerate().skip(j + 1) { + if releases(later, *key, *physical_key) { + break; + } + if matches!(later, egui::Event::Key { key: k, physical_key: p, pressed: true, repeat: true, .. } if same_key(*k, *p, *key, *physical_key)) + { + taken.push(r); + taken.extend(text_of(r).map(|(rt, _)| rt)); + } + } // A wait left in another viewport ends without running: that window lost the keyboard to // this one. Its key's repeats stay held back there until it is let go. if let Some(old) = app.hold_keys.pending.take_if(|p| p.viewport != viewport) { diff --git a/crates/ui-egui/src/shortcuts/hold_keys/tests.rs b/crates/ui-egui/src/shortcuts/hold_keys/tests.rs index be7765f8f3..4e745510fe 100644 --- a/crates/ui-egui/src/shortcuts/hold_keys/tests.rs +++ b/crates/ui-egui/src/shortcuts/hold_keys/tests.rs @@ -307,22 +307,108 @@ fn another_key_ends_the_wait_and_runs_after_it() { assert_eq!(app.session.tool_id(), "selection", "the release of X runs nothing more"); } -/// Two keys pressed in one frame act in the order they went down. +/// The labels of the document's undo steps after the first `from`. +fn steps(app: &VectorcraftApp, from: usize) -> Vec { + app.session.doc().unwrap().history.undo.iter().skip(from).map(|e| e.label.clone()).collect() +} + +/// The label of the undo step `command` records on [`app_with`]'s document. +fn label(command: &str) -> String { + let mut app = app_with(true); + let n = steps(&app, 0).len(); + app.run(command, json!({})).unwrap(); + steps(&app, n).pop().unwrap() +} + +/// A quick press of X swaps fill and stroke, and holding X deselects; D sets the default fill and +/// stroke, as by default. +fn swap_on_x() -> VectorcraftApp { + let mut app = app_with(true); + assert_eq!(crate::shortcut_editor::default_of("paint.default"), Some("D")); + app.run("shortcuts.set", json!({"id": "paint.swap", "shortcut": "X", "force": true})).unwrap(); + app.run("shortcuts.set", json!({"id": "select.none", "hold": "X"})).unwrap(); + app +} + +/// Two keys pressed in one frame act in the order they went down, each once. #[test] fn keys_in_one_frame_act_in_order() { - let mut app = erolka_x(true); + let (swap, default) = (label("paint.swap"), label("paint.default")); + assert_ne!(swap, default); + let mut app = swap_on_x(); let keys = Keyboard::new(); + let n = steps(&app, 0).len(); let mut events = press(Key::X, "x", Modifiers::NONE); - events.extend(press(Key::V, "v", Modifiers::NONE)); + events.extend(press(Key::D, "d", Modifiers::NONE)); keys.frame(&mut app, 0.0, events); - assert_eq!(app.session.tool_id(), "selection", "X's tap first, then V"); - let mut events = press(Key::V, "v", Modifiers::NONE); + assert_eq!(steps(&app, n), [swap.clone(), default.clone()], "X's tap first, then D"); + keys.frame(&mut app, 1.0, vec![release(Key::X), release(Key::D)]); + // Paint that D changes again. + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + let n = steps(&app, 0).len(); + let mut events = press(Key::D, "d", Modifiers::NONE); events.extend(press(Key::X, "x", Modifiers::NONE)); - app.select_tool("pen"); - keys.frame(&mut app, 1.0, vec![release(Key::X), release(Key::V)]); keys.frame(&mut app, 2.0, events); keys.frame(&mut app, 2.1, vec![release(Key::X)]); - assert_eq!(app.session.tool_id(), "eyedropper", "V first, then X's tap at its release"); + assert_eq!(steps(&app, n), [default, swap], "D first, then X's tap at its release"); + assert_eq!(selected(&app), 1, "and no hold"); +} + +/// A wait that starts in a frame after another key, and that a release or another key ends in the +/// same frame, runs its tap after that key. +#[test] +fn a_wait_ended_in_its_frame_runs_after_the_keys_before_it() { + let (swap, default) = (label("paint.swap"), label("paint.default")); + let mut app = swap_on_x(); + let keys = Keyboard::new(); + let n = steps(&app, 0).len(); + let mut events = press(Key::D, "d", Modifiers::NONE); + events.extend(press(Key::X, "x", Modifiers::NONE)); + events.push(release(Key::X)); + keys.frame(&mut app, 0.0, events); + assert_eq!(steps(&app, n), [default.clone(), swap.clone()], "D first, then X's tap"); + assert!(app.hold_keys.pending.is_none()); + keys.frame(&mut app, 1.0, vec![release(Key::D)]); + assert_eq!(selected(&app), 1, "nothing waits after it"); + // Ended by V while X is still down: D, X's tap, then V. + let n = steps(&app, 0).len(); + let mut events = press(Key::D, "d", Modifiers::NONE); + events.extend(press(Key::X, "x", Modifiers::NONE)); + events.extend(press(Key::V, "v", Modifiers::NONE)); + keys.frame(&mut app, 2.0, events); + assert_eq!(steps(&app, n), [default, swap], "D first, then X's tap"); + assert_eq!(app.session.tool_id(), "selection", "then V"); + keys.press(&mut app, 2.5, Key::X, "x"); + keys.frame(&mut app, 2.6, vec![release(Key::X), release(Key::D), release(Key::V)]); + assert_eq!(steps(&app, n).len(), 2, "X's repeats run nothing"); + assert_eq!(selected(&app), 1, "and no hold"); + // Ended by a command chord (Deselect): D, X's tap, then the chord. + assert_eq!(crate::shortcut_editor::default_of("select.none"), Some("Cmd+Shift+A")); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + let n = steps(&app, 0).len(); + let mut events = press(Key::D, "d", Modifiers::NONE); + events.extend(press(Key::X, "x", Modifiers::NONE)); + let modifiers = Modifiers::COMMAND | Modifiers::SHIFT; + events.push(egui::Event::Key { key: Key::A, physical_key: Some(Key::A), pressed: true, repeat: false, modifiers }); + keys.frame(&mut app, 3.0, events); + assert_eq!(steps(&app, n), [label("paint.default"), label("paint.swap")], "D first, then X's tap"); + assert_eq!(selected(&app), 0, "then the chord"); +} + +/// The repeats of a key in the frame that starts its wait, and the text they type, stay out of the +/// frame. +#[test] +fn repeats_in_the_frame_that_starts_a_wait_stay_out_of_it() { + let mut app = swap_on_x(); + let keys = Keyboard::new(); + let n = steps(&app, 0).len(); + let mut events = press(Key::X, "x", Modifiers::NONE); + events.extend(press(Key::X, "x", Modifiers::NONE)); + events.extend(press(Key::X, "x", Modifiers::NONE)); + let left = keys.frame_left(&mut app, 0.0, events); + assert!(app.hold_keys.pending.is_some(), "X waits"); + assert!(!left.iter().any(|e| matches!(e, egui::Event::Text(_) | egui::Event::Key { pressed: true, .. })), "{left:?}"); + assert!(steps(&app, n).is_empty(), "the repeats run nothing"); } /// A press and its release in one frame are a tap, run in that frame.