diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 462adb62d2..2dde31c95f 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -1,577 +1,75 @@ -//! Keyboard shortcuts: command shortcuts from the registry, single-key tool shortcuts, arrows, -//! and tool keys (Enter/Esc/↑/↓ while drawing). +//! What the app does with the commands the key stage fires: tool keys and their holds, the Escape chain, +//! nudges and the window's panel and artboard shortcuts. -use craft_keymap::egui::Hit; -use craft_keymap::{Active, CommandRef}; -use egui::{Key, KeyboardShortcut, Modifiers}; +use craft_keymap::{CommandRef, Mods}; +use craft_ui_contract::runtime::commands::{CommandGate, FirePhase, Fired}; +use craft_ui_contract::runtime::keys::{self, Intent}; use serde_json::json; -use vectorcraft_engine::cmd::clipboard::{Flavour, TEXT}; -use vectorcraft_engine::{Result as EngineResult, UiRequest, ViewInfo}; -use vectorcraft_tools::{Mods, SurroundingUnit, ToolKey}; +use vectorcraft_tools::ToolKey; use crate::VectorcraftApp; -mod alt_tap; mod held_tool; -mod hold_keys; -mod labels; -mod paste; mod presentation; -mod typing; -pub(crate) use alt_tap::AltTap; pub(crate) use held_tool::{HeldTool, note_tool_use}; -pub(crate) use hold_keys::HoldKeys; -#[cfg(test)] -pub(crate) use labels::note_copied_in_window; -pub(crate) use labels::{leave_to_labels, take_copied_in_window}; -use labels::{left_to_labels, note_copies_before_labels, run_after_labels, take_command_after_labels, watch_label_copies}; -use paste::unclip_chords; -pub(crate) use paste::{PasteChord, paste_command}; +use presentation::escape_resets_rotation; pub(crate) use presentation::presentation_step; -use presentation::{escape_resets_rotation, presentation_keys}; -#[cfg(test)] -use typing::is_shortcut_chord; -pub(crate) use typing::keep_marked_text; -use typing::{drop_typing_presses, type_text}; -fn text_focus_frame_id() -> egui::Id { - egui::Id::unique("shortcut-text-focus-frame") +/// The gate over commands for the frame's `CommandInput`: in Presentation Mode only leaving it runs. +// PLAN: the sheet's `presentation_gate() -> CommandGate` has no way to read `screen_mode`; the caller (shortcuts-w6) passes it. +pub(crate) fn presentation_gate(presenting: bool) -> CommandGate { + CommandGate::new(presenting, |presenting: &bool, command: &CommandRef| !*presenting || command.id == "view.presentation") } -pub(crate) fn remember_text_focus(ctx: &egui::Context) { - if ctx.egui_wants_keyboard_input() { - let frame = ctx.cumulative_frame_nr_for(ctx.viewport_id()); - ctx.data_mut(|d| d.insert_temp(text_focus_frame_id(), frame)); - } -} - -fn text_focused_in_previous_frame(ctx: &egui::Context) -> bool { - let previous = ctx.cumulative_frame_nr_for(ctx.viewport_id()).checked_sub(1); - ctx.data(|d| d.get_temp::(text_focus_frame_id())) == previous -} - -/// Parse "Cmd+Shift+]" into an egui shortcut. `Cmd` is Command on macOS and Ctrl elsewhere. -/// `+` and `=` name one chord key ([`Key::Equals`]): `+` is Shift+`=` on many layouts, so a -/// `Cmd+=` chord also answers `+` however it is typed. -pub fn parse(s: &str) -> Option { - if s.is_empty() { - return None; - } - // A bare `+` (the Add Anchor Point tool's key) is the key itself, not a separator with - // nothing on either side. - let (mods_part, key_part) = if s == "+" { - ("", "+") - } else if let Some(stripped) = s.strip_suffix("++") { - (stripped.trim_end_matches('+'), "+") - } else { - s.rsplit_once('+').unwrap_or(("", s)) - }; - let mut m = Modifiers::NONE; - for part in mods_part.split('+').filter(|p| !p.is_empty()) { - match part { - "Cmd" => m |= Modifiers::COMMAND, - "Shift" => m |= Modifiers::SHIFT, - "Alt" => m |= Modifiers::ALT, - "Ctrl" => m |= Modifiers::CTRL, - _ => return None, +/// Runs one command the key stage fired. A tool key chooses its tool (and starts or ends a hold), `Select All` +/// with the Artboard tool selects artboards, and every other command runs as its menu item does. +pub(crate) fn run_fired(app: &mut VectorcraftApp, ctx: &egui::Context, fired: &Fired) { + let command = &fired.command; + if command.id.starts_with("tool:") { + match fired.phase { + FirePhase::Release => held_tool::release(app, ctx, fired), + FirePhase::Press | FirePhase::Repeat => held_tool::choose(app, ctx, fired), } - } - let key = match key_part { - "]" => Key::CloseBracket, - "[" => Key::OpenBracket, - ";" => Key::Semicolon, - "'" => Key::Quote, - "/" => Key::Slash, - "\\" => Key::Backslash, - "=" | "+" => Key::Equals, - "-" => Key::Minus, - "Delete" => Key::Delete, - "Backspace" => Key::Backspace, - "Tab" => Key::Tab, - "~" => Key::Backtick, - // A modifier alone is never a chord's key: it couldn't fire (#487). - k => Key::from_name(k).filter(|k| !is_modifier(*k))?, - }; - Some(KeyboardShortcut::new(m, key)) -} - -/// The modifier keys, which egui also reports as key presses of their own. -pub(crate) fn is_modifier(key: Key) -> bool { - matches!( - key, - Key::ShiftLeft | Key::ShiftRight | Key::ControlLeft | Key::ControlRight | Key::AltLeft | Key::AltRight | Key::SuperLeft | Key::SuperRight - ) -} - -/// Every command shortcut in effect (user overrides from Edit → Keyboard Shortcuts win), with the -/// command's params: `{}`, or `{panel}` for the panel shortcuts (`window.panel`). -pub(crate) fn all_shortcuts() -> Vec<(KeyboardShortcut, &'static str, serde_json::Value)> { - let mut v = vec![]; - for c in vectorcraft_engine::command_specs().iter().chain(vectorcraft_engine::cmd::plugin::command_specs()) { - if let Some(sc) = crate::menus::shortcut_of(c.id).and_then(parse) { - v.push((sc, c.id, json!({}))); - } - } - for c in crate::menus::UI_COMMANDS { - if let Some(sc) = crate::menus::shortcut_of(c.0).and_then(parse) { - v.push((sc, c.0, json!({}))); - } - } - for (panel, _) in crate::state::all_panels() { - if let Some(sc) = crate::shortcut_editor::panel_shortcut(panel).and_then(parse) { - v.push((sc, "window.panel", json!({ "panel": panel }))); - } - } - // Effect menu items with shortcuts of their own (#3296): a chord bound to one is a command's - // too, so the tool doesn't take Cmd+Enter bound to an effect before the keymap runs it. - for e in crate::shortcut_editor::effect_items().iter() { - if let Some(sc) = crate::shortcut_editor::effect_shortcut(&e.effect).and_then(parse) { - v.push((sc, e.command, json!({ "effect": e.effect }))); - } - } - // Object › Plug-ins' filter items with shortcuts, for the same reason. - for f in crate::shortcut_editor::filter_items().iter() { - if let Some(sc) = crate::shortcut_editor::filter_shortcut(&f.id).and_then(parse) { - v.push((sc, "plugin.dialog", json!({ "id": f.id }))); - } - } - // Most specific (most modifiers) first: `paste_command` takes the first V chord the held keys - // match logically, so Cmd+Shift+V isn't taken by Cmd+V. - v.sort_by_key(|(sc, ..)| { - std::cmp::Reverse(sc.modifiers.shift as u8 + sc.modifiers.alt as u8 + sc.modifiers.command as u8 + sc.modifiers.ctrl as u8) - }); - v -} - -/// Does every press of `key` this frame hold a chord with modifiers that a command shortcut is bound -/// to, matched as [`consume`] matches it? `cmd_only`: only chords with Cmd count. False when `key` -/// isn't pressed. -fn runs_a_command(i: &egui::InputState, key: Key, cmd_only: bool) -> bool { - let presses: Vec = i - .events - .iter() - .filter_map(|e| match e { - egui::Event::Key { key: k, pressed: true, modifiers, .. } if *k == key => Some(*modifiers), - _ => None, - }) - .collect(); - !presses.is_empty() && presses.iter().all(|m| chord_runs_a_command(key, *m, cmd_only)) -} - -/// Is a command shortcut bound to `key` held with `m`, matched logically? -/// `cmd_only`: only chords with Cmd count. -fn chord_runs_a_command(key: Key, m: Modifiers, cmd_only: bool) -> bool { - all_shortcuts() - .iter() - .any(|(sc, ..)| sc.logical_key == key && (sc.modifiers.command || (!cmd_only && sc.modifiers.any())) && m.matches_logically(sc.modifiers)) -} - -/// Whether a key press runs a shortcut of the keymap in effect, the user's own included. The web -/// build asks this of every Cmd and Ctrl press, before egui sees it, to cancel what the browser -/// would also do with it (zoom the page on `Cmd+=`, undo on `Cmd+Z`, go back on `Cmd+[`). -/// `key` and `code` are the browser's names for the character typed and the key's position, which -/// egui reads with [`Key::from_name`]; `modifiers` as egui reports them. The press is matched as -/// the dispatcher matches it ([`dispatch`]) on a layout about which nothing is known: what typing -/// has shown of the layout is left out, and so are double presses. An action's function key runs -/// a shortcut too. -pub fn runs_a_shortcut(key: &str, code: &str, modifiers: Modifiers) -> bool { - let physical_key = Key::from_name(code); - let Some(key) = Key::from_name(key).or(physical_key) else { return false }; - let press = egui::Event::Key { key, physical_key, pressed: true, repeat: false, modifiers }; - let Some(input) = craft_keymap::KeyInput::from_egui(&press, crate::keymap::platform()) else { return false }; - let mirror = crate::shortcut_editor::current(); - craft_keymap::Layout::default() - .candidates(&input) - .iter() - .any(|c| mirror.keymap.lookup(c, false, &Active::NONE) != craft_keymap::Lookup::None || crate::panels::actions::plays_an_action(c)) -} - -/// Process one frame's events against the keymap at most once per context, viewport and frame, so -/// reruns cannot fire a shortcut or tool key twice: keymap commands, tools and panels, nudges, -/// Delete/Backspace (left to a Layers or Appearance row that has the keys) and single-key tool -/// shortcuts. -pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { - // One UI pass takes a frame's events. A discarded rerun and a test helper that also calls - // `logic` see the same events again; they must not fire a shortcut or tool key twice. The - // key includes the context (a restarted host starts at frame 0) and the viewport (frame - // numbers are per viewport), and remembers every key taken this host iteration: an - // interleaved root/auxiliary pass cannot make an earlier frame look new again. - let frame = (crate::graphics::context_tag(ctx), ctx.viewport_id(), ctx.cumulative_frame_nr_for(ctx.viewport_id())); - if !crate::take_frame_once(&mut app.shortcuts_frames, frame) { return; } - ctx.input(|i| crate::shortcut_editor::note_backtick_text(&i.events)); - // A Copy or Cut the last pass left to labels that copied nothing runs now, whatever this - // frame's keys do. The text it copies goes out now, so it is not taken for a label's copy. - watch_label_copies(ctx); - if let Some(c) = take_command_after_labels(ctx) { - run_after_labels(app, c); - app.flush_clipboard_out(ctx); - } - note_copies_before_labels(ctx); - note_key_surfaces(app, ctx); - forget_opening_key(ctx); - let focused = ctx.input(|input| input.focused) || app.forwarded_frame && ctx.viewport_id() == egui::ViewportId::ROOT; - // The repeats of a key with a hold shortcut stay out of every frame until it is let go. - hold_keys::guard(app, ctx, focused); - // A held tool shortcut that is let go returns to the tool active before it. - held_tool::follow(app, ctx, focused); - let alt_tapped = alt_tap::follow(&mut app.alt_tap, ctx, focused); - if !focused { - crate::ime::controls_without_editor(app, ctx); + // The end of a momentary key is the board's; no command of the app acts on it. + if fired.phase == FirePhase::Release { return; } - // Followed before anything returns, so a key typed in a field isn't taken for a paste. - let textless_paste = ctx.input(|i| app.paste_chord.textless_paste(&i.events)); - // A numeric field being scrubbed has the keyboard: Escape cancels the drag. - if crate::scrub::phase(ctx) != crate::scrub::Phase::Idle { - crate::ime::controls_without_editor(app, ctx); + if command.id == "select.all" && crate::panels::artboards::selects_all(app, ctx) { + // With the Artboard tool, Select All's keys after a click on an Artboards panel row select every artboard + // instead of the art. + crate::panels::artboards::select_all(app); return; } - // The update prompt and the modal result window draw over everything and read Escape themselves. - if crate::updates_ui::blocks_input(app) { - crate::ime::controls_without_editor(app, ctx); - return; + match menu_target(app, command) { + Some(Ok((id, params))) => crate::menus::invoke(app, &id, params), + Some(Err(why)) => app.status(why), + None => crate::menus::invoke(app, &command.id, shortcut_params(command)), } - if app.ui.dialog.is_some() || app.ui.palette_open { - crate::ime::controls_without_editor(app, ctx); - if app.ui.dialog.as_ref().is_some_and(crate::dialogs::revolve_gizmo::active) && crate::dialogs::revolve_gizmo::dragging(ctx) { - // Escape first restores this rotation gesture. The settings stay open. - return; - } - if crate::shortcut_editor::is_recording(app) { - return; - } - // Escape closes a dropdown list or popover open in the dialog, or the palette's Recent - // Commands list (each closes itself on it), and leaves the dialog or the palette open. - let popup = app.ui.dialog.as_ref().map_or(crate::palette::recent_list_open(ctx), |d| { - egui::Popup::is_any_open(ctx) - || crate::dialogs::brush_options::tips_open(d) - || crate::dialogs::new_document_popup_open(d) - || crate::dialogs::export_artboard_name_editing(app, d) - }); - // Escape ends Brush Options' Key Color pick and leaves the dialog open: the Eyedropper - // switches back to the tool that armed it. - if !popup && pressed_anew(ctx, Key::Escape) && key_color_pick_armed(app) { - let view = app.view_info(); - let r = app.session.tool_key(ToolKey::Escape, Mods::default(), view); - crate::canvas::apply_requests(app, r); - return; - } - // Escape in Preferences' search field with text clears the field first. - if !popup && pressed_anew(ctx, Key::Escape) && !crate::prefs_dialog::clear_search_on_escape(app, ctx) { - crate::dialogs::cancel(app); - app.ui.palette_open = false; - } +} + +/// Once per pass: the returns of held tools that a gesture or a dialog deferred. +pub(crate) fn follow_holds(app: &mut VectorcraftApp, ctx: &egui::Context) { + held_tool::follow(app, ctx); +} + +/// An Escape the window took (nothing focused, no popup or session took it) leaves Presentation Mode, or else ends +/// the first thing on: pattern editing, isolation, Global Edit, a rotated view or a full screen mode. +pub(crate) fn escape(app: &mut VectorcraftApp, ctx: &egui::Context) { + // Cancel reads the same in either reading direction. + if !keys::with_window_intents(ctx, false, |window| window.take(Intent::Cancel)) { return; } if app.ui.screen_mode == 3 { - crate::ime::controls_without_editor(app, ctx); - presentation_keys(app, ctx); + let _ = app.run("view.presentation", json!({})); return; } - // Keys with a hold shortcut wait before anything else reads the frame's keys, so a key pressed - // after one acts after it. - if hold_keys::intake(app, ctx) { - return; - } - // Escape that cancels a ruler-origin drag or floating Tools move skips the tool and later Escape actions, - // and so do its repeats while it is held. - let escape_ended_gesture = escape_ended_gesture(ctx); - let escape_held_by_drag = crate::canvas::dragging(ctx) || escape_ended_gesture; - let typing = ctx.egui_wants_keyboard_input(); - // Escape closes Edit Toolbar's drawer first (egui drops a drag from it on Escape already). - if app.ui.tools_drawer && !typing && !escape_held_by_drag && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { - app.ui.tools_drawer = false; - } - let view = app.view_info(); - // While an IME composes, Enter and Escape are its own (confirm / cancel). - let composing = app.session.tool_composing(); - // Tool keys first (Enter/Escape end paths; arrows change polygon sides while dragging). - let busy = app.session.tool_busy(); - // Enter in the Type tool types a line break (Cmd+Enter ends editing), so it goes to the tool - // with the frame's text, below: the loop then skips Enter, the first key. - let enter_types = app.session.tool_wants_text(); - for (k, tk) in [(Key::Enter, ToolKey::Enter), (Key::Escape, ToolKey::Escape)].into_iter().skip(usize::from(enter_types)) { - if !typing && !composing && !take_claimed_repeat(app, ctx, k, tk, view) && pressed_anew(ctx, k) { - // A chord a command is bound to (Cmd+Enter) runs only that command, in the shortcuts - // below, also when the tool claims the key. While the Type tool edits text only Cmd - // chords run one, and while another tool is busy none does. - let text = app.session.tool_wants_text(); - if (text || !busy) && ctx.input(|i| runs_a_command(i, k, text)) { - continue; - } - if k == Key::Escape && escape_ended_gesture { - continue; - } - // A key the tool claims (Esc with a loaded place cursor) is only the tool's. - let claimed = app.session.tool_claims_key(tk, view); - let mods = ctx.input(|i| { - let m = i - .events - .iter() - .rev() - .find_map(|e| match e { - egui::Event::Key { key, pressed: true, modifiers, .. } if *key == k => Some(*modifiers), - _ => None, - }) - .unwrap_or(i.modifiers); - crate::canvas::mods(m, false) - }); - let ends = k == Key::Escape && app.session.tool_ends_on_escape(view); - let before = (k == Key::Escape && !ends).then(|| document_revision(app)); - let r = app.session.tool_key(tk, mods, view); - // An Escape that ended something in the tool (a path being drawn, a selected point) ends - // nothing else. A hover highlight it clears does not count. - let tool_took = ends || before.is_some_and(|b| b != document_revision(app)); - // Enter also takes what the tool asks of the UI: Rotate, Scale, Reflect and Shear open - // their dialog with it. - if claimed || (k == Key::Enter && !busy) { - crate::canvas::apply_requests(app, r); - } - if claimed { - ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)); - ctx.input_mut(|i| i.consume_key(Modifiers::SHIFT, k)); - } - if k == Key::Escape && !busy && !claimed && !escape_held_by_drag && !tool_took { - escape_ends_one_thing(app, ctx); - } - if k == Key::Enter && !busy && !claimed { - // Enter with a selection tool opens the Move dialog, as a double-click on its button - // does. - let tool = app.session.tool_id(); - if app.ui.dialog.is_none() && vectorcraft_tools::catalog::is_selection_tool(tool) { - // Nothing selected: it fails and nothing opens (the menu item is disabled then too). - let _ = crate::toolbar::open_options(app, tool); - } - // The Enter that opened a dialog isn't also its OK: dialogs take Enter, this frame too. - if app.ui.dialog.is_some() { - ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)); - } - } - held_tool::note_enter_dialog(app, k); - } - } - if typing { - crate::ime::controls_without_editor(app, ctx); - return; - } - // The Copy or Cut the menu bar left to the labels came from no key: unclipped, the menu's Cut - // would become a plain X press (Toggle Fill/Stroke Focus). - if left_to_labels(ctx).is_none() { - ctx.input_mut(unclip_chords); - } - // Tab is ours when no field has the keyboard (it shows and hides the panels, or goes to the - // Type tool): left to egui, it would also move the focus on to a field, and every key after it - // would count as typing. - if ctx.input(|i| i.key_pressed(Key::Tab)) { - ctx.memory_mut(|m| m.move_focus(egui::FocusDirection::None)); - } - // While the Type tool edits text, a character typed with AltGr runs no command chord. - if app.session.tool_wants_text() { - ctx.input_mut(drop_typing_presses); - } - if app.session.tool_wants_text() { - type_tool_input(app, ctx, composing); - return; - } - crate::ime::controls_without_editor(app, ctx); - let to_labels = handle_clipboard(app, ctx, textless_paste); - // Alt tapped on its own: the Quick Pen tool's next action. - if alt_tapped && app.session.tool_claims_key(ToolKey::AltTap, view) { - let r = app.session.tool_key(ToolKey::AltTap, Mods::default(), view); - crate::canvas::apply_requests(app, r); - } - if busy { - busy_tool_keys(app, ctx, view); - return; - } - // A plain Delete or Backspace after a click on a Layers or Appearance row is that panel's (it - // removes the highlighted rows), not a tool's (the Artboard tool's) or Edit › Clear's. - let rows_keys = crate::panels::rows_take_delete(ctx); - if claimed_tool_keys(app, ctx, view, rows_keys) { - return; - } - // An action's function key plays the action, also when a command has the same shortcut. - crate::panels::actions::play_function_key(app, ctx); - // Command, panel and tool shortcuts. A bound shifted punctuation chord uses its key press; - // other text keys use the typed character below. - let row_key = |chord: &craft_keymap::Chord| { - rows_keys && chord.is_plain() && !chord.mods.shift && matches!(chord.key, craft_keymap::Key::Delete | craft_keymap::Key::Backspace) - }; - // An Escape that ended a ruler-origin drag or floating Tools move runs no command bound to it. - let gesture_escape = |chord: &craft_keymap::Chord| escape_ended_gesture && chord.is_plain() && chord.key == craft_keymap::Key::Escape; - // A Copy or Cut left to the labels runs neither command from the keymap. - let labels_clip = |hit: &Hit| to_labels && matches!(hit.command.id.as_str(), "edit.copy" | "edit.cut"); - let hits = dispatch(app, ctx, |hit| { - let chord = &hit.trigger.chord; - let shifted_punctuation = chord.mods.shift && chord.key.name().chars().all(|c| !c.is_alphanumeric()); - !(chord.is_plain() && types_text(chord.key) && !shifted_punctuation || row_key(chord) || gesture_escape(chord) || labels_clip(hit)) - }); - let ran = !hits.is_empty(); - for hit in hits { - let c = unshifted_when_dimmed(app, hit); - run_hit(app, ctx, &c); - if dialog_or_palette_open(app) { - break; - } - } - if settings_on_a_mac(app, ctx, mac(ctx)) || ran { - return; - } - if alt_type_arrows(app, ctx) { - return; - } - nudge_and_clear(app, ctx, rows_keys); - single_key_shortcuts(app, ctx); + escape_ends_one_thing(app, ctx); } -/// Did `key` go down in this frame? The key repeats of a held key do not count. -pub(crate) fn pressed_anew(ctx: &egui::Context, key: Key) -> bool { - ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: k, pressed: true, repeat: false, .. } if *k == key))) -} - -/// Is Brush Options open with its Key Color eyedropper armed, waiting for a click on the art? -fn key_color_pick_armed(app: &VectorcraftApp) -> bool { - let open = app.ui.dialog.as_ref().is_some_and(|d| d.kind == crate::dialogs::brush_options::KIND); - open && app.session.tool_id() == "eyedropper" && app.session.tool_options()["brushKeyColor"] == true -} - -/// Takes this frame's repeats of `key` when the tool claims it: a press acts once, and they stay out -/// of the shortcuts. A chord a command is bound to keeps its repeats. -fn take_claimed_repeat(app: &mut VectorcraftApp, ctx: &egui::Context, key: Key, tool_key: ToolKey, view: ViewInfo) -> bool { - let text = app.session.tool_wants_text(); - let runs_a_command = (text || !app.session.tool_busy()) && ctx.input(|i| runs_a_command(i, key, text)); - if runs_a_command || pressed_anew(ctx, key) || !ctx.input(|i| i.key_pressed(key)) || !app.session.tool_claims_key(tool_key, view) { - return false; - } - ctx.input_mut(|i| i.consume_key(Modifiers::NONE, key)); - ctx.input_mut(|i| i.consume_key(Modifiers::SHIFT, key)); - true -} - -/// What Enter and Escape act on: the open dialog, the command search, Edit Toolbar's drawer and -/// Presentation Mode. -type KeySurface = (Option, bool, bool, bool); - -fn key_surface(app: &VectorcraftApp) -> KeySurface { - (app.ui.dialog.as_ref().map(|d| d.kind.clone()), app.ui.palette_open, app.ui.tools_drawer, app.ui.screen_mode == 3) -} - -/// The mark of what `key` went down on; `None` once that has changed. -fn key_surface_id(ctx: &egui::Context, key: Key) -> egui::Id { - egui::Id::unique("key-surface").with(key).with(ctx.viewport_id()) -} - -/// Notes what a new press of Enter or Escape lands on, and forgets it once the key is up. -fn note_key_surfaces(app: &VectorcraftApp, ctx: &egui::Context) { - for key in [Key::Enter, Key::Escape] { - let id = key_surface_id(ctx, key); - if pressed_anew(ctx, key) { - ctx.data_mut(|m| m.insert_temp(id, Some(key_surface(app)))); - } else { - hold_back_key(app, ctx, key); - if !ctx.input(|i| i.key_down(key)) { - ctx.data_mut(|m| m.remove::>(id)); - } - } - } -} - -/// Removes this frame's presses of Enter and Escape when the key went down on something that has -/// since changed: the press that opened or closed a dialog, and its repeats until the key is let -/// go, reach neither the new dialog nor what is under the old one. Also removes the repeats of a -/// key without a modifier that opened a dialog or the palette ([`hold_back_opening_key`]). -pub(crate) fn hold_back_keys(app: &VectorcraftApp, ctx: &egui::Context) { - hold_back_key(app, ctx, Key::Enter); - hold_back_key(app, ctx, Key::Escape); - hold_back_opening_key(ctx); -} - -/// The key of the mark of a key without a modifier whose command opened a dialog or the palette. -fn opening_key_id(ctx: &egui::Context) -> egui::Id { - egui::Id::unique("opening-key").with(ctx.viewport_id()) -} - -/// Removes this frame's repeats of the key without a modifier that opened a dialog or the -/// palette, and the text they type, until that key is let go: a held key does not type into the -/// field that takes the keyboard. -fn hold_back_opening_key(ctx: &egui::Context) { - let id = opening_key_id(ctx); - let Some(key) = ctx.data(|m| m.get_temp::(id)) else { return }; - let repeat_of = |e: Option<&egui::Event>| matches!(e, Some(egui::Event::Key { key: k, pressed: true, repeat: true, .. }) if *k == key); - ctx.input_mut(|i| { - let typed_by = typing_presses(&i.events); - let held: Vec = i - .events - .iter() - .zip(typed_by) - .map(|(e, by)| repeat_of(Some(e)) || matches!(e, egui::Event::Text(_)) && repeat_of(by.and_then(|k| i.events.get(k)))) - .collect(); - let mut held = held.into_iter(); - i.events.retain(|_| !held.next().unwrap_or(false)); - }); - // A repeat that comes in the same frame as the release is held back above; later presses are new. - let released = - ctx.input(|i| !i.key_down(key) || i.events.iter().any(|e| matches!(e, egui::Event::Key { key: k, pressed: false, .. } if *k == key))); - if released { - ctx.data_mut(|m| m.remove::(id)); - } -} - -/// Forgets the key that opened a dialog or the palette ([`hold_back_opening_key`]) once it is up -/// and this frame has none of its events. -fn forget_opening_key(ctx: &egui::Context) { - let id = opening_key_id(ctx); - if let Some(key) = ctx.data(|m| m.get_temp::(id)) - && ctx.input(|i| !i.key_down(key) && !i.events.iter().any(|e| matches!(e, egui::Event::Key { key: k, .. } if *k == key))) - { - ctx.data_mut(|m| m.remove::(id)); - } -} - -fn hold_back_key(app: &VectorcraftApp, ctx: &egui::Context, key: Key) { - let id = key_surface_id(ctx, key); - let Some(pressed_on) = ctx.data(|m| m.get_temp::>(id)) else { return }; - if pressed_on.as_ref() == Some(&key_surface(app)) { - return; - } - ctx.data_mut(|m| m.insert_temp(id, None::)); - ctx.input_mut(|i| i.events.retain(|e| !matches!(e, egui::Event::Key { key: k, pressed: true, .. } if *k == key))); -} - -/// The key of the mark that the Escape held down ended a ruler-origin drag, a floating Tools move -/// or a Control bar gripper drag. -fn escape_ended_gesture_id() -> egui::Id { - egui::Id::unique("escape-ended-gesture") -} - -/// Does this frame's Escape end a ruler-origin drag, a floating Tools move or a Control bar gripper -/// drag? The repeats of an Escape that ended one do too, up to the frame that releases Escape or -/// presses it again. -fn escape_ended_gesture(ctx: &egui::Context) -> bool { - let (down, pressed, repeated) = ctx.input(|i| { - let escape = - |repeat: bool| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: Key::Escape, pressed: true, repeat: r, .. } if *r == repeat)); - (i.key_down(Key::Escape), escape(false), escape(true)) - }); - if crate::canvas::ruler_origin_dragging(ctx) || crate::tools_float::escape_cancelled_move(ctx) || crate::chrome::control_bar_moving(ctx) { - if down { - ctx.data_mut(|d| d.insert_temp(escape_ended_gesture_id(), true)); - } - return true; - } - // A release in the same frame as a repeat still holds that repeat back. - let held = (down || repeated) && !pressed && ctx.data(|d| d.get_temp::(escape_ended_gesture_id())).is_some(); - if !(held && down) { - ctx.data_mut(|d| d.remove::(escape_ended_gesture_id())); - } - held -} - -/// An Escape that no tool, field, popup or drag took ends the first of these that is on: pattern -/// editing, isolation mode, Global Edit, a tool flyout, a full screen mode and a rotated view. +/// An Escape that nothing else took ends the first of these that is on. fn escape_ends_one_thing(app: &mut VectorcraftApp, ctx: &egui::Context) { if app.session.active().is_some_and(|d| d.doc.pattern_edit.is_some()) { let _ = app.run("object.pattern.done", json!({})); @@ -580,609 +78,65 @@ fn escape_ends_one_thing(app: &mut VectorcraftApp, ctx: &egui::Context) { let _ = app.run("object.exitIsolation", json!({ "all": true })); } else if app.session.active().is_some_and(|d| d.global_edit.is_some()) { let _ = app.run("select.globalEdit", json!({})); - } else if app.ui.flyout.is_some() { - app.ui.flyout = None; } else if app.session.tool_id() == "rotateView" && escape_resets_rotation(app, ctx) { // With the Rotate View tool, the view resets before a full screen mode ends. let _ = app.run("view.rotateReset", json!({})); - } else if matches!(app.ui.screen_mode, 1 | 2) - && !egui::Popup::is_any_open(ctx) - && !text_focused_in_previous_frame(ctx) - && ctx.input(|i| { - i.events.iter().any( - |e| matches!(e, egui::Event::Key { key: Key::Escape, pressed: true, repeat: false, modifiers, .. } if *modifiers == Modifiers::NONE), - ) - }) - { + } else if matches!(app.ui.screen_mode, 1 | 2) && keys::escape_mods(ctx).is_none() { let _ = app.run("view.screenMode", json!({ "mode": 0 })); } else if escape_resets_rotation(app, ctx) { - // An Escape that has nothing else to end resets a rotated view. After one that ended - // something, the next one does, however long after it comes. A modified Escape does not - // leave a full screen mode, so it resets the view there. + // An Escape that has nothing else to end resets a rotated view. A modified Escape does not leave a full + // screen mode, so it resets the view there. let _ = app.run("view.rotateReset", json!({})); } } -/// What a tool's Escape can change besides what [`vectorcraft_engine::Session::tool_ends_on_escape`] -/// reports: the document's revision (edits and selection changes, such as the Curvature tool -/// letting go of a selected path's current point). -fn document_revision(app: &VectorcraftApp) -> Option { - app.session.active().map(|d| d.revision) -} - -/// Dispatch unmodified text keys to command bindings or tools. -fn single_key_shortcuts(app: &mut VectorcraftApp, ctx: &egui::Context) { - // Single-key tool shortcuts (no Cmd/Ctrl/Alt). With a layout without Latin letters (Persian, - // Arabic, Russian, Greek…) the key's position stands in for what it types (#793). - // A text's key is the press that typed it ([`typing_presses`]), and the text repeats with it. - let events: Vec<(String, Modifiers, Option, bool)> = ctx.input(|i| { - let typed_by = typing_presses(&i.events); - i.events - .iter() - .zip(typed_by) - .filter_map(|(e, by)| match e { - egui::Event::Text(t) => { - let (physical, key, repeat) = match by.and_then(|k| i.events.get(k)) { - Some(egui::Event::Key { key, physical_key, repeat, .. }) => (*physical_key, Some(*key), *repeat), - _ => (None, None, false), - }; - Some((latin(t, physical), i.modifiers, key, repeat)) - } - _ => None, - }) - .collect() - }); - for (text, m, pressed, repeat) in events { - if m.command || m.alt || m.ctrl { - continue; +/// An arrow nudge of the window or of a tool that left it. `direction` points the way of the arrow. In +/// Presentation Mode Left and Right step the artboard and nothing moves; with only type selected, Alt steps the +/// type's spacing; otherwise the selection moves (Shift ×10, Alt copies, `patterns_only` moves pattern fills only). +pub(crate) fn nudge(app: &mut VectorcraftApp, direction: egui::Vec2, mods: Mods, patterns_only: bool) { + if app.ui.screen_mode == 3 { + if direction.x != 0.0 { + presentation_step(app, direction.x > 0.0); } - let chords = text_chords(&text, m, pressed); - if run_single_key(app, ctx, &chords, pressed, repeat) { - break; - } - } -} - -/// The chords a single-key shortcut reads for `text`, typed with `m` by the key `pressed`. -fn text_chords(text: &str, m: Modifiers, pressed: Option) -> Vec { - let upper = text.to_uppercase(); - let key = if m.shift && text.chars().all(|c| c.is_alphabetic()) { format!("Shift+{upper}") } else { upper.clone() }; - // A shifted punctuation character can also be written with its Shift (the Curvature tool's - // Shift+~ arrives as `~`). - let shifted = m.shift.then(|| format!("Shift+{text}")); - let mut chords: Vec = - [Some(key), Some(text.to_string()), shifted].into_iter().flatten().filter_map(|t| crate::keymap::vc_chord(&t)).collect(); - // A character no chord names (`"`, which the backtick key types on Turkish Q) is read as - // the key that typed it, as the Keyboard Shortcuts editor records that press. - if chords.is_empty() { - let typed_by = pressed.and_then(|k| crate::shortcut_editor::chord_from_event(k, Modifiers { shift: m.shift, ..Modifiers::NONE })); - chords.extend(typed_by.and_then(|t| crate::keymap::vc_chord(&t))); - } - chords -} - -/// Runs the single-key shortcut of `chords`, typed by the key `pressed`. True when it opened a -/// dialog or the palette: the shortcuts after it in the frame do not run. -fn run_single_key(app: &mut VectorcraftApp, ctx: &egui::Context, chords: &[craft_keymap::Chord], pressed: Option, repeat: bool) -> bool { - let keymap = crate::shortcut_editor::current(); - let hits: Vec = chords.iter().filter_map(|c| crate::keymap::lookup(&keymap.keymap, c)).collect(); - // Single-key command shortcuts (X, Shift+X, D, /, Shift+D, F, Shift+F by default) before - // tools. - let Some(hit) = hits.iter().find(|c| !c.id.starts_with("tool:")).or(hits.first()) else { return false }; - // A command runs as it does on a chord ([`run_hit`]): what its menu item runs. Smooth opens - // its slider, and Move opens its dialog. - match hit.id.strip_prefix("tool:") { - Some(tool) => { - held_tool::choose(app, ctx, tool, pressed, repeat); - false - } - None => { - run_hit(app, ctx, hit); - if !dialog_or_palette_open(app) { - return false; - } - if let Some(key) = pressed { - let id = opening_key_id(ctx); - ctx.data_mut(|m| m.insert_temp(id, key)); - } - true - } - } -} - -/// Is a dialog or the palette open? A shortcut that opens one stops the shortcuts after it in the -/// same frame. -fn dialog_or_palette_open(app: &VectorcraftApp) -> bool { - app.ui.dialog.is_some() || app.ui.palette_open -} - -/// Route Alt+arrows to spacing controls when text objects are selected. -fn alt_type_arrows(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { - let keys = [(Key::ArrowLeft, ToolKey::Left), (Key::ArrowRight, ToolKey::Right), (Key::ArrowUp, ToolKey::Up), (Key::ArrowDown, ToolKey::Down)]; - // The modifiers held when each arrow went down, as `nudge_and_clear` reads them. - let pressed = keys.map(|(key, tool_key)| (key, tool_key, ctx.input(|i| press_modifiers(i, key)))); - if !pressed.iter().any(|(.., m)| m.alt) { - return false; - } - let orientation = app.session.active().and_then(|st| { - if !st.selection.guides.is_empty() || st.selection.objects.is_empty() { - return None; - } - let mut all_vertical = true; - for id in &st.selection.objects { - let node = st.doc.node(*id)?; - let vectorcraft_doc::NodeKind::Text(t) = &node.kind else { return None }; - all_vertical &= t.vertical; - } - Some(all_vertical) - }); - let Some(vertical) = orientation else { - return false; - }; - for (key, tool_key, m) in pressed { - if m.alt && ctx.input_mut(|i| i.consume_key(m, key)) { - if let Some((attribute, by)) = vectorcraft_tools::text::step_key(tool_key, m.shift, false, vertical) { - let by = if m.command { by * 5.0 } else { by }; - let _ = app.run("type.step", json!({"attribute": attribute, "by": by})); - } - return true; - } - } - false -} - -/// Route text-tool input and command chords while preserving IME composition ownership. -fn type_tool_input(app: &mut VectorcraftApp, ctx: &egui::Context, composing: bool) { - // Route-level loss (no current target or caret geometry) retires a live guard before any - // marker in this pass can be considered. The finalizer may re-arm on a later activation. - crate::ime::suspend_if_route_lost(app, ctx); - let old_composition_retired = type_text(app, ctx); - // Keys of a frame that began composing are the IME's too (a Backspace that empties the - // marked text must not delete the committed character before it). - if composing && !old_composition_retired || app.session.tool_composing() { - // The IME owns the keyboard until it commits: no editing keys, clipboard or shortcuts. - ctx.input_mut(|i| i.events.retain(|e| !matches!(e, egui::Event::Key { .. } | egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_)))); return; } - crate::panels::actions::play_function_key(app, ctx); - // Cmd+A is Select All's, below: the text. Enter went to the tool in `type_text`, unless a - // command is bound to its chord, and so did the editing keys and the clipboard events (a - // cut or paste after a deferred pointer or navigation notice is dropped there). Only chords - // with the command key run commands: the rest type or edit. - let hits = dispatch(app, ctx, |hit| hit.trigger.chord.mods.cmd); - for hit in hits { - let c = unshifted_when_dimmed(app, hit); - run_hit(app, ctx, &c); - if dialog_or_palette_open(app) { - break; - } - } - settings_on_a_mac(app, ctx, mac(ctx)); -} - -/// The modifiers held when `key` last went down in this frame, which can differ from the frame's -/// at its end; the frame's when the key did not go down. -fn press_modifiers(i: &egui::InputState, key: Key) -> Modifiers { - i.events - .iter() - .rev() - .find_map(|e| match e { - egui::Event::Key { key: k, pressed: true, modifiers, .. } if *k == key => Some(*modifiers), - _ => None, - }) - .unwrap_or(i.modifiers) -} - -/// Backquote held when `key` last went down, before any later transitions in the frame. -fn backquote_at_press(i: &egui::InputState, key: Key) -> bool { - let mut held = i.key_down(Key::Backtick); - for event in i.events.iter().rev() { - match event { - egui::Event::Key { key: k, pressed: true, .. } if *k == key => return held, - egui::Event::Key { key: Key::Backtick, pressed, repeat: false, .. } => held = !*pressed, - _ => {} - } - } - i.key_down(Key::Backtick) -} - -/// Apply arrow-key movement and clear selected art when no text editor owns input, unless a Layers -/// or Appearance row has Delete/Backspace (`rows_keys`). -fn nudge_and_clear(app: &mut VectorcraftApp, ctx: &egui::Context, rows_keys: bool) { - // Arrow nudges (Shift = ×10, Alt = copy). - let arrows = [(Key::ArrowLeft, -1.0, 0.0), (Key::ArrowRight, 1.0, 0.0), (Key::ArrowUp, 0.0, -1.0), (Key::ArrowDown, 0.0, 1.0)]; - for (k, dx, dy) in arrows { - // The modifiers held when the key went down, as `claimed_tool_keys` reads them. - let (m, patterns_only) = ctx.input(|i| (press_modifiers(i, k), backquote_at_press(i, k))); - if ctx.input_mut(|i| i.consume_key(m, k)) && app.session.active().is_some_and(|d| d.selection.has_objects_or_guides()) { - let mut params = json!({"dx": dx, "dy": dy, "big": m.shift, "copy": m.alt}); - if patterns_only { - params["objects"] = json!(false); - params["patterns"] = json!(true); - } - let _ = app.run("object.nudge", params); - } - } - // Delete / Backspace clear the selection. - if !rows_keys - && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Backspace)) - && app.session.active().is_some_and(|d| d.selection.has_objects_or_guides()) + if mods.alt + && let Some(vertical) = selected_type_is_vertical(app) { - let _ = app.run("edit.clear", json!({})); + let key = match (direction.x, direction.y) { + (x, _) if x < 0.0 => ToolKey::Left, + (x, _) if x > 0.0 => ToolKey::Right, + (_, y) if y < 0.0 => ToolKey::Up, + _ => ToolKey::Down, + }; + if let Some((attribute, by)) = vectorcraft_tools::text::step_key(key, mods.shift, false, vertical) { + let by = if mods.cmd { by * 5.0 } else { by }; + let _ = app.run("type.step", json!({"attribute": attribute, "by": by})); + } + return; + } + if app.session.active().is_some_and(|d| d.selection.has_objects_or_guides()) { + let mut params = json!({"dx": f64::from(direction.x), "dy": f64::from(direction.y), "big": mods.shift, "copy": mods.alt}); + if patterns_only { + params["objects"] = json!(false); + params["patterns"] = json!(true); + } + let _ = app.run("object.nudge", params); } } -/// Route clipboard events to the system clipboard or the app's rich-format paste path. → whether -/// a Copy or Cut is left to the labels, so no shortcut runs it. -fn handle_clipboard(app: &mut VectorcraftApp, ctx: &egui::Context, textless_paste: Option) -> bool { - // A clipboard image (eframe's `clipboard` feature, 0.37): the host's text paste path never - // carries it. With the app's rich-format `SystemClipboard`, it is only the signal that the - // clipboard holds no text — the next tick invokes Paste, whose `adopt_system_clipboard` reads - // the formats once (never paste twice). Without one (the web/simple host), turn the pixels - // into a PNG flavour and paste that. - let image_paste = app.services.system_clipboard.is_none(); - let mut pasted_image: Option> = None; - let mut read_image_formats = false; - // `MiddleClickPaste` is deliberately left in `i.events`: the Type tool above already took it, - // and otherwise egui's text field under the pointer (focused or not) pastes it later in this - // pass. It is not a shortcut. - ctx.input_mut(|i| { - i.events.retain(|e| match e { - egui::Event::PasteImage(image) => { - if image_paste { - if pasted_image.is_none() { - let pixels: Vec = image.pixels.iter().flat_map(|c| c.to_array()).collect(); - let rendered = vectorcraft_render::Rendered { - width: u32::try_from(image.size[0]).unwrap_or(0), - height: u32::try_from(image.size[1]).unwrap_or(0), - pixels, - }; - // A renderer failure leaves the paste as the no-op an empty flavour gets. - pasted_image = rendered.to_png().ok(); - } - } else { - read_image_formats = true; - } - false - } - _ => true, - }) - }); - if read_image_formats { - // A text paste in the same frame wins, as it does for a clipboard with text and a picture: - // the paste chord path below reads the text. An image-only clipboard is read here. - if pasted_image.is_none() && textless_paste.is_none() && !ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Paste(_)))) { - // Remember the chord as it was when the image was pasted: the next `tick` runs in a - // later input pass whose modifiers need not describe this paste. The request also - // schedules that tick; nothing else may be coming to run it. - app.clipboard_image_request = Some(ctx.input(|i| i.modifiers)); - ctx.request_repaint(); - } +/// Whether the selection is only type, and then whether all of it is vertical. +fn selected_type_is_vertical(app: &VectorcraftApp) -> Option { + let st = app.session.active()?; + if !st.selection.guides.is_empty() || st.selection.objects.is_empty() { + return None; } - if let Some(png) = pasted_image { - let held = ctx.input(|i| i.modifiers); - app.clipboard_in = Some(Flavour { mime: vectorcraft_engine::cmd::clipboard::PNG, data: png }); - crate::menus::invoke(app, paste_command(held), json!({})); - return false; + let mut all_vertical = true; + for id in &st.selection.objects { + let vectorcraft_doc::NodeKind::Text(t) = &st.doc.node(*id)?.kind else { return None }; + all_vertical &= t.vertical; } - // Clipboard keys arrive as events, not key presses; the chord held says which paste. Copy and - // Cut with text selected in a label copy that text ([`leave_to_labels`]), unless another window - // sent them on (a floating document's): those copy the art. The menu bar's Copy and Cut have - // left theirs to the labels already and dropped the unwritten formats; dropping them again - // here does nothing more. - let mut clip = vec![]; - let forwarded = app.forwarded_clipboard && ctx.viewport_id() == egui::ViewportId::ROOT; - let to_labels = |e: egui::Event, id| { - ctx.input(|i| i.events.contains(&e)) && (left_to_labels(ctx) == Some(id) || (!forwarded && leave_to_labels(app, ctx, id))) - }; - let (labels_copy, labels_cut) = (to_labels(egui::Event::Copy, "edit.copy"), to_labels(egui::Event::Cut, "edit.cut")); - // The labels' text, or the art copied in the next pass when they copy nothing, replaces what an - // earlier Copy or Cut has not written yet. - if labels_copy || labels_cut { - app.drop_unwritten_formats(); - } - ctx.input_mut(|i| { - let held = i.modifiers; - i.events.retain(|e| { - let (id, text) = match e { - egui::Event::Copy if labels_copy => return true, - egui::Event::Cut if labels_cut => return true, - egui::Event::Copy => ("edit.copy", None), - egui::Event::Cut => ("edit.cut", None), - egui::Event::Paste(t) => (paste_command(held), Some(t.clone())), - _ => return true, - }; - clip.push((id, text)); - false - }) - }); - // Only the system clipboard service reads what isn't text. - if let Some(id) = textless_paste.map(paste_command) - && app.services.system_clipboard.is_some() - { - clip.push((id, None)); - } - for (id, text) in clip { - app.clipboard_in = text.map(|t| Flavour { mime: TEXT, data: t.into_bytes() }); - crate::menus::invoke(app, id, json!({})); - } - labels_copy || labels_cut -} - -/// Copy or Cut (`id`) on a key that egui does not send as a Copy or Cut event (F3 and F2 off -/// macOS, a key of the user's own): with text selected in a label, the labels copy it, as they do -/// for Cmd/Ctrl+C and X ([`leave_to_labels`]) (→ true). When a key another window sent on in this -/// frame (a floating document's) runs `id`, the art is copied. -fn clipboard_key_to_labels(app: &mut VectorcraftApp, ctx: &egui::Context, id: &str) -> bool { - let (command, event) = match id { - "edit.copy" => ("edit.copy", egui::Event::Copy), - "edit.cut" => ("edit.cut", egui::Event::Cut), - _ => return false, - }; - if ctx.viewport_id() == egui::ViewportId::ROOT && forwarded_key_runs(app, command) || !leave_to_labels(app, ctx, command) { - return false; - } - ctx.input_mut(|i| i.events.push(event)); - app.drop_unwritten_formats(); - true -} - -/// Does a key press another window sent on in this frame run command `id`? -fn forwarded_key_runs(app: &VectorcraftApp, id: &str) -> bool { - let mirror = crate::shortcut_editor::current(); - let platform = crate::keymap::platform(); - app.forwarded_presses.iter().filter_map(|e| craft_keymap::KeyInput::from_egui(e, platform)).any(|input| { - app.dispatcher.layout().candidates(&input).iter().any(|chord| crate::keymap::lookup(&mirror.keymap, chord).is_some_and(|c| c.id == id)) - }) -} - -/// Route arrows, digits and letters to a tool while a gesture is active. -fn busy_tool_keys(app: &mut VectorcraftApp, ctx: &egui::Context, view: ViewInfo) { - // The arrows while dragging: a polygon's sides, a grid's rows (↑/↓) and columns (←/→)… - let arrows = [(Key::ArrowUp, ToolKey::Up), (Key::ArrowDown, ToolKey::Down), (Key::ArrowLeft, ToolKey::Left), (Key::ArrowRight, ToolKey::Right)]; - for (k, tk) in arrows { - // The press's Shift and Alt (the consume below takes those presses too) go to a tool that - // claims the arrow (Shift steps a blend widget by ten); other tools get the plain arrow. - let pressed = ctx.input(|i| { - i.events.iter().find_map(|e| match e { - egui::Event::Key { key, pressed: true, modifiers, .. } if *key == k && !(modifiers.command || modifiers.ctrl) => Some(*modifiers), - _ => None, - }) - }); - if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)) { - let mods = match pressed { - Some(m) if app.session.tool_claims_key(tk, view) => crate::canvas::mods(m, false), - _ => Mods::default(), - }; - let _ = app.session.tool_key(tk, mods, view); - } - } - // Digits (5 while dragging with the Perspective Selection tool), once per press. - let digits: Vec = ctx.input(|i| { - i.events - .iter() - .filter_map(|e| match e { - egui::Event::Key { key, pressed: true, repeat: false, .. } => digit_of(*key), - _ => None, - }) - .collect() - }); - for d in digits { - let _ = app.session.tool_key(ToolKey::Digit(d), Mods::default(), view); - } - // `[` and `]` while the Quick Pen tool draws a piece: the arc being dragged takes the new size. - // The Blob Brush, Eraser and Symbolism tools do not get them during a press, so their size and - // intensity stay as they were when the press began. - if app.session.tool_id() == vectorcraft_tools::quickpen::ID { - tool_brackets(app, ctx, view); - } - // Tab, when the tool takes it (the Smart Pen Tool placing an anchor). - if app.session.tool_claims_key(ToolKey::Tab, view) && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Tab)) { - let _ = app.session.tool_key(ToolKey::Tab, Mods::default(), view); - } - // The tool gets each letter it takes (E while dragging a selection marquee) once per press, - // without Cmd, Ctrl or Alt. The key is the one egui reports, which on a layout without Latin - // letters is the key at that position on a US layout. - let letters: Vec = ctx.input(|i| { - i.events - .iter() - .filter_map(|e| match e { - egui::Event::Key { key, pressed: true, repeat: false, modifiers, .. } if !(modifiers.command || modifiers.alt || modifiers.ctrl) => { - letter_of(*key) - } - _ => None, - }) - .collect() - }); - for c in letters { - if app.session.tool_claims_key(ToolKey::Letter(c), view) { - let _ = app.session.tool_key(ToolKey::Letter(c), Mods::default(), view); - } - } - // Between clicks, the active tool's shortcut chooses that tool again (W with the Blend - // tool's first pick held finishes the blend). While the button is held, it does nothing. - if !app.session.pointer_held() { - let presses = ctx.input(|i| shortcut_presses(&i.events, i.modifiers)); - let keymap = crate::shortcut_editor::current(); - let active = app.session.tool_id(); - let again = presses.iter().any(|(names, letter)| { - let claimed = letter.is_some_and(|c| app.session.tool_claims_key(ToolKey::Letter(c), view)); - // The first name bound to anything is the press's shortcut (Shift+W is the Width - // tool's, not W's). - !claimed - && names - .iter() - .find_map(|name| crate::keymap::vc_chord(name).and_then(|c| crate::keymap::lookup(&keymap.keymap, &c))) - .is_some_and(|c| c.id.strip_prefix("tool:") == Some(active)) - }); - if again { - app.select_tool(active); - } - } -} - -/// Give keys claimed by the active tool precedence over their command shortcuts, except a plain -/// Delete or Backspace while a panel's rows have them (`rows_keys`). -fn claimed_tool_keys(app: &mut VectorcraftApp, ctx: &egui::Context, view: ViewInfo, rows_keys: bool) -> bool { - let m = ctx.input(|i| i.modifiers); - let rows_take = |k: Key| rows_keys && m.is_none() && matches!(k, Key::Delete | Key::Backspace); - for (k, tk) in [ - (Key::Delete, ToolKey::Delete), - (Key::Backspace, ToolKey::Backspace), - (Key::ArrowLeft, ToolKey::Left), - (Key::ArrowRight, ToolKey::Right), - (Key::ArrowUp, ToolKey::Up), - (Key::ArrowDown, ToolKey::Down), - // The Smart Pen Tool's Tab while it draws a path (the key otherwise hides the panels). - (Key::Tab, ToolKey::Tab), - ] { - let pm = ctx.input(|i| press_modifiers(i, k)); - if !rows_take(k) - && ctx.input(|i| i.key_pressed(k)) - && app.session.tool_claims_key_with(tk, crate::canvas::mods(pm, false), view) - && ctx.input_mut(|i| i.consume_key(pm, k)) - { - let r = app.session.tool_key(tk, crate::canvas::mods(pm, false), view); - // Keyboard actions can change the Artboard tool's active board too. Keep the - // navigator aligned with its valid survivor, as pointer dispatch does. - if r.is_ok() - && app.session.tool_id() == "artboard" - && let Some(i) = app.session.tool_options()["active"].as_u64().and_then(|i| usize::try_from(i).ok()) - && app.session.active().is_some_and(|d| i < d.doc.artboards.len()) - && let Some(v) = app.view_mut() - { - v.artboard = i; - } - crate::canvas::apply_requests(app, r); - return true; - } - } - // Digits the active tool or the perspective grid takes (1–4 pick the plane while it shows). - if !(m.command || m.alt || m.ctrl) { - let digits: Vec<(u8, Key)> = ctx.input(|i| { - i.events - .iter() - .filter_map(|e| match e { - egui::Event::Key { key, pressed: true, .. } => digit_of(*key).map(|d| (d, *key)), - _ => None, - }) - .collect() - }); - for (d, k) in digits { - if app.session.tool_claims_key(ToolKey::Digit(d), view) && ctx.input_mut(|i| i.consume_key(m, k)) { - // The digit's text is the key's too: no single-key shortcut sees it. - let text = d.to_string(); - ctx.input_mut(|i| i.events.retain(|e| !matches!(e, egui::Event::Text(t) if *t == text))); - let r = app.session.tool_key(ToolKey::Digit(d), crate::canvas::mods(m, false), view); - crate::canvas::apply_requests(app, r); - return true; - } - } - } - tool_brackets(app, ctx, view) -} - -/// `[` and `]` the active tool takes (the Blob Brush's and the Eraser's size, the Symbolism tools' -/// diameter, with Shift their intensity). Read as typed, so layouts where a bracket takes Option or -/// AltGr count too; `{` and `}` are Shift's. Did the tool take one? -fn tool_brackets(app: &mut VectorcraftApp, ctx: &egui::Context, view: ViewInfo) -> bool { - let m = ctx.input(|i| i.modifiers); - if !(m.command || m.ctrl) { - let typed: Vec<(String, ToolKey, bool)> = ctx.input(|i| { - i.events - .iter() - .filter_map(|e| match e { - egui::Event::Text(t) => match t.as_str() { - "[" => Some((t.clone(), ToolKey::BracketLeft, false)), - "]" => Some((t.clone(), ToolKey::BracketRight, false)), - "{" => Some((t.clone(), ToolKey::BracketLeft, true)), - "}" => Some((t.clone(), ToolKey::BracketRight, true)), - _ => None, - }, - _ => None, - }) - .collect() - }); - let mut taken = false; - for (text, key, shift) in typed { - if app.session.tool_claims_key(key, view) { - ctx.input_mut(|i| i.events.retain(|e| !matches!(e, egui::Event::Text(t) if *t == text))); - let r = app.session.tool_key(key, Mods { shift, ..Mods::default() }, view); - crate::canvas::apply_requests(app, r); - taken = true; - } - } - if taken { - return true; - } - } - false -} - -/// Runs this frame's key presses against the keymap in effect; `accept` declines a hit, leaving -/// its press (and the text it typed) to what follows. Each hit's command is worked out with -/// [`unshifted_when_dimmed`] just before it runs, after the commands of the presses before it. -fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, accept: impl FnMut(&Hit) -> bool) -> Vec { - let mirror = crate::shortcut_editor::current(); - let dispatcher = &mut app.dispatcher; - ctx.input_mut(|i| { - // An explicit shifted logical binding takes precedence. Otherwise, Shift+Comma and - // Shift+Period follow their key positions when no chord for the press is bound. - for e in &mut i.events { - let input = craft_keymap::KeyInput::from_egui(e, crate::keymap::platform()); - if let egui::Event::Key { key, physical_key: Some(physical), modifiers, pressed: true, .. } = e - && modifiers.shift - && !modifiers.command - && !modifiers.ctrl - && !modifiers.alt - && !modifiers.mac_cmd - && matches!(*physical, Key::Comma | Key::Period) - && *key != *physical - && let (Some(logical), Some(position)) = (craft_keymap::Key::from_egui(*key), craft_keymap::Key::from_egui(*physical)) - && let Some(input) = input - { - let mods = craft_keymap::Mods::from_egui(modifiers, crate::keymap::platform()); - let logical_chord = craft_keymap::Chord::new(mods, logical); - let position_chord = craft_keymap::Chord::new(mods, position); - if crate::keymap::lookup(&mirror.keymap, &logical_chord).is_some() { - *physical = *key; - } else if crate::keymap::lookup(&mirror.keymap, &position_chord).is_some() - && !dispatcher.layout().candidates(&input).iter().any(|chord| crate::keymap::lookup(&mirror.keymap, chord).is_some()) - { - *key = *physical; - } - } - } - // Shift+`=` types `+`: as the Plus key it also reaches a `=` chord held with Shift - // (Cmd+Shift+= zooms in as Cmd+= does while Superscript is dimmed: [`unshifted_when_dimmed`]). - for e in &mut i.events { - if let egui::Event::Key { key, modifiers, .. } = e - && *key == Key::Equals - && modifiers.shift - { - *key = Key::Plus; - } - } - dispatcher.dispatch_filtered(i, &mirror.keymap, &Active::NONE, accept) - }) -} - -/// The command a hit runs. A Shift+`=` chord whose command is dimmed runs what the same chord -/// without Shift runs, when that is bound: Cmd+Shift+= (Superscript) zooms in, as Cmd+= does, -/// while no type is selected. -fn unshifted_when_dimmed(app: &VectorcraftApp, hit: Hit) -> CommandRef { - let mirror = crate::shortcut_editor::current(); - let chord = hit.trigger.chord; - if chord.key == craft_keymap::Key::Equals - && chord.mods.shift - && !hit.trigger.double - && !crate::menus::enabled(app, &hit.command.id) - && let Some(unshifted) = - crate::keymap::lookup(&mirror.keymap, &craft_keymap::Chord::new(craft_keymap::Mods { shift: false, ..chord.mods }, chord.key)) - { - return unshifted; - } - hit.command + Some(all_vertical) } /// What a shortcut without params runs when its command's menu bar item gives params @@ -1223,162 +177,5 @@ fn shortcut_params(c: &CommandRef) -> serde_json::Value { params } -/// Runs what a shortcut is bound to: a tool, a panel (`window.panel {panel}`) or a command. -fn run_hit(app: &mut VectorcraftApp, ctx: &egui::Context, c: &CommandRef) { - if let Some(tool) = c.id.strip_prefix("tool:") { - app.select_tool(tool); - } else if c.id == "select.all" && crate::panels::artboards::selects_all(app, ctx) { - // With the Artboard tool, Select All's keys after a click on an Artboards panel row select - // every artboard instead of the art. - crate::panels::artboards::select_all(app); - } else if clipboard_key_to_labels(app, ctx, &c.id) { - // The labels copy their selected text at the end of the pass. - } else { - match menu_target(app, c) { - Some(Ok((id, p))) => crate::menus::invoke(app, &id, p), - Some(Err(why)) => app.status(why), - None => crate::menus::invoke(app, &c.id, shortcut_params(c)), - } - } -} - -/// Keys that type a character: letters, digits and punctuation (not Space). -pub(crate) fn types_text(key: craft_keymap::Key) -> bool { - key.name().chars().count() == 1 -} - -/// Whether the app runs on a Mac (on the web, in a browser on a Mac). -fn mac(ctx: &egui::Context) -> bool { - ctx.os() == egui::os::OperatingSystem::Mac -} - -/// On a Mac, Cmd+, opens Settings as in every Mac app (#663), beside Preferences' own shortcut, -/// when no shortcut took the press this frame. Runs after [`dispatch`]. `true` when it ran. -fn settings_on_a_mac(app: &mut VectorcraftApp, ctx: &egui::Context, mac: bool) -> bool { - if !mac { - return false; - } - let pressed = ctx.input_mut(|i| { - let at = i.events.iter().position( - |e| matches!(e, egui::Event::Key { key: Key::Comma, pressed: true, modifiers, .. } if modifiers.matches_exact(Modifiers::COMMAND)), - ); - at.map(|at| i.events.remove(at)).is_some() - }); - if pressed { - crate::menus::invoke(app, "edit.preferences", json!({})); - } - pressed -} - -/// What a single-key shortcut reads for `text`, typed by the key at `physical`: the text itself, -/// or, when it holds no ASCII character (a layout without Latin letters), what that key types on a -/// US layout, so V selects the Selection tool whatever the V key types. -fn latin(text: &str, physical: Option) -> String { - match physical { - Some(k) if !text.is_ascii() => k.symbol_or_name().to_lowercase(), - _ => text.to_string(), - } -} - -/// For each event, the index of the key press that typed it when it is text: the press right -/// before it (egui-winit) unless an earlier text took that press, or else the press right after it -/// (eframe's web build with no text field focused). Modifier key presses type no text. Each press -/// types at most one text. A text takes the press after it only when every later text in the same -/// run of alternating texts and presses has a press after it too; otherwise the text after that -/// press takes it as the press before it, and this text has none. -pub(crate) fn typing_presses(events: &[egui::Event]) -> Vec> { - let is_press = |k: usize| matches!(events.get(k), Some(egui::Event::Key { key, pressed: true, .. }) if !is_modifier(*key)); - let is_text = |k: usize| matches!(events.get(k), Some(egui::Event::Text(_))); - // Whether the run of alternating texts and presses that starts with the text at `j` ends - // with a press. - let ends_with_press = |mut j: usize| loop { - if !is_press(j + 1) { - break false; - } - if !is_text(j + 2) { - break true; - } - j += 2; - }; - let mut taken = None; - events - .iter() - .enumerate() - .map(|(j, e)| { - if !matches!(e, egui::Event::Text(_)) { - return None; - } - let before = j.checked_sub(1).filter(|&k| is_press(k) && taken != Some(k)); - let by = before.or_else(|| ends_with_press(j).then_some(j + 1)); - taken = by.or(taken); - by - }) - .collect() -} - -/// Each new press's shortcut names, first match first, and the letter it types, without Cmd, Ctrl -/// or Alt. A text-only press counts as well (Shift+~ arrives as the text `~` with Shift), unless -/// the key that typed it repeated. A text's key is the one `typing_presses` pairs it with. Text -/// reads its key's modifiers, or the latest modifier change (`held` before any), and tries its -/// key's own name first. -fn shortcut_presses(events: &[egui::Event], held: Modifiers) -> Vec<(Vec, Option)> { - let key_name = |key: &Key, m: &Modifiers| if m.shift { format!("Shift+{}", key.name()) } else { key.name().to_string() }; - let press_at = |j: Option| match j.and_then(|j| events.get(j)) { - Some(egui::Event::Key { key, pressed: true, repeat, modifiers, .. }) => Some((*repeat, *modifiers, key_name(key, modifiers))), - _ => None, - }; - let typed_by = typing_presses(events); - let mut latest = held; - events - .iter() - .enumerate() - .filter_map(|(j, e)| match e { - egui::Event::ModifiersChanged(m) => { - latest = *m; - None - } - egui::Event::Key { key, pressed: true, repeat: false, modifiers, .. } if !(modifiers.command || modifiers.alt || modifiers.ctrl) => { - Some((vec![key_name(key, modifiers)], letter_of(*key))) - } - egui::Event::Text(t) => { - let (repeated, mods, key_name) = - press_at(typed_by.get(j).copied().flatten()).map_or((false, latest, None), |(r, m, n)| (r, m, Some(n))); - if repeated || mods.command || mods.alt || mods.ctrl { - return None; - } - let upper = t.to_uppercase(); - let alpha = t.chars().all(|c| c.is_alphabetic()); - // A shifted letter is only Shift+letter; other shifted text may also be written - // without its Shift. - let text_names = match (mods.shift, alpha) { - (true, true) => vec![format!("Shift+{upper}")], - (true, false) => vec![upper, t.clone(), format!("Shift+{t}")], - (false, _) => vec![upper, t.clone()], - }; - let names: Vec = key_name.into_iter().chain(text_names).collect(); - let mut chars = t.chars(); - let letter = chars.next().filter(|c| c.is_ascii_alphabetic() && chars.next().is_none()).map(|c| c.to_ascii_lowercase()); - Some((names, letter)) - } - _ => None, - }) - .collect() -} - -/// The digit a number-row or keypad key types. -fn digit_of(k: Key) -> Option { - const DIGITS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::Num4, Key::Num5, Key::Num6, Key::Num7, Key::Num8, Key::Num9]; - DIGITS.iter().position(|d| *d == k).map(|i| i as u8) -} - -/// The lowercase letter a letter key A–Z stands for. -fn letter_of(k: Key) -> Option { - let mut name = k.name().chars(); - match (name.next(), name.next()) { - (Some(c), None) if c.is_ascii_alphabetic() => Some(c.to_ascii_lowercase()), - _ => None, - } -} - #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/shortcuts/alt_tap.rs b/crates/ui-egui/src/shortcuts/alt_tap.rs deleted file mode 100644 index b92d6c3800..0000000000 --- a/crates/ui-egui/src/shortcuts/alt_tap.rs +++ /dev/null @@ -1,114 +0,0 @@ -//! Alt (Option on macOS) pressed and let go with no other key, click or wheel turn in between: the -//! active tool gets [`ToolKey::AltTap`](vectorcraft_tools::ToolKey::AltTap) when it claims it (the -//! Quick Pen tool switches to its next action). - -/// Alt held down since it went down, and whether anything else happened since. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct AltTap { - down: bool, - spoiled: bool, -} - -impl AltTap { - /// The modifiers changed: `alt` is whether Alt is held, `alone` whether it is held without - /// Shift, Ctrl or Cmd. True when Alt was let go after a press with nothing else in between. - pub(crate) fn modifiers(&mut self, alt: bool, alone: bool) -> bool { - match (self.down, alt) { - (false, true) => { - (self.down, self.spoiled) = (true, !alone); - false - } - (true, true) => { - self.spoiled |= !alone; - false - } - (true, false) => { - let tap = !self.spoiled; - *self = Self::default(); - tap - } - (false, false) => false, - } - } - - /// A key press, a click or a wheel turn: Alt held now is no tap. - pub(crate) fn other(&mut self) { - self.spoiled = true; - } -} - -fn alt_alone(m: egui::Modifiers) -> (bool, bool) { - (m.alt, !(m.shift || m.ctrl || m.command || m.mac_cmd)) -} - -/// Follows the frame's events in order, then its modifiers at its end; true when Alt was tapped, -/// also when it went down and up within the frame. A frame without the keyboard focus drops a -/// press under way. -pub(super) fn follow(tap: &mut AltTap, ctx: &egui::Context, focused: bool) -> bool { - if !focused { - *tap = AltTap::default(); - return false; - } - ctx.input(|i| { - let mut tapped = false; - for e in &i.events { - match e { - egui::Event::ModifiersChanged(m) => { - let (alt, alone) = alt_alone(*m); - tapped |= tap.modifiers(alt, alone); - } - egui::Event::Key { pressed: true, .. } - | egui::Event::PointerButton { .. } - | egui::Event::MouseWheel { .. } - | egui::Event::Touch { .. } => tap.other(), - _ => {} - } - } - let (alt, alone) = alt_alone(i.modifiers); - tapped | tap.modifiers(alt, alone) - }) -} - -#[cfg(test)] -mod tests { - use super::{AltTap, follow}; - - #[test] - fn a_press_and_release_alone_is_a_tap() { - let mut t = AltTap::default(); - assert!(!t.modifiers(true, true)); - assert!(!t.modifiers(true, true)); - assert!(t.modifiers(false, true)); - assert!(!t.modifiers(false, true), "once"); - } - - #[test] - fn anything_else_while_alt_is_down_is_no_tap() { - // A key (Alt+P), a click or a wheel turn while held. - let mut t = AltTap::default(); - t.modifiers(true, true); - t.other(); - assert!(!t.modifiers(false, true)); - // With Shift held too. - t.modifiers(true, false); - assert!(!t.modifiers(false, true)); - // Something before Alt went down does not count, and the next press starts afresh. - t.other(); - t.modifiers(true, true); - assert!(t.modifiers(false, true)); - } - - /// Alt down and up between two frames: both changes come in one frame's events, whose - /// modifiers at its end hold no Alt. - #[test] - fn a_tap_within_one_frame_counts() { - let ctx = egui::Context::default(); - let mut t = AltTap::default(); - let mut tapped = false; - let events = vec![egui::Event::ModifiersChanged(egui::Modifiers::ALT), egui::Event::ModifiersChanged(egui::Modifiers::NONE)]; - let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| tapped = follow(&mut t, ui.ctx(), true)); - out.textures_delta.clear(); - assert!(tapped); - assert_eq!(t, AltTap::default()); - } -} diff --git a/crates/ui-egui/src/shortcuts/held_tool.rs b/crates/ui-egui/src/shortcuts/held_tool.rs index 5d69422a05..c18c8b49ee 100644 --- a/crates/ui-egui/src/shortcuts/held_tool.rs +++ b/crates/ui-egui/src/shortcuts/held_tool.rs @@ -2,7 +2,9 @@ //! Temporarily, `holdToolKeys`): the tool it chose stays until the key is let go, and then the tool //! active before comes back. A quick press chooses the tool for good. -use super::{Key, VectorcraftApp}; +use craft_ui_contract::runtime::commands::{FirePhase, Fired}; + +use super::VectorcraftApp; /// A key let go this many seconds or more after its press returns to the tool active before it. /// VectorCraft's own value. @@ -10,31 +12,32 @@ pub(crate) const HOLD_SECONDS: f64 = 0.25; /// A tool shortcut's key held down since it chose its tool. pub(crate) struct HeldTool { - /// The key that chose the tool. - key: Key, + /// The tool command the key fires; its release names the hold. + command: String, /// The viewport that saw the press: other viewports do not see the key. viewport: egui::ViewportId, /// The tool the key chose. tool: &'static str, /// The tool to go back to. previous: &'static str, - /// When the key went down (`egui::InputState::time`). + /// When the key went down (the fired press's input time). since: f64, /// The tool took a drag, a click or a dialog while the key was down. used: bool, - /// When a frame first saw the key let go. The decision can come in a later frame (after a - /// drag, a dialog or a press of the same frame), and it uses this time. + /// When the key was let go. The decision can come in a later pass (after a drag, a dialog or a + /// press of the same pass), and it uses this time. released: Option, } -/// Chooses `tool` for a press of its single-key shortcut `key` (`None`: no key press typed it). A -/// press that changes the tool, with the preference on, starts a hold. A hold started while another -/// key is held goes on top of it: letting go of the later key returns to the earlier key's tool, -/// and letting go of the earlier key then returns to the tool before both. With the preference on, -/// a key's repeats choose nothing: a key held down chooses its tool once. With it off, each repeat -/// chooses the tool again. -pub(super) fn choose(app: &mut VectorcraftApp, ctx: &egui::Context, tool: &str, key: Option, repeat: bool) { - if repeat && app.session.prefs.hold_tool_keys { +/// Chooses the tool of a fired tool key. A press that changes the tool, with the preference on, starts +/// a hold. A hold started while another key is held goes on top of it: letting go of the later key +/// returns to the earlier key's tool, and letting go of the earlier key then returns to the tool before +/// both. With the preference on, a key's repeats choose nothing: a key held down chooses its tool once. +/// With it off, each repeat chooses the tool again. +pub(super) fn choose(app: &mut VectorcraftApp, ctx: &egui::Context, fired: &Fired) { + let Some(tool) = fired.command.id.strip_prefix("tool:") else { return }; + let hold = app.session.prefs.hold_tool_keys; + if fired.phase == FirePhase::Repeat && hold { return; } let previous = app.session.tool_id(); @@ -46,21 +49,26 @@ pub(super) fn choose(app: &mut VectorcraftApp, ctx: &egui::Context, tool: &str, if chosen == previous { return; } - let viewport = ctx.viewport_id(); - let (down, now) = key.map_or((false, 0.0), |k| ctx.input(|i| (i.key_down(k), i.time))); - match key { - // A key let go in the frame that pressed it was a quick press. - Some(key) if down && app.session.prefs.hold_tool_keys && chosen == tool => { - app.held_tool.retain(|h| h.viewport == viewport && h.key != key); - app.held_tool.push(HeldTool { key, viewport, tool: chosen, previous, since: now, used: false, released: None }); - } - _ => app.held_tool.clear(), + if hold && chosen == tool { + let viewport = ctx.viewport_id(); + app.held_tool.retain(|h| h.viewport == viewport && h.command != fired.command.id); + app.held_tool.push(HeldTool { + command: fired.command.id.clone(), + viewport, + tool: chosen, + previous, + since: fired.time, + used: false, + released: None, + }); + } else { + app.held_tool.clear(); } } /// A press that reaches the active tool, a drag of the Zoom, Hand or Rotate View tool, or the /// tool's dialog opened with Enter, uses the tool of the key held last when that tool is active, -/// also when that and the key's release come between two frames of [`follow`]. +/// also when that and the key's release come between two passes of [`follow`]. pub(crate) fn note_tool_use(app: &mut VectorcraftApp) { let active = app.session.tool_id(); if let Some(held) = app.held_tool.last_mut().filter(|h| h.tool == active) { @@ -68,32 +76,31 @@ pub(crate) fn note_tool_use(app: &mut VectorcraftApp) { } } -/// After the tool takes `key`: a dialog that Enter left open is the tool's, so it uses the tool. -pub(super) fn note_enter_dialog(app: &mut VectorcraftApp, key: Key) { - if key == Key::Enter && app.ui.dialog.is_some() { - note_tool_use(app); +/// The release of a tool key: times the hold it ended, then decides. A release that comes with the window +/// losing the keyboard goes to another window, so it ends every hold without going back. +pub(super) fn release(app: &mut VectorcraftApp, ctx: &egui::Context, fired: &Fired) { + if ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::WindowFocused(false)))) { + app.held_tool.clear(); + return; } + let viewport = ctx.viewport_id(); + for held in app.held_tool.iter_mut().filter(|h| h.viewport == viewport && h.released.is_none() && h.command == fired.command.id) { + held.released = Some(fired.time); + } + follow(app, ctx); } -/// Once per frame of the viewport that saw the press: when the key held last is let go, goes back -/// to the tool active before it, unless the press was quick and the tool was not used. A key let -/// go during a drag, with the button held or with a dialog open, goes back once that ends. Choosing -/// another tool, a quick press, turning the preference off or the window losing the keyboard ends -/// every hold without going back. A frame of another viewport that has the keyboard also ends them. -pub(super) fn follow(app: &mut VectorcraftApp, ctx: &egui::Context, focused: bool) { - // Every key let go is timed in the frame that first sees it up, under the key held last too. - let (viewport, time) = (ctx.viewport_id(), ctx.input(|i| i.time)); - for held in app.held_tool.iter_mut().filter(|h| h.viewport == viewport && h.released.is_none()) { - if !ctx.input(|i| i.key_down(held.key)) { - held.released = Some(time); - } - } - // Each pass looks at the key held last; one that goes back hands over to the key under it. +/// When the key held last is let go, goes back to the tool active before it, unless the press was +/// quick and the tool was not used. A key let go during a drag, with the button held or with a dialog +/// open, goes back once that ends. Choosing another tool or turning the preference off ends every +/// hold without going back. +pub(super) fn follow(app: &mut VectorcraftApp, ctx: &egui::Context) { + // Each step looks at the key held last; one that goes back hands over to the key under it. loop { let gesture = app.session.tool_busy() || app.session.pointer_held(); - // A dialog, an update dialog, or a canvas drag that does not reach the tool (a pan, zoom or - // turn of the view), defers the decision. - let dialog = app.ui.dialog.is_some() || crate::updates_ui::blocks_input(app) || crate::canvas::dragging(ctx); + // A dialog, or a canvas drag that does not reach the tool (a pan, zoom or turn of the view), + // defers the decision. + let dialog = app.any_dialog_open() || crate::canvas::tool_adapter::in_gesture(app, ctx); let active = app.session.tool_id(); let on = app.session.prefs.hold_tool_keys; let Some(held) = app.held_tool.last_mut() else { return }; @@ -102,39 +109,29 @@ pub(super) fn follow(app: &mut VectorcraftApp, ctx: &egui::Context, focused: boo return; } if held.viewport != ctx.viewport_id() { - // This viewport has the keyboard, so the viewport that saw the press lost it. - if focused { - app.held_tool.clear(); - } return; } - if !focused { - app.held_tool.clear(); - return; - } - let (down, now) = ctx.input(|i| (i.key_down(held.key), i.time)); if gesture || dialog { // A gesture of the held tool with the key down uses the tool; a gesture lent to a // selection tool does not. A dialog uses it only when Enter opened it, and a view drag // when it is the held tool's ([`note_tool_use`]). - held.used |= gesture && down && active == held.tool; + held.used |= gesture && held.released.is_none() && active == held.tool; return; } if active != held.tool { app.held_tool.clear(); return; } - if down { - return; - } - // The canvas takes a pointer press of the same frame, and the tool an Enter press, after - // this: the decision waits for the next frame, measured from this one. - let pressed = ctx.input(|i| { - i.events + let Some(released) = held.released else { return }; + // The canvas takes a pointer press of the same pass, and the tool an Enter press, after + // this: the decision waits for the next pass, measured from this one. + let (pressed, now) = ctx.input(|i| { + let pressed = i + .events .iter() - .any(|e| matches!(e, egui::Event::PointerButton { pressed: true, .. } | egui::Event::Key { key: Key::Enter, pressed: true, .. })) + .any(|e| matches!(e, egui::Event::PointerButton { pressed: true, .. } | egui::Event::Key { key: egui::Key::Enter, pressed: true, .. })); + (pressed, i.time) }); - let released = held.released.unwrap_or(now); if pressed && released == now { ctx.request_repaint(); return; diff --git a/crates/ui-egui/src/shortcuts/held_tool/tests.rs b/crates/ui-egui/src/shortcuts/held_tool/tests.rs index c272024adb..a370ff1ea6 100644 --- a/crates/ui-egui/src/shortcuts/held_tool/tests.rs +++ b/crates/ui-egui/src/shortcuts/held_tool/tests.rs @@ -1,11 +1,12 @@ +use egui::Key; use serde_json::json; use vectorcraft_tools::{PointerEvent, PointerKind}; -use super::super::handle; use super::*; /// A keyboard on one context, so egui keeps the keys held down from frame to frame and marks a -/// held key's later presses as repeats, with the frame times the test sets. +/// held key's later presses as repeats, with the frame times the test sets. A frame runs the app's own +/// `logic` and `ui`. struct Keyboard { ctx: egui::Context, } @@ -15,32 +16,17 @@ impl Keyboard { Self { ctx: egui::Context::default() } } - /// One frame at `time` seconds delivering `events`; with `field`, a text field that takes the - /// keyboard is drawn after the shortcuts. - fn frame(&self, app: &mut VectorcraftApp, time: f64, events: Vec, field: Option<&mut String>) { - self.frame_with_focus(app, time, events, field, true); + /// One frame at `time` seconds delivering `events`. + fn frame(&self, app: &mut VectorcraftApp, time: f64, events: Vec) { + self.frame_with_focus(app, time, events, true); } /// [`Self::frame`], with the window having the keyboard (`focused`) or not. - fn frame_with_focus(&self, app: &mut VectorcraftApp, time: f64, events: Vec, mut field: Option<&mut String>, focused: bool) { + fn frame_with_focus(&self, app: &mut VectorcraftApp, time: f64, events: Vec, focused: bool) { let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); let mut out = self.ctx.run_ui(egui::RawInput { events, screen_rect, time: Some(time), focused, ..Default::default() }, |ui| { app.logic(ui.ctx()); - handle(app, ui.ctx()); - if let Some(text) = field.as_deref_mut() { - ui.add(egui::TextEdit::singleline(text).id(egui::Id::unique("held-tool-field"))).request_focus(); - } - }); - out.textures_delta.clear(); - } - - /// One frame at `time` seconds delivering `events`, with the canvas drawn after the shortcuts. - fn on_canvas(&self, app: &mut VectorcraftApp, time: f64, events: Vec) { - let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); - let mut out = self.ctx.run_ui(egui::RawInput { events, screen_rect, time: Some(time), focused: true, ..Default::default() }, |ui| { - app.logic(ui.ctx()); - handle(app, ui.ctx()); - crate::canvas::show(app, ui); + app.ui(ui); }); out.textures_delta.clear(); } @@ -48,12 +34,12 @@ impl Keyboard { /// `key` pressed (or repeated while it is down) at `time`, typing `letter`. fn press(&self, app: &mut VectorcraftApp, time: f64, key: Key, letter: &str) { let press = egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - self.frame(app, time, vec![press, egui::Event::Text(letter.into())], None); + self.frame(app, time, vec![press, egui::Event::Text(letter.into())]); } fn release(&self, app: &mut VectorcraftApp, time: f64, key: Key) { let release = egui::Event::Key { key, physical_key: Some(key), pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }; - self.frame(app, time, vec![release], None); + self.frame(app, time, vec![release]); } fn press_s(&self, app: &mut VectorcraftApp, time: f64) { @@ -86,7 +72,7 @@ fn a_tool_key_let_go_behind_the_update_prompt_returns_after_it() { keys.release_s(&mut app, 1.0); assert_eq!(app.session.tool_id(), "scale", "Scale stays behind the prompt"); crate::updates_ui::close_dialogs_for_test(&mut app); - keys.frame(&mut app, 1.1, vec![], None); + keys.frame(&mut app, 1.1, vec![]); assert_eq!(app.session.tool_id(), "pen", "the Pen is back after the prompt"); } @@ -108,23 +94,11 @@ fn a_quick_press_of_a_tool_key_chooses_the_tool_for_good() { let keys = Keyboard::new(); hold_s(&mut app, &keys, &[], HOLD_SECONDS / 2.0); assert_eq!(app.session.tool_id(), "scale"); - keys.frame(&mut app, 5.0, vec![], None); + keys.frame(&mut app, 5.0, vec![]); assert_eq!(app.session.tool_id(), "scale", "Scale stays chosen"); assert!(app.held_tool.is_empty()); } -/// A press and release of S in one frame is a quick press, also when the next frame comes long -/// after it. -#[test] -fn a_press_and_release_in_one_frame_chooses_the_tool_for_good() { - let mut app = pen_app(); - let keys = Keyboard::new(); - let key = |pressed| egui::Event::Key { key: Key::S, physical_key: Some(Key::S), pressed, repeat: false, modifiers: egui::Modifiers::NONE }; - keys.frame(&mut app, 0.0, vec![key(true), egui::Event::Text("s".into()), key(false)], None); - keys.frame(&mut app, 5.0, vec![], None); - assert_eq!(app.session.tool_id(), "scale"); -} - /// S held past the threshold, with its key repeats, and let go returns to the Pen. #[test] fn a_held_tool_key_returns_to_the_previous_tool_when_let_go() { @@ -163,13 +137,13 @@ fn a_tool_key_let_go_during_a_drag_returns_after_the_drag() { app.session.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 150.0), view).unwrap(); app.session.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 190.0), view).unwrap(); assert!(app.session.tool_busy(), "Scale is dragging"); - keys.frame(&mut app, release / 2.0, vec![], None); + keys.frame(&mut app, release / 2.0, vec![]); keys.release_s(&mut app, release); assert_eq!(app.session.tool_id(), "scale", "let go at {release} s: Scale stays during the drag"); - keys.frame(&mut app, release + 0.1, vec![], None); + keys.frame(&mut app, release + 0.1, vec![]); assert_eq!(app.session.tool_id(), "scale", "let go at {release} s: still dragging"); app.session.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 190.0), view).unwrap(); - keys.frame(&mut app, release + 0.2, vec![], None); + keys.frame(&mut app, release + 0.2, vec![]); assert_eq!(app.session.tool_id(), "pen", "let go at {release} s: the Pen is back after the drag"); } } @@ -204,7 +178,7 @@ fn a_click_lent_to_a_selection_tool_does_not_use_the_held_tool() { let event = |kind| PointerEvent { mods, ..PointerEvent::new(kind, 150.0, 125.0) }; crate::canvas::dispatch(&mut app, &event(PointerKind::Down), view); if frame_during_click { - keys.frame(&mut app, HOLD_SECONDS / 4.0, vec![], None); + keys.frame(&mut app, HOLD_SECONDS / 4.0, vec![]); } crate::canvas::dispatch(&mut app, &event(PointerKind::Up), view); keys.release_s(&mut app, HOLD_SECONDS / 2.0); @@ -220,26 +194,26 @@ fn a_view_tool_drag_counts_as_using_the_held_tool() { for let_go_during_pan in [false, true] { let mut app = pen_app(); let keys = Keyboard::new(); - keys.on_canvas(&mut app, 0.0, vec![]); + keys.frame(&mut app, 0.0, vec![]); let at = app.canvas_rect.expect("the canvas was drawn").center(); let to = at + egui::vec2(30.0, 20.0); let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; let key = |pressed| egui::Event::Key { key: Key::H, physical_key: Some(Key::H), pressed, repeat: false, modifiers: egui::Modifiers::NONE }; - keys.on_canvas(&mut app, 0.01, vec![egui::Event::PointerMoved(at), key(true), egui::Event::Text("h".into())]); + keys.frame(&mut app, 0.01, vec![egui::Event::PointerMoved(at), key(true), egui::Event::Text("h".into())]); assert_eq!(app.session.tool_id(), "hand", "let go during the pan: {let_go_during_pan}"); - keys.on_canvas(&mut app, 0.02, vec![button(at, true)]); - keys.on_canvas(&mut app, 0.03, vec![egui::Event::PointerMoved(to)]); - assert!(crate::canvas::dragging(&keys.ctx), "the Hand pans"); + keys.frame(&mut app, 0.02, vec![button(at, true)]); + keys.frame(&mut app, 0.03, vec![egui::Event::PointerMoved(to)]); + assert!(crate::canvas::tool_adapter::in_gesture(&app, &keys.ctx), "the Hand pans"); if let_go_during_pan { - keys.on_canvas(&mut app, 0.05, vec![key(false)]); + keys.frame(&mut app, 0.05, vec![key(false)]); assert_eq!(app.session.tool_id(), "hand", "the Hand stays during the pan"); - keys.on_canvas(&mut app, 0.06, vec![button(to, false)]); + keys.frame(&mut app, 0.06, vec![button(to, false)]); } else { - keys.on_canvas(&mut app, 0.05, vec![button(to, false)]); - keys.on_canvas(&mut app, 0.06, vec![key(false)]); + keys.frame(&mut app, 0.05, vec![button(to, false)]); + keys.frame(&mut app, 0.06, vec![key(false)]); } - keys.on_canvas(&mut app, 0.07, vec![]); + keys.frame(&mut app, 0.07, vec![]); assert_eq!(app.session.tool_id(), "pen", "let go during the pan: {let_go_during_pan}"); assert!(app.held_tool.is_empty()); } @@ -257,7 +231,7 @@ fn a_press_in_the_frame_that_lets_go_waits_for_the_canvas() { let at = egui::pos2(150.0, 125.0); let press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; let release = egui::Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }; - keys.frame(&mut app, 0.1, vec![egui::Event::PointerMoved(at), press, release], None); + keys.frame(&mut app, 0.1, vec![egui::Event::PointerMoved(at), press, release]); assert_eq!(app.session.tool_id(), "scale", "canvas {canvas}: no decision before the canvas"); if canvas { let view = app.view_info(); @@ -265,33 +239,11 @@ fn a_press_in_the_frame_that_lets_go_waits_for_the_canvas() { crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, 150.0, 125.0), view); } } - keys.frame(&mut app, 2.0, vec![], None); + keys.frame(&mut app, 2.0, vec![]); assert_eq!(app.session.tool_id(), if canvas { "pen" } else { "scale" }, "canvas {canvas}"); } } -/// S and then V pressed quickly, both let go in the frame of a canvas click with the Selection tool: -/// V was used, so Scale comes back, and S was a quick press, so Scale stays, also when the next -/// frame comes late. -#[test] -fn keys_let_go_together_are_timed_in_the_frame_that_lets_them_go() { - let mut app = pen_app(); - let keys = Keyboard::new(); - keys.press_s(&mut app, 0.0); - keys.press(&mut app, 0.02, Key::V, "v"); - let at = egui::pos2(150.0, 125.0); - let up = |key| egui::Event::Key { key, physical_key: Some(key), pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }; - let press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; - keys.frame(&mut app, 0.05, vec![egui::Event::PointerMoved(at), press, up(Key::V), up(Key::S)], None); - let view = app.view_info(); - for kind in [PointerKind::Down, PointerKind::Up] { - crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, 150.0, 125.0), view); - } - keys.frame(&mut app, 2.0, vec![], None); - assert_eq!(app.session.tool_id(), "scale"); - assert!(app.held_tool.is_empty()); -} - /// With S held and then V held, a click with the Selection tool uses Selection only: V let go /// quickly returns to Scale, and S let go quickly then keeps Scale. #[test] @@ -320,66 +272,32 @@ fn a_dialog_opened_during_the_hold_counts_as_using_the_tool() { keys.press(&mut app, 0.0, key, letter); let enter = egui::Event::Key { key: Key::Enter, physical_key: Some(Key::Enter), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - keys.frame(&mut app, 0.05, vec![enter], None); + keys.frame(&mut app, 0.05, vec![enter]); assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialog), "Enter opens the {dialog} dialog"); keys.release(&mut app, 0.1, key); assert_eq!(app.session.tool_id(), tool, "{tool} stays while its dialog is open"); crate::dialogs::cancel(&mut app); - keys.frame(&mut app, 0.15, vec![], None); + keys.frame(&mut app, 0.15, vec![]); assert_eq!(app.session.tool_id(), "pen", "after the {dialog} dialog"); } } -/// Enter pressed in the frame that lets go of S after the threshold opens the Scale dialog, and -/// Scale stays until the dialog closes. -#[test] -fn enter_in_the_frame_that_lets_go_reaches_the_held_tool() { - let mut app = pen_app(); - let keys = Keyboard::new(); - keys.press_s(&mut app, 0.0); - let enter = egui::Event::Key { key: Key::Enter, physical_key: Some(Key::Enter), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - let release = egui::Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }; - keys.frame(&mut app, 1.0, vec![release, enter], None); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("scale"), "Enter opens the Scale dialog"); - keys.frame(&mut app, 1.1, vec![], None); - assert_eq!(app.session.tool_id(), "scale", "Scale stays while its dialog is open"); - crate::dialogs::cancel(&mut app); - keys.frame(&mut app, 1.2, vec![], None); - assert_eq!(app.session.tool_id(), "pen"); -} - -/// Another dialog (Preferences) opened while S is down and S let go quickly while it is open: Scale +/// Another dialog (New Document) opened while S is down and S let go quickly while it is open: Scale /// was not used, so it stays once the dialog closes. #[test] fn another_dialog_opened_during_the_hold_does_not_use_the_tool() { let mut app = pen_app(); let keys = Keyboard::new(); keys.press_s(&mut app, 0.0); - crate::prefs_dialog::open(&mut app, None); - keys.frame(&mut app, 0.05, vec![], None); + // PLAN: Preferences is its own viewport and `any_dialog_open()` does not count it; New Document is a dialog of the host. + app.run("file.newDialog", json!({})).unwrap(); + keys.frame(&mut app, 0.05, vec![]); keys.release_s(&mut app, 0.1); crate::dialogs::cancel(&mut app); - keys.frame(&mut app, 0.15, vec![], None); + keys.frame(&mut app, 0.15, vec![]); assert_eq!(app.session.tool_id(), "scale"); } -/// S typed and held in a text field types its letter and chooses no tool. -#[test] -fn a_tool_key_held_in_a_text_field_types_and_keeps_the_tool() { - let mut app = pen_app(); - let keys = Keyboard::new(); - let mut text = String::new(); - keys.frame(&mut app, 0.0, vec![], Some(&mut text)); - let press = egui::Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - let release = egui::Event::Key { key: Key::S, physical_key: Some(Key::S), pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }; - keys.frame(&mut app, 0.1, vec![press.clone(), egui::Event::Text("s".into())], Some(&mut text)); - keys.frame(&mut app, 0.6, vec![press, egui::Event::Text("s".into())], Some(&mut text)); - keys.frame(&mut app, 1.0, vec![release], Some(&mut text)); - assert_eq!(text, "ss"); - assert_eq!(app.session.tool_id(), "pen"); - assert!(app.held_tool.is_empty()); -} - /// With General › Hold a Tool Shortcut to Use the Tool Temporarily off, a held S chooses Scale for /// good, as a quick press does. #[test] @@ -405,28 +323,6 @@ fn with_the_preference_off_each_repeat_chooses_the_tool_again() { assert_eq!(app.session.tool_id(), "scale"); } -/// A hold whose viewport stopped drawing ends when another viewport has the keyboard or the -/// preference is turned off, and stays while the other viewport does not have the keyboard. -#[test] -fn a_hold_of_another_viewport_ends_when_this_one_has_the_keyboard() { - let other = egui::ViewportId::from_hash_of("held-tool-other"); - let hold = || HeldTool { key: Key::S, viewport: other, tool: "scale", previous: "pen", since: 0.0, used: false, released: None }; - let mut app = pen_app(); - app.select_tool("scale"); - let keys = Keyboard::new(); - app.held_tool.push(hold()); - keys.frame_with_focus(&mut app, 0.5, vec![], None, false); - assert_eq!(app.held_tool.len(), 1, "a viewport without the keyboard leaves the hold alone"); - keys.frame(&mut app, 1.0, vec![], None); - assert!(app.held_tool.is_empty(), "a viewport with the keyboard ends the hold"); - assert_eq!(app.session.tool_id(), "scale"); - app.held_tool.push(hold()); - app.run("prefs.set", json!({"key": "holdToolKeys", "value": false})).unwrap(); - keys.frame_with_focus(&mut app, 1.5, vec![], None, false); - assert!(app.held_tool.is_empty(), "turning the preference off ends the hold"); - assert_eq!(app.session.tool_id(), "scale"); -} - /// Scale chosen again on the toolbar while S is held stays chosen when S is let go. #[test] fn the_held_tool_chosen_again_stays_when_the_key_is_let_go() { @@ -454,11 +350,11 @@ fn losing_the_keyboard_ends_the_hold() { app.session.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 150.0), view).unwrap(); app.session.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 190.0), view).unwrap(); } - keys.frame_with_focus(&mut app, 0.3, vec![egui::Event::WindowFocused(false)], None, false); + keys.frame_with_focus(&mut app, 0.3, vec![egui::Event::WindowFocused(false)], false); if drag { app.session.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 190.0), view).unwrap(); } - keys.frame(&mut app, 0.5, vec![egui::Event::WindowFocused(true)], None); + keys.frame(&mut app, 0.5, vec![egui::Event::WindowFocused(true)]); keys.release_s(&mut app, 0.6); assert_eq!(app.session.tool_id(), "scale", "drag {drag}: Scale stays"); } @@ -471,7 +367,7 @@ fn a_tool_chosen_during_the_hold_stays_when_the_key_is_let_go() { let keys = Keyboard::new(); keys.press_s(&mut app, 0.0); app.select_tool("rectangle"); - keys.frame(&mut app, 0.3, vec![], None); + keys.frame(&mut app, 0.3, vec![]); keys.release_s(&mut app, 0.5); assert_eq!(app.session.tool_id(), "rectangle"); } diff --git a/crates/ui-egui/src/shortcuts/hold_keys.rs b/crates/ui-egui/src/shortcuts/hold_keys.rs deleted file mode 100644 index e5cbdc15e1..0000000000 --- a/crates/ui-egui/src/shortcuts/hold_keys.rs +++ /dev/null @@ -1,426 +0,0 @@ -//! Hold shortcuts (Edit › Keyboard Shortcuts, Hold Shortcuts on, the Hold column): a character key -//! with a hold shortcut waits when it goes down. Held for the Hold Shortcut Delay (`keyHoldDelay`), -//! it runs its hold shortcut once, and its repeats are ignored until it is let go. Let go sooner, it -//! runs what a press of the key runs without a hold shortcut, at the release. A key without a hold -//! shortcut runs on its press, as before, and so does every key while Hold Shortcuts is off. - -use super::{Key, Modifiers, VectorcraftApp}; -use vectorcraft_tools::ToolKey; - -/// A press of a key with a hold shortcut, waiting for its release or for the delay to pass. -pub(crate) struct Pending { - /// The entry the hold shortcut runs (`tool:`, a command id or `panel:`). - entry: String, - /// The chords the press names, first match first, for the tap. - chords: Vec, - /// The key as egui reported the press, before any rewrite of the dispatcher. - key: Key, - /// The key's position, when the press gave one. - physical: Option, - /// The modifiers held at the press. - mods: Modifiers, - /// When the key went down (`egui::InputState::time`). - since: f64, - /// The Hold Shortcut Delay read at the press: a later change does not move this wait. - delay: f64, - /// The viewport whose frame saw the press. Frames of other viewports leave the wait alone. - viewport: egui::ViewportId, -} - -/// A key whose repeats, and the text they type, are dropped until it is let go. -#[derive(Clone, Copy, PartialEq)] -struct Swallowed { - key: Key, - physical: Option, - viewport: egui::ViewportId, -} - -/// The hold shortcut state of the app: at most one waiting press, and the keys held down after -/// their wait ended. -#[derive(Default)] -pub(crate) struct HoldKeys { - pending: Option, - swallowed: Vec, -} - -/// Is `e` the release of the key `key` at `physical`? The position decides when both events give -/// one; otherwise the key decides. -fn releases(e: &egui::Event, key: Key, physical: Option) -> bool { - matches!(e, egui::Event::Key { key: k, physical_key: p, pressed: false, .. } if same_key(*k, *p, key, physical)) -} - -fn same_key(k: Key, p: Option, key: Key, physical: Option) -> bool { - match (p, physical) { - (Some(p), Some(q)) => p == q, - _ => k == key || Some(k) == physical, - } -} - -/// Is the key still down? egui keeps the keys down by the key it reported for the press. -fn is_down(i: &egui::InputState, key: Key, physical: Option) -> bool { - i.key_down(key) || physical.is_some_and(|p| i.key_down(p)) -} - -/// What stops a wait: anything that takes the keyboard from the canvas. -fn blocked(app: &VectorcraftApp, ctx: &egui::Context) -> bool { - crate::scrub::phase(ctx) != crate::scrub::Phase::Idle - || crate::updates_ui::blocks_input(app) - || app.ui.dialog.is_some() - || app.ui.palette_open - || app.ui.screen_mode == 3 - || ctx.egui_wants_keyboard_input() - || app.session.tool_wants_text() - || app.session.tool_composing() - || app.session.tool_busy() - // An input method composing on the canvas with any tool. - || ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) if !text.is_empty()))) -} - -/// Every frame, before anything can return: drops the repeats of the keys held after their wait -/// ended or while it waits, and the text they type, also on frames that run no shortcut. Ends the -/// wait without running anything when the window lost the keyboard, or when a field, a dialog, -/// Presentation Mode, a numeric scrub, an IME composition or a busy tool has it. -pub(super) fn guard(app: &mut VectorcraftApp, ctx: &egui::Context, focused: bool) { - let viewport = ctx.viewport_id(); - if !focused { - // egui lets go of every key when the window loses the keyboard. - if app.hold_keys.pending.as_ref().is_some_and(|p| p.viewport == viewport) { - app.hold_keys.pending = None; - } - app.hold_keys.swallowed.retain(|s| s.viewport != viewport); - return; - } - let mut held: Vec<(Key, Option)> = app.hold_keys.swallowed.iter().filter(|s| s.viewport == viewport).map(|s| (s.key, s.physical)).collect(); - held.extend(app.hold_keys.pending.as_ref().filter(|p| p.viewport == viewport).map(|p| (p.key, p.physical))); - // A wait that ends here still drops this frame's repeats of its key, also when the frame lets - // the key go. - if app.hold_keys.pending.as_ref().is_some_and(|p| p.viewport == viewport) && (blocked(app, ctx) || !app.session.prefs.hold_shortcuts) { - cancel(app, ctx); - } - if held.is_empty() { - return; - } - drop_repeats(ctx, &held); - // A key let go, or pressed anew, is no longer held back after this frame: a repeat that came - // in the same frame as its release was dropped above. - ctx.input(|i| { - app.hold_keys.swallowed.retain(|s| { - s.viewport != viewport - || is_down(i, s.key, s.physical) - && !i.events.iter().any(|e| { - releases(e, s.key, s.physical) - || matches!(e, egui::Event::Key { key, physical_key, pressed: true, repeat: false, .. } if same_key(*key, *physical_key, s.key, s.physical)) - }) - }); - }); -} - -/// Removes this frame's repeats of the keys `held`, and the text they type. -fn drop_repeats(ctx: &egui::Context, held: &[(Key, Option)]) { - let repeat = |e: Option<&egui::Event>| { - matches!(e, Some(egui::Event::Key { key, physical_key, pressed: true, repeat: true, .. }) - if held.iter().any(|(k, p)| same_key(*key, *physical_key, *k, *p))) - }; - ctx.input_mut(|i| { - let typed_by = super::typing_presses(&i.events); - let drop: Vec = i - .events - .iter() - .zip(typed_by) - .map(|(e, by)| repeat(Some(e)) || matches!(e, egui::Event::Text(_)) && repeat(by.and_then(|k| i.events.get(k)))) - .collect(); - let mut drop = drop.into_iter(); - i.events.retain(|_| !drop.next().unwrap_or(false)); - }); -} - -/// Ends the wait without running anything; the key's repeats stay held back until it is let go. -fn cancel(app: &mut VectorcraftApp, ctx: &egui::Context) { - let Some(p) = app.hold_keys.pending.take() else { return }; - if ctx.input(|i| is_down(i, p.key, p.physical)) { - app.hold_keys.swallowed.push(Swallowed { key: p.key, physical: p.physical, viewport: p.viewport }); - } -} - -/// Runs the result of the wait: the hold shortcut when `hold`, otherwise the tap. `down`: the key -/// is still down, so its repeats are held back until it is let go. True when the result opened a -/// dialog or the palette. -fn settle(app: &mut VectorcraftApp, ctx: &egui::Context, hold: bool, down: bool) -> bool { - let Some(p) = app.hold_keys.pending.take() else { return false }; - if down { - app.hold_keys.swallowed.push(Swallowed { key: p.key, physical: p.physical, viewport: p.viewport }); - } - if hold { - super::run_hit(app, ctx, &crate::keymap::command_of(&p.entry)); - } else { - // The key is already up, or another key went down: a tool it chooses is chosen for good. - super::run_single_key(app, ctx, &p.chords, None, false); - } - let opened = super::dialog_or_palette_open(app); - if opened && down { - // The key's repeats do not reach the dialog. - let id = super::opening_key_id(ctx); - ctx.data_mut(|m| m.insert_temp(id, p.key)); - } - opened -} - -/// The chords a press names for a hold shortcut, first match first: the key itself with its Shift -/// (Shift+1 typing `!`), then those of the text it typed, as a single-key shortcut reads them. When -/// one entry holds Shift+1 and another `!`, Shift+1 runs the first. A letter names only the chord -/// with its own Shift state: a hold on X does not catch Shift+X. -fn press_chords(text: &str, key: Key, m: Modifiers) -> Vec { - let mut chords = super::text_chords(text, m, Some(key)); - if !text.is_empty() && text.chars().all(char::is_alphabetic) { - chords.retain(|c| c.mods.shift == m.shift); - } - let shift = Modifiers { shift: m.shift, ..Modifiers::NONE }; - if let Some(c) = crate::shortcut_editor::chord_from_event(key, shift).and_then(|t| crate::keymap::vc_chord(&t)) { - chords.retain(|t| *t != c); - chords.insert(0, c); - } - chords -} - -/// The chords a quick press runs, as the key runs without a hold shortcut: a shortcut on a shifted -/// punctuation key itself (Shift+.), which the shortcuts read from the key press, then those of -/// the text it typed. -fn tap_chords(text: &str, key: Key, m: Modifiers) -> Vec { - let shift = Modifiers { shift: m.shift, ..Modifiers::NONE }; - let pressed = crate::shortcut_editor::chord_from_event(key, shift) - .and_then(|t| crate::keymap::vc_chord(&t)) - .filter(|c| c.mods.shift && c.key.name().chars().all(|ch| !ch.is_alphanumeric())); - let mut chords: Vec = super::text_chords(text, m, Some(key)).into_iter().filter(|c| pressed.as_ref() != Some(c)).collect(); - if let Some(c) = pressed { - chords.insert(0, c); - } - chords -} - -/// Does the active tool take this key itself (a digit with the perspective grid showing, a bracket -/// with the Blob Brush, E with the Extend Path tool)? Then the key keeps doing that and does not -/// wait. -fn tool_takes(app: &mut VectorcraftApp, key: Key, text: &str) -> bool { - let view = app.view_info(); - let tool_key = match text { - "[" | "{" => Some(ToolKey::BracketLeft), - "]" | "}" => Some(ToolKey::BracketRight), - _ => super::digit_of(key).map(ToolKey::Digit).or_else(|| super::letter_of(key).map(ToolKey::Letter)), - }; - tool_key.is_some_and(|k| app.session.tool_claims_key(k, view)) -} - -/// Is there a press before the event at `start` that no wait took and that the frame handles: one -/// with Cmd, Ctrl or Alt, or one that typed a text of a key the active tool takes ([`tool_takes`])? -fn chord_before(app: &mut VectorcraftApp, events: &[egui::Event], typed_by: &[Option], start: usize, taken: &[usize]) -> bool { - let mut before = events.iter().enumerate().take(start).filter(|(k, _)| !taken.contains(k)); - before.any(|(k, e)| match e { - egui::Event::Key { key, pressed: true, modifiers: m, .. } if !super::is_modifier(*key) => { - m.command - || m.ctrl - || m.alt - || m.mac_cmd - || typed_by - .iter() - .enumerate() - .any(|(t, by)| *by == Some(k) && matches!(events.get(t), Some(egui::Event::Text(text)) if tool_takes(app, *key, text))) - } - _ => false, - }) -} - -/// 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. When one opened a dialog or the palette, the position of its first event -/// in the frame: its press, or its text where the text came first (the web build). -fn run_typed_before( - app: &mut VectorcraftApp, - ctx: &egui::Context, - events: &[egui::Event], - typed_by: &[Option], - start: usize, - taken: &mut Vec, -) -> Option { - 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 Some(by.map_or(k, |b| b.min(k))); - } - } - None -} - -/// 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, 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; after a chord with Cmd, Ctrl -/// or Alt, or a key the active tool takes, before its key, the key goes back to the frame instead -/// ([`chord_before`]). 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) { - return false; - } - let viewport = ctx.viewport_id(); - let (events, now) = ctx.input(|i| (i.events.clone(), i.time)); - let typed_by = super::typing_presses(&events); - 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, and how many events were taken before it: - // when the wait also ends in this frame, the keys typed before it run first. - let mut started: Option<(usize, usize)> = 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; - let ended = if releases(e, p.key, p.physical) { - Some((overdue, false)) - } else { - match e { - egui::Event::Key { key, physical_key, pressed: true, .. } - if !super::is_modifier(*key) && !same_key(*key, *physical_key, p.key, p.physical) => - { - Some((overdue, true)) - } - // A new press of the waiting key whose release was never seen. - egui::Event::Key { key, physical_key, pressed: true, repeat: false, .. } if same_key(*key, *physical_key, p.key, p.physical) => { - Some((false, false)) - } - egui::Event::ModifiersChanged(m) if (m.command, m.ctrl, m.alt) != (p.mods.command, p.mods.ctrl, p.mods.alt) => { - Some((false, true)) - } - _ => None, - } - }; - if let Some((hold, down)) = ended { - let start = started.take(); - // After a chord with Cmd, Ctrl or Alt pressed before it, which the frame's shortcuts - // run, or a key the active tool takes, the key goes back to the frame without - // waiting, so the frame handles it as it does with Hold Shortcuts off and its tap - // does not run before that key. Its press, its repeats and their texts stay in the - // frame, and its later repeats reach later frames. - if let Some((start, before)) = start - && chord_before(app, &events, &typed_by, start, &taken) - { - app.hold_keys.pending = None; - taken.truncate(before); - } else if let Some((start, _)) = start - && let Some(opened) = run_typed_before(app, ctx, &events, &typed_by, start, &mut taken) - { - // A key typed before it that opened a dialog or the palette ends the wait - // without running it. - cancel(app, ctx); - stop_at = Some(opened); - break; - } else 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 }; - if m.command || m.ctrl || m.alt || m.mac_cmd || super::is_modifier(*key) { - continue; - } - // Only a press that typed a text waits: a text alone has no key to let go. - let Some((t, egui::Event::Text(text))) = text_of(j) else { continue }; - let typed = super::latin(text, *physical_key); - let Some(entry) = - press_chords(&typed, *key, *m).iter().find_map(|c| crate::shortcut_editor::hold_for(&app.ui.shortcut_holds, c)).map(str::to_string) - else { - continue; - }; - let chords = tap_chords(&typed, *key, *m); - if tool_takes(app, *key, text) { - continue; - } - started = Some((j, taken.len())); - 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) { - app.hold_keys.swallowed.push(Swallowed { key: old.key, physical: old.physical, viewport: old.viewport }); - } - let delay = app.session.prefs.key_hold_delay(); - app.hold_keys.pending = Some(Pending { entry, chords, key: *key, physical: *physical_key, mods: *m, since: now, delay, viewport }); - } - // Take the waiting presses and their texts, and after a result that opened a dialog, the key - // event that ended the wait (or the typed key that opened the dialog, when that came earlier) - // and every later key event and text of the frame, with the text a - // press typed before it (the web build sends a press's text first): none of them reaches the - // dialog. - ctx.input_mut(|i| { - if i.events.len() != events.len() { - return; - } - let mut j = 0; - i.events.retain(|e| { - let k = j; - j += 1; - let later = stop_at.is_some_and(|s| { - k >= s && matches!(e, egui::Event::Key { .. } | egui::Event::Text(_)) - || matches!(e, egui::Event::Text(_)) && typed_by.get(k).copied().flatten().is_some_and(|by| by >= s) - }); - !(taken.contains(&k) || later) - }); - }); - if stop_at.is_some() { - return true; - } - let Some(p) = app.hold_keys.pending.as_ref().filter(|p| p.viewport == viewport) else { return false }; - let deadline = p.since + p.delay; - let down = ctx.input(|i| is_down(i, p.key, p.physical)); - if !down { - // Let go without a release this frame saw. - return settle(app, ctx, now >= deadline, false); - } - if now >= deadline { - return settle(app, ctx, true, true); - } - // egui draws only on input, and a held key need not repeat: draw again at the deadline. - ctx.request_repaint_after_secs((deadline - now) as f32); - false -} - -#[cfg(test)] -mod tests; diff --git a/crates/ui-egui/src/shortcuts/hold_keys/tests.rs b/crates/ui-egui/src/shortcuts/hold_keys/tests.rs deleted file mode 100644 index 6afc2a0002..0000000000 --- a/crates/ui-egui/src/shortcuts/hold_keys/tests.rs +++ /dev/null @@ -1,757 +0,0 @@ -use serde_json::json; - -use super::super::handle; -use super::*; - -/// A keyboard on one context, so egui keeps the keys held down from frame to frame and marks a -/// held key's later presses as repeats, with the frame times the test sets. -struct Keyboard { - ctx: egui::Context, -} - -impl Keyboard { - fn new() -> Self { - Self { ctx: egui::Context::default() } - } - - /// One frame at `time` seconds delivering `events`, with the window having the keyboard - /// (`focused`) or not. - fn frame_with_focus(&self, app: &mut VectorcraftApp, time: f64, events: Vec, focused: bool) { - let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); - let mut out = self.ctx.run_ui(egui::RawInput { events, screen_rect, time: Some(time), focused, ..Default::default() }, |ui| { - app.logic(ui.ctx()); - handle(app, ui.ctx()); - }); - out.textures_delta.clear(); - } - - fn frame(&self, app: &mut VectorcraftApp, time: f64, events: Vec) { - self.frame_with_focus(app, time, events, true); - } - - /// [`Self::frame`], giving the events the shortcuts left in the first pass for what is drawn - /// after them. - fn frame_left(&self, app: &mut VectorcraftApp, time: f64, events: Vec) -> Vec { - let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); - let mut left = None; - let mut out = self.ctx.run_ui(egui::RawInput { events, screen_rect, time: Some(time), focused: true, ..Default::default() }, |ui| { - app.logic(ui.ctx()); - handle(app, ui.ctx()); - if left.is_none() { - left = Some(ui.ctx().input(|i| i.events.clone())); - } - }); - out.textures_delta.clear(); - left.unwrap_or_default() - } - - /// `key` pressed (a repeat when it is already down) at `time`, typing `text`. - fn press(&self, app: &mut VectorcraftApp, time: f64, key: Key, text: &str) { - self.frame(app, time, press(key, text, Modifiers::NONE)); - } - - fn release(&self, app: &mut VectorcraftApp, time: f64, key: Key) { - self.frame(app, time, vec![release(key)]); - } -} - -fn press(key: Key, text: &str, modifiers: Modifiers) -> Vec { - vec![egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers }, egui::Event::Text(text.into())] -} - -fn release(key: Key) -> egui::Event { - egui::Event::Key { key, physical_key: Some(key), pressed: false, repeat: false, modifiers: Modifiers::NONE } -} - -/// A document with a selected rectangle filled red with a blue stroke, the Pen tool chosen, and -/// Hold Shortcuts `on`. -fn app_with(on: bool) -> VectorcraftApp { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - crate::shortcut_editor::sync(&app.ui); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap(); - app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); - app.run("paint.setStroke", json!({"color": "#0000ff"})).unwrap(); - app.run("prefs.set", json!({"key": "holdShortcuts", "value": on})).unwrap(); - app.select_tool("pen"); - app -} - -/// erolka's X: a quick press chooses the Eyedropper, and holding X swaps fill and stroke. -fn erolka_x(on: bool) -> VectorcraftApp { - let mut app = app_with(on); - app.run("shortcuts.set", json!({"id": "tool:eyedropper", "shortcut": "X", "force": true})).unwrap(); - app.run("shortcuts.set", json!({"id": "paint.swap", "hold": "X"})).unwrap(); - app -} - -/// The fill of the selected object, as `#rrggbb`. -fn fill(app: &VectorcraftApp) -> String { - let d = app.session.active().unwrap(); - let id = *d.selection.objects.first().unwrap(); - d.doc.node(id).unwrap().appearance.fill_paint().color().unwrap().to_hex() -} - -fn selected(app: &VectorcraftApp) -> usize { - app.session.active().unwrap().selection.objects.len() -} - -/// A quick press of X runs its tap at the release, and holding X runs the hold once at the delay, -/// also with no repeats; the repeats until the release run nothing more. -#[test] -fn a_tap_runs_the_key_and_a_hold_runs_the_hold_shortcut() { - let mut app = erolka_x(true); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::X, "x"); - assert_eq!(app.session.tool_id(), "pen", "the press waits"); - keys.release(&mut app, 0.1, Key::X); - assert_eq!(app.session.tool_id(), "eyedropper", "the quick press chooses the Eyedropper"); - assert_eq!(fill(&app), "#ff0000", "and swaps nothing"); - - app.select_tool("pen"); - keys.press(&mut app, 1.0, Key::X, "x"); - keys.frame(&mut app, 1.2, vec![]); - assert_eq!(fill(&app), "#ff0000", "before the delay nothing runs"); - keys.frame(&mut app, 1.35, vec![]); - assert_eq!(fill(&app), "#0000ff", "at the delay the hold swaps fill and stroke"); - assert_eq!(app.session.tool_id(), "pen", "and chooses no tool"); - for t in [1.5, 1.6, 1.7] { - keys.press(&mut app, t, Key::X, "x"); - } - keys.release(&mut app, 1.8, Key::X); - assert_eq!(fill(&app), "#0000ff", "the repeats and the release swap nothing more"); - assert_eq!(app.session.tool_id(), "pen"); -} - -/// The delay is the Hold Shortcut Delay read at the press. -#[test] -fn the_hold_waits_for_the_hold_shortcut_delay() { - let mut app = erolka_x(true); - app.run("prefs.set", json!({"key": "keyHoldDelay", "value": 0.8})).unwrap(); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::X, "x"); - app.run("prefs.set", json!({"key": "keyHoldDelay", "value": 0.2})).unwrap(); - keys.frame(&mut app, 0.5, vec![]); - assert_eq!(fill(&app), "#ff0000", "a later change does not move the wait"); - keys.frame(&mut app, 0.8, vec![]); - assert_eq!(fill(&app), "#0000ff"); -} - -/// erolka's `.`: a quick press keeps the key's own command (Apply Last Gradient) and keeps the -/// selection, and holding it deselects. -#[test] -fn the_period_key_taps_its_own_command_and_holds_to_deselect() { - let mut app = app_with(true); - app.run("shortcuts.set", json!({"id": "select.none", "hold": "."})).unwrap(); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::Period, "."); - keys.release(&mut app, 0.1, Key::Period); - assert_eq!(selected(&app), 1, "the quick press keeps the selection"); - let d = app.session.active().unwrap(); - let id = *d.selection.objects.first().unwrap(); - let appearance = &d.doc.node(id).unwrap().appearance; - let gradient = |p: vectorcraft_color::Paint| matches!(p, vectorcraft_color::Paint::Gradient(_)); - assert!(gradient(appearance.fill_paint()) || gradient(appearance.stroke_paint()), "and applies the last gradient"); - // Solid paint again, so a hold that also ran the tap would show. - app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); - app.run("paint.setStroke", json!({"color": "#0000ff"})).unwrap(); - keys.press(&mut app, 1.0, Key::Period, "."); - keys.frame(&mut app, 1.4, vec![]); - assert_eq!(selected(&app), 0, "the hold deselects"); - keys.release(&mut app, 1.5, Key::Period); - let appearance = &app.session.active().unwrap().doc.node(id).unwrap().appearance; - assert!(!gradient(appearance.fill_paint()) && !gradient(appearance.stroke_paint()), "and applies no gradient"); -} - -/// A hold on a letter alone does not catch the letter with Shift: Shift+X, held, does with Hold -/// Shortcuts on what it does with them off, and does not wait. -#[test] -fn a_hold_on_a_letter_leaves_the_letter_with_shift_alone() { - let mut results = vec![]; - for on in [false, true] { - let mut app = erolka_x(on); - let keys = Keyboard::new(); - keys.frame(&mut app, 0.0, press(Key::X, "X", Modifiers::SHIFT)); - assert!(app.hold_keys.pending.is_none(), "Shift+X does not wait (on {on})"); - let pressed = (fill(&app), app.session.tool_id().to_string()); - keys.frame(&mut app, 1.0, vec![]); - keys.frame(&mut app, 1.1, vec![release(Key::X)]); - results.push((pressed, fill(&app), app.session.tool_id().to_string())); - } - assert_eq!(results[0], results[1], "holding Shift+X does not run X's hold"); -} - -/// A letter the active tool takes itself (E with the Extend Path tool) does not wait, also with a -/// hold shortcut on it. -#[test] -fn a_letter_the_tool_takes_does_not_wait() { - let mut app = app_with(true); - app.run("shortcuts.set", json!({"id": "paint.swap", "hold": "E"})).unwrap(); - app.select_tool(vectorcraft_tools::addons::extend_path::ID); - assert_eq!(app.session.tool_id(), vectorcraft_tools::addons::extend_path::ID); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::E, "e"); - assert!(app.hold_keys.pending.is_none(), "E stays the tool's"); - keys.frame(&mut app, 1.0, vec![]); - keys.release(&mut app, 1.1, Key::E); - assert_eq!(fill(&app), "#ff0000", "the hold does not run"); - assert_eq!(app.session.tool_id(), vectorcraft_tools::addons::extend_path::ID); -} - -/// An input method that starts composing while a key waits ends the wait without running anything. -#[test] -fn an_input_method_composition_ends_the_wait() { - let mut app = erolka_x(true); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::X, "x"); - assert!(app.hold_keys.pending.is_some()); - keys.frame(&mut app, 0.1, vec![egui::Event::Ime(egui::ImeEvent::Preedit { text: "か".into(), active_range_chars: Some(1..1) })]); - assert!(app.hold_keys.pending.is_none(), "the composition ends the wait"); - keys.frame(&mut app, 1.0, vec![]); - keys.release(&mut app, 1.1, Key::X); - assert_eq!(app.session.tool_id(), "pen", "no tap ran"); - assert_eq!(fill(&app), "#ff0000", "and no hold"); -} - -/// A dialog opened, or Presentation Mode entered, while a key waits ends the wait without running -/// anything. -#[test] -fn a_dialog_or_presentation_mode_ends_the_wait() { - for what in ["dialog", "Presentation Mode"] { - let mut app = erolka_x(true); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::X, "x"); - assert!(app.hold_keys.pending.is_some(), "{what}"); - if what == "dialog" { - app.ui.dialog = Some(crate::state::Dialog::new("preferences", json!({}))); - } else { - app.ui.screen_mode = 3; - } - keys.frame(&mut app, 0.1, vec![]); - assert!(app.hold_keys.pending.is_none(), "{what} ends the wait"); - app.ui.dialog = None; - app.ui.screen_mode = 0; - keys.frame(&mut app, 1.0, vec![]); - keys.release(&mut app, 1.1, Key::X); - assert_eq!(app.session.tool_id(), "pen", "{what}: no tap ran"); - assert_eq!(fill(&app), "#ff0000", "{what}: and no hold"); - } -} - -/// A dialog opened while a key waits does not get the key's repeat, or the text it types, from the -/// frame that also lets the key go. -#[test] -fn a_dialog_that_ends_the_wait_gets_no_repeat_from_the_frame_of_the_release() { - let mut app = erolka_x(true); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::X, "x"); - assert!(app.hold_keys.pending.is_some()); - app.ui.dialog = Some(crate::state::Dialog::new("preferences", json!({}))); - let mut events = press(Key::X, "x", Modifiers::NONE); - events.push(release(Key::X)); - let left = keys.frame_left(&mut app, 0.1, events); - assert!(app.hold_keys.pending.is_none(), "the dialog ends the wait"); - assert!( - !left.iter().any(|e| matches!(e, egui::Event::Text(_) | egui::Event::Key { pressed: true, .. })), - "neither the repeat nor its text reaches the dialog: {left:?}" - ); -} - -/// A new wait does not drop a wait left in another viewport unseen: that wait ends, and its key's -/// repeats stay held back in its viewport. -#[test] -fn a_wait_in_another_viewport_ends_when_a_new_one_starts() { - let mut app = erolka_x(true); - let other = egui::ViewportId::from_hash_of("another window"); - app.hold_keys.pending = Some(Pending { - entry: "paint.swap".into(), - chords: vec![], - key: Key::X, - physical: Some(Key::X), - mods: Modifiers::NONE, - since: 0.0, - delay: 0.35, - viewport: other, - }); - let keys = Keyboard::new(); - keys.press(&mut app, 0.1, Key::X, "x"); - assert!(app.hold_keys.pending.as_ref().is_some_and(|p| p.viewport == egui::ViewportId::ROOT), "the new press waits here"); - assert!(app.hold_keys.swallowed.iter().any(|s| s.viewport == other && s.key == Key::X), "the other window's key stays held back"); - assert_eq!(fill(&app), "#ff0000", "the other wait ran nothing"); -} - -/// With Hold Shortcuts off, a key with a hold shortcut runs on its press, as every key does, and -/// holding it runs nothing else. -#[test] -fn with_hold_shortcuts_off_every_key_runs_on_its_press() { - let mut app = erolka_x(false); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::X, "x"); - assert_eq!(app.session.tool_id(), "eyedropper", "the press runs at once"); - keys.frame(&mut app, 1.0, vec![]); - keys.release(&mut app, 1.2, Key::X); - assert_eq!(fill(&app), "#ff0000", "the hold shortcut does not act"); - assert!(app.hold_keys.pending.is_none()); -} - -/// Turning Hold Shortcuts off while a key waits ends the wait without running anything. -#[test] -fn turning_hold_shortcuts_off_ends_the_wait() { - let mut app = erolka_x(true); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::X, "x"); - assert!(app.hold_keys.pending.is_some()); - app.run("prefs.set", json!({"key": "holdShortcuts", "value": false})).unwrap(); - keys.frame(&mut app, 0.5, vec![]); - keys.release(&mut app, 0.6, Key::X); - assert!(app.hold_keys.pending.is_none()); - assert_eq!(fill(&app), "#ff0000", "no hold ran"); - assert_eq!(app.session.tool_id(), "pen", "and no tap"); -} - -/// A key without a hold shortcut runs in its press frame, and a waiting key pressed before it acts -/// first. -#[test] -fn another_key_ends_the_wait_and_runs_after_it() { - let (swap, default) = (label("paint.swap"), label("paint.default")); - let mut app = swap_on_x(); - app.select_tool("selection"); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::P, "p"); - assert_eq!(app.session.tool_id(), "pen", "P runs on its press"); - keys.release(&mut app, 0.05, Key::P); - let n = steps(&app, 0).len(); - keys.press(&mut app, 0.1, Key::X, "x"); - assert_eq!(steps(&app, n), Vec::::new(), "X waits"); - keys.press(&mut app, 0.2, Key::D, "d"); - assert_eq!(steps(&app, n), [swap.clone(), default.clone()], "X's tap ran, then D"); - keys.release(&mut app, 0.3, Key::X); - keys.release(&mut app, 0.35, Key::D); - assert_eq!(steps(&app, n), [swap, default], "the release of X runs nothing more"); - assert_eq!(selected(&app), 1, "and no hold"); -} - -/// 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 (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::D, "d", Modifiers::NONE)); - keys.frame(&mut app, 0.0, events); - 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)); - keys.frame(&mut app, 2.0, events); - keys.frame(&mut app, 2.1, vec![release(Key::X)]); - 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"); -} - -/// A command chord (Undo) pressed before a wait that starts and ends in one frame runs first: the -/// key's tap does not run before it, and the frame acts as it does with Hold Shortcuts off. -#[test] -fn a_chord_before_a_wait_ended_in_its_frame_runs_first() { - assert_eq!(crate::shortcut_editor::default_of("edit.undo"), Some("Cmd+Z")); - let frame = |app: &mut VectorcraftApp| { - app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); - let mut events = - vec![egui::Event::Key { key: Key::Z, physical_key: Some(Key::Z), pressed: true, repeat: false, modifiers: Modifiers::COMMAND }]; - events.extend(press(Key::X, "x", Modifiers::NONE)); - events.push(release(Key::X)); - Keyboard::new().frame(app, 0.0, events); - (fill(app), selected(app)) - }; - let mut off = swap_on_x(); - off.run("prefs.set", json!({"key": "holdShortcuts", "value": false})).unwrap(); - let off = frame(&mut off); - let mut app = swap_on_x(); - let on = frame(&mut app); - assert_eq!(on.0, "#ff0000", "Undo restores the red fill and does not undo X's swap"); - assert_eq!(on, off); - assert!(app.hold_keys.pending.is_none()); -} - -/// A key the active tool takes (E with the Extend Path tool), pressed before a wait that starts and -/// ends in one frame, reaches the tool first: the key's tap, which chooses another tool, does not -/// run before it, and the frame acts as it does with Hold Shortcuts off. -#[test] -fn a_tool_key_before_a_wait_ended_in_its_frame_reaches_the_tool_first() { - let frame = |app: &mut VectorcraftApp| { - app.select_tool(vectorcraft_tools::addons::extend_path::ID); - let mut events = press(Key::E, "e", Modifiers::NONE); - events.extend(press(Key::X, "x", Modifiers::NONE)); - events.push(release(Key::X)); - Keyboard::new().frame(app, 0.0, events); - (app.session.tool_id().to_string(), fill(app)) - }; - let off = frame(&mut erolka_x(false)); - let mut app = erolka_x(true); - let on = frame(&mut app); - assert_eq!(on.0, "eyedropper", "X's tap chooses the Eyedropper after E reached the Extend Path tool"); - assert_eq!(on, off); - assert!(app.hold_keys.pending.is_none()); -} - -/// After a command chord before a wait that starts and ends in one frame, the key's repeats in -/// that frame and in later ones, and the text they type, reach the frame as with Hold Shortcuts -/// off. -#[test] -fn a_chord_before_a_wait_leaves_the_key_repeats_to_the_frame() { - let run = |app: &mut VectorcraftApp| { - app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); - let n = steps(app, 0).len(); - let keys = Keyboard::new(); - let mut events = - vec![egui::Event::Key { key: Key::Z, physical_key: Some(Key::Z), pressed: true, repeat: false, modifiers: Modifiers::COMMAND }]; - events.extend(press(Key::X, "x", Modifiers::NONE)); - events.extend(press(Key::X, "x", Modifiers::NONE)); - events.extend(press(Key::D, "d", Modifiers::NONE)); - let first = keys.frame_left(app, 0.0, events); - let mut events = press(Key::X, "x", Modifiers::NONE); - events.extend([release(Key::X), release(Key::D)]); - let second = keys.frame_left(app, 0.05, events); - (steps(app, n), first, second, fill(app)) - }; - let mut off = swap_on_x(); - off.run("prefs.set", json!({"key": "holdShortcuts", "value": false})).unwrap(); - let off = run(&mut off); - let mut app = swap_on_x(); - let on = run(&mut app); - assert_eq!(on, off); - assert!(app.hold_keys.pending.is_none()); - assert!(app.hold_keys.swallowed.is_empty()); -} - -/// 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. -#[test] -fn a_press_and_release_in_one_frame_is_a_tap() { - let mut app = erolka_x(true); - let keys = Keyboard::new(); - let mut events = press(Key::X, "x", Modifiers::NONE); - events.push(release(Key::X)); - keys.frame(&mut app, 0.0, events); - assert_eq!(app.session.tool_id(), "eyedropper"); - assert!(app.hold_keys.pending.is_none()); - keys.frame(&mut app, 5.0, vec![]); - assert_eq!(fill(&app), "#ff0000", "nothing waits after it"); -} - -/// Another key pressed after the delay has passed, before a frame ran the hold, runs the hold. -#[test] -fn an_overdue_wait_ended_by_another_key_runs_the_hold() { - let mut app = erolka_x(true); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::X, "x"); - keys.press(&mut app, 0.5, Key::V, "v"); - assert_eq!(fill(&app), "#0000ff", "the hold ran"); - assert_eq!(app.session.tool_id(), "selection", "then V"); -} - -/// The window losing the keyboard ends the wait without running anything. -#[test] -fn losing_the_keyboard_ends_the_wait() { - let mut app = erolka_x(true); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::X, "x"); - keys.frame_with_focus(&mut app, 0.1, vec![], false); - keys.frame(&mut app, 1.0, vec![]); - assert_eq!(app.session.tool_id(), "pen"); - assert_eq!(fill(&app), "#ff0000"); - assert!(app.hold_keys.pending.is_none()); -} - -/// Cmd, Ctrl or Alt pressed while a key waits ends the wait as a tap, before the chord runs. -#[test] -fn a_command_modifier_ends_the_wait_as_a_tap() { - let mut app = erolka_x(true); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::X, "x"); - keys.frame(&mut app, 0.1, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND)]); - assert_eq!(app.session.tool_id(), "eyedropper"); - keys.frame(&mut app, 1.0, vec![]); - assert_eq!(fill(&app), "#ff0000", "nothing waits after it"); -} - -/// A tool key with a hold shortcut runs the hold, and the tool is not chosen for the time the key -/// is held (`holdToolKeys`); a quick press chooses the tool for good. -#[test] -fn a_hold_shortcut_takes_a_tool_key_from_hold_tool_keys() { - let mut app = app_with(true); - assert!(app.session.prefs.hold_tool_keys); - app.run("shortcuts.set", json!({"id": "paint.swap", "hold": "S"})).unwrap(); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::S, "s"); - keys.frame(&mut app, 0.4, vec![]); - assert_eq!(fill(&app), "#0000ff", "the hold runs"); - assert_eq!(app.session.tool_id(), "pen", "Scale is not chosen while S is held"); - keys.release(&mut app, 1.0, Key::S); - assert_eq!(app.session.tool_id(), "pen"); - keys.press(&mut app, 2.0, Key::S, "s"); - keys.release(&mut app, 2.1, Key::S); - assert_eq!(app.session.tool_id(), "scale", "a quick press chooses Scale"); - keys.frame(&mut app, 3.0, vec![]); - assert_eq!(app.session.tool_id(), "scale", "for good"); - assert!(app.held_tool.is_empty()); -} - -/// A tool key without a hold shortcut still chooses its tool while held when another key has one. -#[test] -fn other_tool_keys_keep_hold_tool_keys() { - let mut app = erolka_x(true); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::S, "s"); - assert_eq!(app.session.tool_id(), "scale"); - keys.frame(&mut app, 1.0, vec![]); - keys.release(&mut app, 1.1, Key::S); - assert_eq!(app.session.tool_id(), "pen", "the Pen comes back"); -} - -/// A hold on Shift and a digit recorded in the dialog (Shift+1) holds when the press types `!`. -#[test] -fn a_shifted_digit_holds_when_it_types_its_symbol() { - let mut app = app_with(true); - app.run("shortcuts.set", json!({"id": "paint.swap", "hold": "Shift+1"})).unwrap(); - let keys = Keyboard::new(); - keys.frame(&mut app, 0.0, press(Key::Num1, "!", Modifiers::SHIFT)); - keys.frame(&mut app, 0.4, vec![]); - assert_eq!(fill(&app), "#0000ff"); -} - -/// With one entry holding Shift+1 and another `!`, which Shift+1 types, holding Shift+1 runs the -/// entry that holds the key itself. -#[test] -fn a_shifted_digit_holds_before_the_symbol_it_types() { - let mut app = app_with(true); - app.run("shortcuts.set", json!({"id": "paint.swap", "hold": "Shift+1"})).unwrap(); - app.run("shortcuts.set", json!({"id": "select.all", "hold": "!"})).unwrap(); - assert_eq!(app.ui.shortcut_holds.len(), 2); - let keys = Keyboard::new(); - keys.frame(&mut app, 0.0, press(Key::Num1, "!", Modifiers::SHIFT)); - keys.frame(&mut app, 0.4, vec![]); - assert_eq!(fill(&app), "#0000ff", "Shift+1's hold ran"); -} - -/// A quick press of a shifted key with a hold shortcut runs what the key runs without one: a -/// shortcut on Shift+. (typing `>`) runs, and Shift+1 (typing `!`) runs what `!` runs. -#[test] -fn a_quick_press_of_a_shifted_key_runs_what_it_runs_without_a_hold() { - for (key, text, chord) in [(Key::Period, ">", "Shift+."), (Key::Num1, "!", "Shift+1")] { - let mut app = app_with(true); - app.run("shortcuts.set", json!({"id": "tool:eyedropper", "shortcut": chord, "force": true})).unwrap(); - let keys = Keyboard::new(); - keys.frame(&mut app, 0.0, press(key, text, Modifiers::SHIFT)); - keys.frame(&mut app, 0.05, vec![release(key)]); - let without = app.session.tool_id().to_string(); - app.select_tool("pen"); - app.run("shortcuts.set", json!({"id": "paint.swap", "hold": chord})).unwrap(); - keys.frame(&mut app, 1.0, press(key, text, Modifiers::SHIFT)); - assert_eq!(app.session.tool_id(), "pen", "{chord} waits"); - keys.frame(&mut app, 1.05, vec![release(key)]); - assert_eq!(app.session.tool_id(), without, "a quick press of {chord}"); - assert_eq!(fill(&app), "#ff0000"); - } -} - -/// The Shift+. shortcut runs on its press without a hold shortcut, and at the release of a quick -/// press with one. -#[test] -fn a_quick_press_of_shift_period_runs_its_shortcut() { - let mut app = app_with(true); - app.run("shortcuts.set", json!({"id": "tool:eyedropper", "shortcut": "Shift+.", "force": true})).unwrap(); - app.run("shortcuts.set", json!({"id": "paint.swap", "hold": "Shift+."})).unwrap(); - let keys = Keyboard::new(); - keys.frame(&mut app, 0.0, press(Key::Period, ">", Modifiers::SHIFT)); - keys.frame(&mut app, 0.05, vec![release(Key::Period)]); - assert_eq!(app.session.tool_id(), "eyedropper"); -} - -/// A text with no key press that typed it does not wait: it has no key to let go. -#[test] -fn a_text_without_its_key_press_does_not_wait() { - let mut app = erolka_x(true); - let keys = Keyboard::new(); - keys.frame(&mut app, 0.0, vec![egui::Event::Text("x".into())]); - assert!(app.hold_keys.pending.is_none()); - assert_eq!(app.session.tool_id(), "eyedropper", "it runs as a single-key shortcut, as before"); -} - -/// A hold whose command opens a dialog holds back the key's repeats from it. -#[test] -fn a_hold_that_opens_a_dialog_keeps_the_repeats_from_it() { - let mut app = app_with(true); - app.run("shortcuts.set", json!({"id": "edit.preferences", "hold": "K"})).unwrap(); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::K, "k"); - keys.frame(&mut app, 0.4, vec![]); - assert!(app.ui.dialog.is_some(), "the hold opened Preferences"); - let opening = keys.ctx.data(|m| m.get_temp::(super::super::opening_key_id(&keys.ctx))); - assert_eq!(opening, Some(Key::K), "K is the key that opened it"); - keys.press(&mut app, 0.5, Key::K, "k"); - assert!(app.hold_keys.swallowed.iter().any(|s| s.key == Key::K), "K's repeats are held back until it is let go"); - // A repeat in the same frame as the release is held back too. - let mut events = press(Key::K, "k", Modifiers::NONE); - events.push(release(Key::K)); - let left = keys.frame_left(&mut app, 0.6, events); - assert!(!left.iter().any(|e| matches!(e, egui::Event::Text(_) | egui::Event::Key { pressed: true, .. })), "{left:?}"); - assert!(app.hold_keys.swallowed.is_empty()); -} - -/// A key that ends a wait whose tap opens a dialog does not reach the dialog: Enter does not -/// confirm it. -#[test] -fn the_key_that_ends_a_wait_does_not_reach_the_dialog_it_opened() { - let mut app = app_with(true); - app.run("shortcuts.set", json!({"id": "edit.preferences", "shortcut": "K", "force": true})).unwrap(); - app.run("shortcuts.set", json!({"id": "paint.swap", "hold": "K"})).unwrap(); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::K, "k"); - let enter = egui::Event::Key { key: Key::Enter, physical_key: Some(Key::Enter), pressed: true, repeat: false, modifiers: Modifiers::NONE }; - let left = keys.frame_left(&mut app, 0.1, vec![enter]); - assert!(app.ui.dialog.is_some(), "the tap opened Preferences"); - assert!(!left.iter().any(|e| matches!(e, egui::Event::Key { key: Key::Enter, .. })), "{left:?}"); - assert_eq!(fill(&app), "#ff0000"); -} - -/// A key typed before a wait that starts and ends in one frame, and that opens a dialog, keeps the -/// frame's later keys from the dialog, the ones before the waiting key included. -#[test] -fn a_key_typed_before_a_wait_does_not_let_later_keys_reach_its_dialog() { - let mut app = app_with(true); - app.run("shortcuts.set", json!({"id": "edit.preferences", "shortcut": "D", "force": true})).unwrap(); - app.run("shortcuts.set", json!({"id": "paint.swap", "hold": "X"})).unwrap(); - let keys = Keyboard::new(); - let mut events = press(Key::D, "d", Modifiers::NONE); - events.extend(press(Key::A, "a", Modifiers::NONE)); - events.extend(press(Key::X, "x", Modifiers::NONE)); - events.push(release(Key::X)); - let left = keys.frame_left(&mut app, 0.0, events); - assert!(app.ui.dialog.is_some(), "D opened Preferences"); - assert!(!left.iter().any(|e| matches!(e, egui::Event::Text(_) | egui::Event::Key { key: Key::A, pressed: true, .. })), "{left:?}"); - assert_eq!(fill(&app), "#ff0000"); -} - -/// On the web build, where each press's text comes before it, a key typed before a wait that -/// starts and ends in one frame, and that opens a dialog, keeps the frame's later keys from the -/// dialog too. -#[test] -fn a_key_typed_before_a_wait_on_the_web_build_does_not_let_later_keys_reach_its_dialog() { - let mut app = app_with(true); - app.run("shortcuts.set", json!({"id": "edit.preferences", "shortcut": "D", "force": true})).unwrap(); - app.run("shortcuts.set", json!({"id": "paint.swap", "hold": "X"})).unwrap(); - let keys = Keyboard::new(); - let web = |key: Key, text: &str| { - [egui::Event::Text(text.into()), egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE }] - }; - let mut events = vec![]; - for (key, text) in [(Key::D, "d"), (Key::A, "a"), (Key::X, "x")] { - events.extend(web(key, text)); - } - events.push(release(Key::X)); - let left = keys.frame_left(&mut app, 0.0, events); - assert!(app.ui.dialog.is_some(), "D opened Preferences"); - assert!(!left.iter().any(|e| matches!(e, egui::Event::Text(_) | egui::Event::Key { pressed: true, .. })), "{left:?}"); - assert_eq!(fill(&app), "#ff0000"); -} - -/// On the web build a press's text comes before it: the text of the key that ends such a wait -/// does not reach the dialog either. -#[test] -fn the_text_before_the_key_that_ends_a_wait_does_not_reach_the_dialog() { - let mut app = app_with(true); - app.run("shortcuts.set", json!({"id": "edit.preferences", "shortcut": "K", "force": true})).unwrap(); - app.run("shortcuts.set", json!({"id": "paint.swap", "hold": "K"})).unwrap(); - let keys = Keyboard::new(); - keys.press(&mut app, 0.0, Key::K, "k"); - let m = egui::Event::Key { key: Key::M, physical_key: Some(Key::M), pressed: true, repeat: false, modifiers: Modifiers::NONE }; - let left = keys.frame_left(&mut app, 0.1, vec![egui::Event::Text("m".into()), m]); - assert!(app.ui.dialog.is_some(), "the tap opened Preferences"); - assert!(!left.iter().any(|e| matches!(e, egui::Event::Text(_) | egui::Event::Key { pressed: true, .. })), "{left:?}"); -} diff --git a/crates/ui-egui/src/shortcuts/labels.rs b/crates/ui-egui/src/shortcuts/labels.rs deleted file mode 100644 index 9f4f9466fc..0000000000 --- a/crates/ui-egui/src/shortcuts/labels.rs +++ /dev/null @@ -1,179 +0,0 @@ -use egui::text_selection::LabelSelectionState; -use serde_json::json; -use vectorcraft_doc::{NodeId, Selection}; - -use crate::VectorcraftApp; - -/// A Copy or Cut command left to the labels, with the active document (its `uid`) and the -/// selection it was given then. -#[derive(Clone, Default)] -pub(super) struct LeftToLabels { - id: &'static str, - given: Option<(u64, Selection)>, -} - -/// The Copy or Cut command left to the labels of viewport `viewport` in this pass. -fn waiting_id(viewport: egui::ViewportId) -> egui::Id { - egui::Id::unique(("copy-waits-for-labels", viewport)) -} - -/// How many texts viewport `viewport` had copied in this pass before its labels could copy theirs. -fn copies_before_labels_id(viewport: egui::ViewportId) -> egui::Id { - egui::Id::unique(("copies-before-labels", viewport)) -} - -/// The texts copied in this pass of the current viewport so far. -fn copies(ctx: &egui::Context) -> usize { - ctx.output(|o| o.commands.iter().filter(|c| matches!(c, egui::OutputCommand::CopyText(_))).count()) -} - -/// Note the texts copied in this pass so far (the art's, by a Copy or Cut that labels left to this -/// pass): a copy at the end of the pass beyond them is the labels'. -pub(super) fn note_copies_before_labels(ctx: &egui::Context) { - let (id, n) = (copies_before_labels_id(ctx.viewport_id()), copies(ctx)); - ctx.data_mut(|d| d.insert_temp(id, n)); -} - -/// The Copy or Cut command to run in the next pass: the labels it was left to copied nothing. -fn after_labels_id() -> egui::Id { - egui::Id::unique("copy-after-labels") -} - -/// Set when a label in a window of its own (a floating panel's) copied its selected text: the -/// window then sends the Copy or Cut on to the main window ([`crate::panel_docking::forward_keys`]). -/// It lasts until the main window's next pass starts. -fn copied_in_window_id() -> egui::Id { - egui::Id::unique("labels-copied-in-window") -} - -/// Watch the labels' copies from the next pass on ([`leave_to_labels`]). egui runs a plugin only -/// from the pass after the one that adds it. -pub(super) fn watch_label_copies(ctx: &egui::Context) { - if ctx.plugin_opt::().is_none() { - ctx.add_plugin(CopyAfterLabels); - } -} - -/// Copy or Cut `command` (`edit.copy`, `edit.cut`) while text is selected in a label, such as a -/// Document Info value or an Info panel readout: egui copies that text when the Copy or Cut event -/// reaches the labels, so the event is left in the input for them (→ true). When no label of this -/// viewport copies anything in this pass (the selected text is in another window, or its label is -/// not drawn), `command` runs in the next pass ([`take_command_after_labels`]), on the selection of -/// `app`'s active document now ([`run_after_labels`]). -pub(crate) fn leave_to_labels(app: &VectorcraftApp, ctx: &egui::Context, command: &'static str) -> bool { - let selected = ctx.with_plugin(|s: &mut LabelSelectionState| s.has_selection()).unwrap_or(false); - if !selected || ctx.plugin_opt::().is_none() { - return false; - } - let id = waiting_id(ctx.viewport_id()); - let given = active_selection(app); - ctx.data_mut(|d| d.insert_temp(id, LeftToLabels { id: command, given })); - true -} - -/// The `uid` of `app`'s active document and its selection. -fn active_selection(app: &VectorcraftApp) -> Option<(u64, Selection)> { - app.session.active().map(|st| (st.uid, st.selection.clone())) -} - -/// The Copy or Cut command left to this viewport's labels in this pass, if any. -pub(super) fn left_to_labels(ctx: &egui::Context) -> Option<&'static str> { - let id = waiting_id(ctx.viewport_id()); - ctx.data(|d| d.get_temp::(id)).map(|c| c.id) -} - -/// The Copy or Cut command an earlier pass left to labels that copied nothing. -pub(super) fn take_command_after_labels(ctx: &egui::Context) -> Option { - ctx.data_mut(|d| d.remove_temp::(after_labels_id())) -} - -/// Run Copy or Cut `c`, which labels left to this pass, on the selection it was given. A selection -/// made in the same frame after it (a Select All) comes back after it, without the objects a Cut -/// removed and with the pieces it left of a path it split. With another document active by now, -/// or none, it does not run. -pub(super) fn run_after_labels(app: &mut VectorcraftApp, c: LeftToLabels) { - let Some((doc, given)) = c.given else { - crate::menus::invoke(app, c.id, json!({})); - return; - }; - match active_selection(app) { - None => {} - Some((active, _)) if active != doc => {} - Some((_, now)) if now != given => { - if let Err(e) = app.session.select(|_, sel| *sel = given.clone()) { - app.status(e.to_string()); - return; - } - let before = app.session.active().map(|st| st.doc.clone()); - crate::menus::invoke(app, c.id, json!({})); - // The pieces a Cut left of a path it split are new objects: they join the later - // selection when it held an object the Cut acted on. - let acted_on = given.objects.iter().any(|id| now.contains(*id)); - let pieces: Vec = match (before, app.session.active()) { - (Some(before), Some(st)) if acted_on => st.selection.objects.iter().copied().filter(|id| before.node(*id).is_none()).collect(), - _ => vec![], - }; - if let Err(e) = app.session.select(|_, sel| { - *sel = now; - sel.add_all(pieces); - }) { - app.status(e.to_string()); - } - } - _ => crate::menus::invoke(app, c.id, json!({})), - } -} - -/// Note that a floating panel's window copied its label text, as [`CopyAfterLabels`] does. -#[cfg(test)] -pub(crate) fn note_copied_in_window(ctx: &egui::Context) { - ctx.data_mut(|d| d.insert_temp(copied_in_window_id(), true)); -} - -/// Did a label in another window copy its selected text since the last call? The Copy or Cut that -/// window sends on is then its own and copies nothing more. -pub(crate) fn take_copied_in_window(ctx: &egui::Context) -> bool { - ctx.data_mut(|d| d.remove_temp::(copied_in_window_id())).unwrap_or(false) -} - -/// Runs after egui's label text selection at the end of each pass, when the labels have copied -/// their selected text. -struct CopyAfterLabels; - -impl egui::Plugin for CopyAfterLabels { - fn debug_name(&self) -> &'static str { - "CopyAfterLabels" - } - - /// The windows of their own run their passes inside the main window's pass, and their Copy or - /// Cut is sent on in that pass: a copy noted before it is not theirs. - fn on_begin_pass(&mut self, ui: &mut egui::Ui) { - if ui.ctx().viewport_id() == egui::ViewportId::ROOT { - take_copied_in_window(ui.ctx()); - } - } - - fn on_end_pass(&mut self, ui: &mut egui::Ui) { - let ctx = ui.ctx(); - // The art a Copy or Cut copied earlier in this pass is not the labels' copy. - let before_id = copies_before_labels_id(ctx.viewport_id()); - let before = ctx.data_mut(|d| d.remove_temp::(before_id)).unwrap_or(0); - let copied = copies(ctx) > before; - // A field with the keyboard copies its own text, and its window sends nothing on. - if ctx.viewport_id() != egui::ViewportId::ROOT - && copied - && ctx.memory(|m| m.focused().is_none()) - && ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Copy | egui::Event::Cut))) - { - ctx.data_mut(|d| d.insert_temp(copied_in_window_id(), true)); - } - let id = waiting_id(ctx.viewport_id()); - let Some(command) = ctx.data_mut(|d| d.remove_temp::(id)) else { - return; - }; - if !copied { - ctx.data_mut(|d| d.insert_temp(after_labels_id(), command)); - ctx.request_repaint(); - } - } -} diff --git a/crates/ui-egui/src/shortcuts/paste.rs b/crates/ui-egui/src/shortcuts/paste.rs deleted file mode 100644 index f13cf02443..0000000000 --- a/crates/ui-egui/src/shortcuts/paste.rs +++ /dev/null @@ -1,72 +0,0 @@ -use super::{Key, Modifiers, all_shortcuts}; - -/// Keys that paste with Cmd, or alone. (Shift+Insert is left out: Ctrl+Insert copies.) -const PASTE_KEYS: [Key; 2] = [Key::V, Key::Paste]; - -/// The paste command whose V chord `held` holds (Paste in Place for Cmd+Shift+V by default), else -/// Paste: egui reports every Cmd+V chord as a paste, never as its key. -pub(crate) fn paste_command(held: Modifiers) -> &'static str { - all_shortcuts() - .into_iter() - .find(|(sc, id, _)| sc.logical_key == Key::V && id.starts_with("edit.paste") && held.matches_logically(sc.modifiers)) - .map_or("edit.paste", |(_, id, _)| id) -} - -/// Give a copy or cut chord held with more modifiers its key back when it has a shortcut of its own: -/// egui reports every Cmd+C and Cmd+X chord as Copy or Cut, Shift and Alt held too, so Cmd+Shift+C -/// (Align center) copied instead (#1940). -pub(super) fn unclip_chords(i: &mut egui::InputState) { - if !i.events.iter().any(|e| matches!(e, egui::Event::Copy | egui::Event::Cut)) { - return; - } - let (held, shortcuts) = (i.modifiers, all_shortcuts()); - for e in &mut i.events { - let (key, own) = match e { - egui::Event::Copy => (Key::C, "edit.copy"), - egui::Event::Cut => (Key::X, "edit.cut"), - _ => continue, - }; - if shortcuts.iter().any(|(sc, id, _)| sc.logical_key == key && *id != own && held.matches_exact(sc.modifiers)) { - *e = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: held }; - } - } -} - -/// Keyboard pastes of something other than text. egui swallows a paste chord's key press and -/// sends a Paste event only when the clipboard holds text, so a paste key released without its -/// press (or a Paste event) reported was a paste of a bitmap or a PDF. -#[derive(Clone, Default)] -pub(crate) struct PasteChord { - /// Paste keys whose press was reported (typed, not pasting). - pressed: Vec, - /// A Paste event came since the last paste key was released. - pasted: bool, -} - -impl PasteChord { - /// Follow one frame's `events` → the modifiers of a paste egui sent no event for (the chord's, - /// as its key is released). - pub(crate) fn textless_paste(&mut self, events: &[egui::Event]) -> Option { - let mut fire = None; - for e in events { - match e { - egui::Event::Paste(_) => self.pasted = true, - // A release that comes while the window is away is never seen. - egui::Event::WindowFocused(false) => *self = Self::default(), - egui::Event::Key { key, pressed: true, .. } if PASTE_KEYS.contains(key) && !self.pressed.contains(key) => self.pressed.push(*key), - egui::Event::Key { key, pressed: false, modifiers, .. } if PASTE_KEYS.contains(key) => { - match self.pressed.iter().position(|k| k == key) { - Some(i) => { - self.pressed.swap_remove(i); - } - // Unless a Paste event came (the guard takes it either way). - None if !std::mem::take(&mut self.pasted) => fire = Some(*modifiers), - None => {} - } - } - _ => {} - } - } - fire - } -} diff --git a/crates/ui-egui/src/shortcuts/presentation.rs b/crates/ui-egui/src/shortcuts/presentation.rs index 1c447d09e6..75b379dd92 100644 --- a/crates/ui-egui/src/shortcuts/presentation.rs +++ b/crates/ui-egui/src/shortcuts/presentation.rs @@ -1,59 +1,10 @@ -use super::{Key, VectorcraftApp, json}; +use super::{VectorcraftApp, json}; /// Does this Escape reset the view's rotation? The caller has checked that nothing earlier took -/// the press. It does when the view is rotated; no popup, modal window (a progress window, About) -/// or Appearance row popup is open; no text field had the keyboard in the last frame (egui takes -/// the focus away on Escape before this runs); no pointer button is held or let go in this frame -/// (a tab or panel drag takes the Escape, in its release frame too); and neither a ruler-origin -/// drag nor a floating Tools move is ending. +/// the press. It does when the view is rotated and no pointer button is held or let go in this +/// frame (a tab or panel drag takes the Escape, in its release frame too). pub(super) fn escape_resets_rotation(app: &VectorcraftApp, ctx: &egui::Context) -> bool { - app.view().is_some_and(|v| v.rotation != 0.0) - && !egui::Popup::is_any_open(ctx) - && !crate::panel_docking::modal_open(app, ctx) - && app.ui.transient_panel.is_none() - && !super::text_focused_in_previous_frame(ctx) - && !ctx.input(|i| i.pointer.any_down() || i.pointer.any_released()) - && !crate::canvas::ruler_origin_dragging(ctx) - && !crate::tools_float::escape_cancelled_move(ctx) -} - -/// The keys in Presentation Mode, where nothing is edited: Escape leaves the mode, and ← and → go to -/// the previous and the next artboard ([`presentation_step`]). Every other key press, the text it -/// types and the clipboard keys are removed from the input, so no shortcut, tool or field acts on -/// them. The macOS menu bar's key equivalents arrive as key presses too ([`crate::native_menu`]). -pub(super) fn presentation_keys(app: &mut VectorcraftApp, ctx: &egui::Context) { - let (mut leave, mut steps) = (false, vec![]); - ctx.input_mut(|i| { - i.events.retain(|e| match e { - egui::Event::Key { key: Key::Escape, pressed: true, .. } => { - leave = true; - false - } - egui::Event::Key { key: Key::ArrowLeft, pressed: true, .. } => { - steps.push(false); - false - } - egui::Event::Key { key: Key::ArrowRight, pressed: true, .. } => { - steps.push(true); - false - } - egui::Event::Key { pressed: true, .. } - | egui::Event::Text(_) - | egui::Event::Ime(_) - | egui::Event::Copy - | egui::Event::Cut - | egui::Event::Paste(_) - | egui::Event::PasteImage(_) - | egui::Event::MiddleClickPaste { .. } => false, - _ => true, - }) - }); - for next in steps { - presentation_step(app, next); - } - if leave { - let _ = app.run("view.presentation", json!({})); - } + app.view().is_some_and(|v| v.rotation != 0.0) && !ctx.input(|i| i.pointer.any_down() || i.pointer.any_released()) } /// Go to the next artboard (`next`) or the previous one with `view.goToArtboard`, as the status bar diff --git a/crates/ui-egui/src/shortcuts/typing.rs b/crates/ui-egui/src/shortcuts/typing.rs deleted file mode 100644 index 94a5817d9e..0000000000 --- a/crates/ui-egui/src/shortcuts/typing.rs +++ /dev/null @@ -1,484 +0,0 @@ -use super::{EngineResult, Key, Mods, SurroundingUnit, ToolKey, UiRequest, VectorcraftApp, ViewInfo, chord_runs_a_command, typing_presses}; -use crate::panels::character::TextInput; - -/// Drop each key press made with Ctrl and Alt held that is followed by the text it typed. Firefox -/// on Windows reports AltGr as Ctrl and Alt held, so AltGr+L on a Polish layout arrives as a -/// Ctrl+Alt+L press and then the text "ł", which the Type tool types. Without the press no command -/// chord runs for it: neither Cmd+Alt+L nor Cmd+L, which egui matches with the extra Alt held. -pub(super) fn drop_typing_presses(i: &mut egui::InputState) { - let next = i.events.iter().skip(1).map(Some).chain([None]); - let typed: Vec = i - .events - .iter() - .zip(next) - .map(|(e, next)| { - matches!(e, egui::Event::Key { pressed: true, modifiers, .. } if modifiers.ctrl && modifiers.alt) - && matches!(next, Some(egui::Event::Text(t)) if !t.is_empty()) - }) - .collect(); - let mut typed = typed.into_iter(); - i.events.retain(|_| !typed.next().unwrap_or(false)); -} - -/// End an IME composition outside the IME (a click away, the IME going away): the -/// marked text stays as typed, and the system IME is told to drop it. -pub(crate) fn keep_marked_text(app: &mut VectorcraftApp) { - let Some(m) = app.ime_marked.take() else { return }; - app.ime_discard = true; - if app.session.tool_composing() { - // Errors are already reported by the engine's interaction. - let _ = app.session.tool_typed_text(&m, app.view_info()); - } -} - -/// Cmd/Ctrl chords are shortcuts (Create Outlines, Bold, …): their letter is never typed into the -/// text if a host still emits `Text` for them (#2094). Alt is left to type: Option+key on macOS -/// and AltGr (Ctrl+Alt) on Windows keyboards type characters such as é, ø and @. -pub(super) fn is_shortcut_chord(m: egui::Modifiers) -> bool { - (m.command || m.ctrl) && !m.alt -} - -/// The character an Alt chord types while the Type tool edits text on Windows and Linux, with the -/// characters its key types without Alt: Alt+8 •, Alt+G ©, Alt+; …, Alt+7 ¶, Alt+6 §, Alt+2 ™, -/// Alt+R ®, Alt+- en dash, Alt+Shift+- em dash, Alt+[ “, Alt+Shift+[ ”, Alt+] ‘ and Alt+Shift+] ’. -/// A chord with Ctrl or Cmd held, AltGr included, types none of them. -fn alt_chord_character(key: Key, m: egui::Modifiers) -> Option<(char, &'static str)> { - if !m.alt || m.ctrl || m.command || m.mac_cmd { - return None; - } - Some(match (key, m.shift) { - (Key::Num8, false) => ('\u{2022}', "8"), - (Key::G, false) => ('\u{00A9}', "gG"), - (Key::Semicolon, false) => ('\u{2026}', ";"), - (Key::Num7, false) => ('\u{00B6}', "7"), - (Key::Num6, false) => ('\u{00A7}', "6"), - (Key::Num2, false) => ('\u{2122}', "2"), - (Key::R, false) => ('\u{00AE}', "rR"), - (Key::Minus, false) => ('\u{2013}', "-"), - (Key::Minus, true) => ('\u{2014}', "_"), - (Key::OpenBracket, false) => ('\u{201C}', "["), - (Key::OpenBracket | Key::OpenCurlyBracket, true) => ('\u{201D}', "{"), - (Key::CloseBracket, false) => ('\u{2018}', "]"), - (Key::CloseBracket | Key::CloseCurlyBracket, true) => ('\u{2019}', "}"), - _ => return None, - }) -} - -/// Turn each Alt chord of [`alt_chord_character`] into the text of its character. Windows and Linux -/// send the key's own character with the press (Alt+G is a G press and the text "g"); that text is -/// replaced. Any other text that the press typed is what the keyboard layout typed, and it is typed -/// as it came. A press that typed no text gets its character added after it. A text's press is the -/// one [`typing_presses`] pairs it with: the press before it, or in the web build the press after it. -/// An input method's committed or marked text belongs to the last press before it, past modifier -/// changes, key releases, empty pre-edits and deletions around the caret; that press is left as it came, since the input method's text is what the key typed. -fn type_alt_chords(events: &mut Vec) { - let chord = |e: &egui::Event| match e { - egui::Event::Key { key, pressed: true, modifiers, .. } => alt_chord_character(*key, *modifiers), - _ => None, - }; - if !events.iter().any(|e| chord(e).is_some()) { - return; - } - let ime_text = |e: &egui::Event| match e { - egui::Event::Ime(egui::ImeEvent::Commit(t) | egui::ImeEvent::Preedit { text: t, .. }) => !t.is_empty(), - _ => false, - }; - // Events between a press and the input method's text it typed. Windows sends an empty pre-edit - // before each commit, and an input method can delete the text around the caret first. - let between = |e: &egui::Event| match e { - egui::Event::ModifiersChanged(_) | egui::Event::Key { pressed: false, .. } => true, - egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) => text.is_empty(), - egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { .. } | egui::ImeEvent::DeleteSurroundingBytes { .. }) => true, - _ => false, - }; - // The press an input method's text at `j` belongs to. - let ime_press = |j: usize| { - events - .iter() - .enumerate() - .take(j) - .rev() - .find(|(_, e)| !between(e)) - .filter(|(_, e)| matches!(e, egui::Event::Key { pressed: true, .. })) - .map(|(k, _)| k) - }; - let pressed_by = typing_presses(events); - let mut typed = vec![false; events.len()]; - let ime_presses = events.iter().enumerate().filter(|(_, e)| ime_text(e)).map(|(j, _)| ime_press(j)); - for k in pressed_by.iter().copied().chain(ime_presses).flatten() { - if let Some(t) = typed.get_mut(k) { - *t = true; - } - } - let chords: Vec<_> = events.iter().map(chord).collect(); - let mut out = Vec::with_capacity(events.len() + 1); - for (j, e) in std::mem::take(events).into_iter().enumerate() { - match e { - egui::Event::Text(t) => { - let press = pressed_by.get(j).copied().flatten().and_then(|k| chords.get(k).copied().flatten()); - match press { - Some((c, own)) if t.is_empty() || (t.chars().count() == 1 && own.contains(t.as_str())) => { - out.push(egui::Event::Text(c.to_string())); - } - _ => out.push(egui::Event::Text(t)), - } - } - e => { - out.push(e); - if let Some((c, _)) = chords.get(j).copied().flatten() - && !typed.get(j).copied().unwrap_or(false) - { - out.push(egui::Event::Text(c.to_string())); - } - } - } - } - *events = out; -} - -enum Seq { - Text(String), - Preedit(String, Option>), - Commit(String), - /// A space the IME commits during a Zoom tool drag on the canvas, where Space moves the marquee. - MarqueeSpace, - Erase(ToolKey, Mods), - /// An input method replaces text around the composition (upstream's character counts or - /// the fork's exact UTF-8 byte counts), then commits. - DeleteSurrounding(usize, usize, SurroundingUnit), - // The actual pointer/key still belongs to its existing handler. Its position in this - // sequence must nevertheless interrupt an old composition before later terminal input. - InterruptPointer, - InterruptNavigation, - InterruptCommand, - ResetCompleted(egui::ImeResetId), - /// Enter, which types a line break. Cmd+Enter (Ctrl+Enter on Windows and Linux) ends editing. - Enter(Mods), - /// An editing key with modifiers, an arrow, Home, End, Tab or a clipboard event. - Edit(TextInput), -} - -/// Typed text, IME events, editing keys, Enter and clipboard events, in the order they came, to the -/// Type tool. Escape is handled before them, in [`handle`]. -pub(super) fn type_text(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { - let view = app.view_info(); - // Switching apps mid-composition needs nothing: the macOS IME keeps its marked text and goes - // on with it when the window comes back (measured with Kotoeri), as the tool does. - let shortcut_mods = ctx.input(|i| is_shortcut_chord(i.modifiers)); - // A frame that began composing keeps its editing keys for the IME: a Backspace that empties the - // marked text must not then delete the committed character before it. - let was_composing = app.session.tool_composing(); - crate::panels::character::keep_ctx(ctx); - // Text, IME events and plain Backspace/Delete are taken together, in the order they arrived, so - // a keyboard-hook IME (UniKey/OpenKey) whose tone key sends Backspace(s) and then re-injects - // characters in one frame interleaves correctly. Taken as two passes (all text, then the keys) - // the deletes land after the inserts and the diacritics are lost. Enter, the other editing keys - // and the clipboard events join them: ← or a paste lands between the texts around it, and each - // Enter types its own line break (or, as Cmd+Enter, ends editing there). Each handled event is - // removed from the input. - let seq = type_sequence(ctx); - let viewport = ctx.viewport_id(); - let mut old_composition_retired = false; - // Set once the IME commits text in this frame. - let mut committed = false; - for e in seq { - // With text marked, the IME's space commits that text as usual. - let e = match e { - Seq::MarqueeSpace if app.session.tool_composing() || app.ime_marked.is_some() => Seq::Commit(" ".into()), - e => e, - }; - // Before the UI, a changed composition or guard is settled `pending`: a token bound here - // could outlive a route this pass invalidates later (a palette/dialog/Home) and attach to - // the stock descriptor. The post-UI finalizer binds the confirmed replacement. - crate::ime::sync_incoming_before_ui(app, ctx); - if let Seq::ResetCompleted(request) = &e { - old_composition_retired |= crate::ime::complete(app, ctx, *request); - continue; - } - if matches!(app.ime_compositions.get(&viewport), Some(crate::ime::IncomingComposition::Stale)) { - match &e { - // Accepted old payloads precede the fence even when their terminal arrives. - // None of these events proves the local reset has reached its boundary. - Seq::Commit(_) | Seq::MarqueeSpace | Seq::DeleteSurrounding(..) | Seq::Preedit(..) => continue, - _ => {} - } - } - // Otherwise the IME's input ends there, and the space is not typed. - if matches!(e, Seq::MarqueeSpace) { - committed = true; - app.ime_compositions.remove(&viewport); - continue; - } - // A pointer/navigation/command notice has not reached its real handler yet. Text and - // erases after it belong to the old caret, not to the destination it will establish. - if crate::ime::deferred(app, ctx) { - match &e { - // A cut or paste must not change the text at the old caret either. - Seq::Text(_) | Seq::Erase(..) | Seq::Edit(TextInput::Cut | TextInput::Paste(_)) => continue, - _ => {} - } - } - // Editing keys and clipboard events belong to the IME while it composes, and in a frame - // that began composing until the IME commits or the composition is retired. - if matches!(&e, Seq::Edit(_)) && (app.session.tool_composing() || (was_composing && !committed && !old_composition_retired)) { - continue; - } - if let Seq::Commit(t) = &e { - committed |= !t.is_empty() && t != "\n" && t != "\r"; - } - let preedit_empty = match &e { - Seq::Preedit(text, _) => Some(text.is_empty()), - _ => None, - }; - let terminal_commit = matches!(&e, Seq::Commit(_)); - let from_ime = matches!(&e, Seq::Preedit(..) | Seq::Commit(_) | Seq::DeleteSurrounding(..)); - // Errors are already reported by the engine's interaction (a failed preview keeps it). - let result = apply_type_event(app, ctx, view, e, shortcut_mods, was_composing, &mut old_composition_retired); - if result.is_ok() && from_ime { - if terminal_commit { - app.ime_compositions.remove(&viewport); - } else { - crate::ime::remember_incoming(app, ctx, preedit_empty); - } - } - } - old_composition_retired -} - -/// Take this frame's typed text, IME events, editing keys, Enter and clipboard events, in the order -/// they arrived. A space typed during the canvas's Zoom tool drag is not typed. -fn type_sequence(ctx: &egui::Context) -> Vec { - let mut seq = vec![]; - let mut edits = vec![]; - let zooming = crate::canvas::dragging_zoom(ctx); - ctx.input_mut(|i| { - // On a Mac, Option types these characters itself. - if !crate::keymap::platform().is_mac() { - type_alt_chords(&mut i.events); - } - // Move the events out instead of cloning their strings: a keyboard hook that reinjects a - // batch keeps the batch in `seq` only, not in both the input list and a second copy. - let mut kept = Vec::with_capacity(i.events.len()); - // InputState's held flag describes the end of the batch. Recover its initial state from - // the first transition, so a move before a later press cannot cancel an earlier commit. - let mut primary_down = i - .events - .iter() - .find_map(|e| match e { - egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed, .. } => Some(!pressed), - _ => None, - }) - .unwrap_or_else(|| i.pointer.primary_down()); - for e in std::mem::take(&mut i.events) { - match e { - // The zoom drag lasts until the primary button goes up. - egui::Event::Text(t) if zooming && primary_down && t == " " => {} - egui::Event::Text(t) => seq.push(Seq::Text(t)), - egui::Event::Ime(egui::ImeEvent::Preedit { text, active_range_chars }) => { - seq.push(Seq::Preedit(text, active_range_chars)); - } - egui::Event::Ime(egui::ImeEvent::Commit(t)) if zooming && primary_down && t == " " => seq.push(Seq::MarqueeSpace), - egui::Event::Ime(egui::ImeEvent::Commit(t)) => seq.push(Seq::Commit(t)), - egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars, after_chars }) => { - seq.push(Seq::DeleteSurrounding(before_chars, after_chars, SurroundingUnit::Chars)); - } - egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes, after_bytes }) => { - seq.push(Seq::DeleteSurrounding(before_bytes, after_bytes, SurroundingUnit::Bytes)); - } - egui::Event::ImeResetCompleted { request_id } => seq.push(Seq::ResetCompleted(request_id)), - // X11/Wayland PRIMARY middle-click: text at the pointer, inserted as typed text (never - // routed as a key or shortcut). - egui::Event::MiddleClickPaste { text, .. } => seq.push(Seq::Text(text)), - // Only unmodified Backspace/Delete interleave with injected text; word-delete and other - // modified forms are taken with the other editing keys below. - egui::Event::Key { key: key @ (Key::Backspace | Key::Delete), pressed: true, modifiers: m, .. } - if !m.command && !m.alt && !m.ctrl => - { - let tk = if key == Key::Backspace { ToolKey::Backspace } else { ToolKey::Delete }; - seq.push(Seq::Erase(tk, Mods { shift: m.shift, ..Mods::default() })); - } - // A command bound to the chord (Cmd+Enter) runs instead of ending editing, in the - // shortcuts after this. - egui::Event::Key { key: Key::Enter, pressed, modifiers: m, .. } if !chord_runs_a_command(Key::Enter, m, true) => { - if pressed { - seq.push(Seq::Enter(crate::canvas::mods(m, false))); - } - } - e @ egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed, .. } => { - primary_down = pressed; - if pressed { - seq.push(Seq::InterruptPointer); - } - kept.push(e); - } - e @ egui::Event::PointerMoved(_) => { - if primary_down { - seq.push(Seq::InterruptPointer); - } - kept.push(e); - } - e => { - let interrupt = match &e { - egui::Event::Key { key, pressed: true, modifiers, .. } - if matches!(key, Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown | Key::Home | Key::End) - || *key == Key::A && modifiers.command => - { - Some(Seq::InterruptNavigation) - } - egui::Event::Key { pressed: true, modifiers, .. } if is_shortcut_chord(*modifiers) => Some(Seq::InterruptCommand), - egui::Event::Cut | egui::Event::Paste(_) => Some(Seq::InterruptCommand), - _ => None, - }; - seq.extend(interrupt); - // The other editing keys and the clipboard events apply in this order too. - if crate::panels::character::type_input(&e, &mut edits) { - kept.push(e); - } - seq.extend(edits.drain(..).map(Seq::Edit)); - } - } - } - i.events = kept; - }); - seq -} - -/// Apply one sequence item to the active tool; the caller filters stale/deferred events and -/// turns a successful IME mutation into its receipt. -fn apply_type_event( - app: &mut VectorcraftApp, - ctx: &egui::Context, - view: ViewInfo, - e: Seq, - shortcut_mods: bool, - was_composing: bool, - old_composition_retired: &mut bool, -) -> EngineResult> { - match e { - Seq::InterruptPointer => { - *old_composition_retired |= crate::ime::defer_interrupt(app, ctx); - Ok(vec![]) - } - Seq::InterruptNavigation => { - // Active composition owns its navigation keys. Once cleared, application caret - // navigation interrupts its still-pending terminal event, even in this batch. - if !app.session.tool_composing() { - *old_composition_retired |= crate::ime::defer_interrupt(app, ctx); - } - Ok(vec![]) - } - Seq::InterruptCommand => { - if crate::ime::blocked(app, ctx) { - *old_composition_retired |= crate::ime::defer_interrupt(app, ctx); - } - Ok(vec![]) - } - Seq::ResetCompleted(_) | Seq::MarqueeSpace => Ok(vec![]), - // Keys the IME passed through come as text only when nothing is marked. This is an - // application edit (also a hook IME's reinjected characters): `Other` dominates. - Seq::Text(t) if !app.session.tool_composing() && !shortcut_mods => { - let target_before = crate::ime::target(&mut app.session, view); - let before = crate::ime::stamp(&mut app.session, view); - let r = app.session.tool_typed_text(&t, view); - if r.is_ok() { - crate::ime::note_application_edit(app, ctx, view, target_before, before); - } - r - } - Seq::Text(_) => Ok(vec![]), - // A pre-edit is not committed text: it changes neither the outgoing snapshot (the - // engine query removes it) nor the cause. - Seq::Preedit(text, active_range_chars) => { - app.ime_marked = Some(text.clone()).filter(|t| !t.is_empty()); - app.session.tool_preedit(&text, active_range_chars, view) - } - // A bare line break confirms the composition (Enter): the marked text, not a newline. - // It is an accepted IME commit of that marked text when the tool inserts the marked - // text unchanged; a commit the tool rewrites (a quoted or filtered marked text) is an - // application edit instead. - Seq::Commit(t) if t == "\n" || t == "\r" => { - let target_before = crate::ime::target(&mut app.session, view); - let before = crate::ime::stamp(&mut app.session, view); - let composing = app.session.tool_composing(); - let verbatim = app.session.tool_ime_session_matches(view) - && match app.ime_marked.as_deref() { - Some(m) => app.session.tool_typed_text_is_verbatim(m, view), - None => true, - }; - keep_marked_text(app); - if composing { - if verbatim { - crate::ime::note_ime_apply(app, ctx, view, target_before, before); - } else { - crate::ime::note_application_edit(app, ctx, view, target_before, before); - } - } - Ok(vec![]) - } - // An accepted IME commit: stamp the bounded committed context immediately before and - // after, so only a real mutation (not a no-op, rejection or failure) earns the receipt. - // A commit the tool rewrites (Typographer's Quotes, a filtered control character) is an - // application edit and must never earn `InputMethod`. - Seq::Commit(t) => { - app.ime_marked = None; - let target_before = crate::ime::target(&mut app.session, view); - let before = crate::ime::stamp(&mut app.session, view); - // A document edit since the composition means this commit starts a fresh typing - // session: that reset is application-side, so it cannot earn `InputMethod`. - let verbatim = app.session.tool_ime_session_matches(view) && app.session.tool_typed_text_is_verbatim(&t, view); - let r = app.session.tool_typed_text(&t, view); - if r.is_ok() { - if verbatim { - crate::ime::note_ime_apply(app, ctx, view, target_before, before); - } else { - crate::ime::note_application_edit(app, ctx, view, target_before, before); - } - } - r - } - // While composing (or in a frame that began composing), editing keys belong to the IME. - Seq::Erase(tk, m) if !was_composing && !app.session.tool_composing() => { - // Mirror `text_key`: surface an erase error in the status bar instead of discarding it, - // and report the successful edit as application-origin. - let target_before = crate::ime::target(&mut app.session, view); - let before = crate::ime::stamp(&mut app.session, view); - let r = app.session.tool_key(tk, m, view); - match &r { - Err(e) => app.status(e.to_string()), - Ok(_) => crate::ime::note_application_edit(app, ctx, view, target_before, before), - } - r - } - Seq::Erase(..) => Ok(vec![]), - // Deleting around the composition starts the same typing session as the commit that - // follows, so the replacement is one undo step; an error reaches the status bar. The - // receipt covers only this accepted deletion. - Seq::DeleteSurrounding(before, after, unit) => { - let target_before = crate::ime::target(&mut app.session, view); - let stamp_before = crate::ime::stamp(&mut app.session, view); - let r = app.session.tool_ime_delete_surrounding(before, after, unit, view); - match &r { - Err(e) => app.status(e.to_string()), - Ok(_) => crate::ime::note_ime_apply(app, ctx, view, target_before, stamp_before), - } - r - } - // An Enter that confirms the composition types no line break. - Seq::Enter(_) if was_composing || app.session.tool_composing() => Ok(vec![]), - Seq::Enter(m) => { - let target_before = crate::ime::target(&mut app.session, view); - let before = crate::ime::stamp(&mut app.session, view); - let r = app.session.tool_key(ToolKey::Enter, m, view); - if r.is_ok() { - crate::ime::note_application_edit(app, ctx, view, target_before, before); - } - crate::canvas::apply_requests(app, r); - Ok(vec![]) - } - // `text_key` and `text_paste` report the edit as application-origin. - Seq::Edit(t) => { - crate::panels::character::apply_type_input(app, t); - Ok(vec![]) - } - } -}