mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 15:21:17 -05:00
shortcuts-w9: net change of 1 commits
- shortcuts-w9: written from its sheet
This commit is contained in:
+85
-1288
File diff suppressed because it is too large
Load Diff
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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<f64>,
|
||||
}
|
||||
|
||||
/// 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<Key>, 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;
|
||||
|
||||
@@ -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<egui::Event>, 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<egui::Event>) {
|
||||
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<egui::Event>, mut field: Option<&mut String>, focused: bool) {
|
||||
fn frame_with_focus(&self, app: &mut VectorcraftApp, time: f64, events: Vec<egui::Event>, 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<egui::Event>) {
|
||||
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");
|
||||
}
|
||||
|
||||
@@ -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:<id>`, a command id or `panel:<id>`).
|
||||
entry: String,
|
||||
/// The chords the press names, first match first, for the tap.
|
||||
chords: Vec<craft_keymap::Chord>,
|
||||
/// 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<Key>,
|
||||
/// 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<Key>,
|
||||
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<Pending>,
|
||||
swallowed: Vec<Swallowed>,
|
||||
}
|
||||
|
||||
/// 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<Key>) -> 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: Key, physical: Option<Key>) -> 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<Key>) -> 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<Key>)> = 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<Key>)]) {
|
||||
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<bool> = 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<craft_keymap::Chord> {
|
||||
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<craft_keymap::Chord> {
|
||||
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<craft_keymap::Chord> = 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<usize>], 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<usize>],
|
||||
start: usize,
|
||||
taken: &mut Vec<usize>,
|
||||
) -> Option<usize> {
|
||||
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<usize> = 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;
|
||||
@@ -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<egui::Event>, 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<egui::Event>) {
|
||||
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<egui::Event>) -> Vec<egui::Event> {
|
||||
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<egui::Event> {
|
||||
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::<String>::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<String> {
|
||||
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::<Key>(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:?}");
|
||||
}
|
||||
@@ -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::<CopyAfterLabels>().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::<CopyAfterLabels>().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::<LeftToLabels>(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<LeftToLabels> {
|
||||
ctx.data_mut(|d| d.remove_temp::<LeftToLabels>(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<NodeId> = 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::<bool>(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::<usize>(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::<LeftToLabels>(id)) else {
|
||||
return;
|
||||
};
|
||||
if !copied {
|
||||
ctx.data_mut(|d| d.insert_temp(after_labels_id(), command));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Key>,
|
||||
/// 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<Modifiers> {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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<bool> = 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<egui::Event>) {
|
||||
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<std::ops::Range<usize>>),
|
||||
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<Seq> {
|
||||
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<Vec<UiRequest>> {
|
||||
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![])
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user