From 45515d18b536184b357ffdd1cce3eb84bf97525d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:29:19 -0800 Subject: [PATCH] craft-automation: ui.drag presses, moves in even steps and releases as one request A host app that serves the control channel can now run a whole drag from one request instead of composing ui.click with hold, ui.move steps and ui.release itself. - synthetic::Drag reads {from, to, button?, steps?, modifiers}. from and to are point objects {x?, y?, coordinates?, page?}, each in its own space; errors inside one name it (from.x ...). steps runs from 1 to MAX_DRAG_STEPS (200), default DRAG_STEPS (12). - Drag::inject resolves both points before it queues anything, then queues the press at from, the moves to to in even steps (the last one lands on to) and the release at to. The modifiers stay held through the release and are let go afterwards unless other input stays held, as after ui.click. - input_method dispatches ui.drag, so its reply waits for the release. - The crate README, docs/craft-framework.md and docs/porting.md list it. Tests: a drag with a document-point end presses at from, makes one move per step towards to, releases at to and leaves nothing held; a drag keeps its modifiers while a held key stays down; a drag whose end cannot be placed queues no press; bad drag params join the refused-input table. --- crates/automation/README.md | 2 +- crates/automation/src/synthetic.rs | 79 ++++++++++++++++++++++++- crates/automation/tests/it/synthetic.rs | 70 +++++++++++++++++++++- docs/craft-framework.md | 2 +- docs/porting.md | 2 +- 5 files changed, 147 insertions(+), 8 deletions(-) diff --git a/crates/automation/README.md b/crates/automation/README.md index d82a01e5b..be6496ceb 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -14,7 +14,7 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch | `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. | | `protocol` | The JSON-lines wire format: one `{"id", "method", "params"}` request per line, one `{"id", "ok", "result" | "error"}` reply per line; `Params` validators that name the bad parameter. | | `control` | `ControlRequest`, `Reply`, `Dispatch` and `ControlChannel`: the UI-thread side that drains requests between frames, replies after injected input or a background job settles, and admits screenshots. The app supplies the method table. | -| `synthetic` | `Click`, `KeyPress` and `move_from_params`: the validated parameters of `ui.click`, `ui.move` and `ui.key`, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | +| `synthetic` | `Click`, `KeyPress`, `move_from_params` and `Drag`: the validated parameters of `ui.click`, `ui.move`, `ui.key` and `ui.drag` (a press, moves in even steps and the release, from one request), and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | | `server` | `listen` (bind a port) and `serve` (a listener bound earlier): the loopback TCP server that authenticates each connection and forwards requests to the channel, until its `Listening` is dropped. | | `client` | `ControlClient`: connect, authenticate, call (a screenshot is `call("ui.screenshot", ..)`); for integration tests and CLIs. | | `screenshot` | `Captures`: the bounded, cancellable screenshot queue over `WindowHost::screenshot`, with settling, geometry epochs, retries and the PNG reply. | diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index 96024d958..8a2bdb184 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -1,5 +1,5 @@ -//! Synthetic pointer, keyboard and input-method input: `ui.click`, `ui.move`, `ui.wheel`, `ui.key`, `ui.release`, -//! `ui.type`, `ui.ime` and `ui.capsLock`. +//! Synthetic pointer, keyboard and input-method input: `ui.click`, `ui.move`, `ui.drag`, `ui.wheel`, `ui.key`, +//! `ui.release`, `ui.type`, `ui.ime` and `ui.capsLock`. //! //! This module reads and validates the protocol's parameters; the window host queues the input //! ([`WindowHost::inject_move`], [`WindowHost::inject_click`], [`WindowHost::inject_wheel`], @@ -11,7 +11,8 @@ //! withdraws a step queued for a document or focus that changed before the pass consumed it. //! //! Held input: `hold: true` on `ui.click` leaves its last press down and on `ui.key` its key, until `ui.release`; a -//! `ui.move` while a button is held drags. Each request names the modifiers held during it; a move or wheel leaves +//! `ui.move` while a button is held drags. `ui.drag` is the whole gesture in one request: a press, moves in even steps +//! and the release, queued together, so its reply waits for the release. Each request names the modifiers held during it; a move or wheel leaves //! them held (a hover with modifiers across a screenshot), a click or key that holds nothing lets them go. //! //! Points are screen points (egui points), or document points with `coordinates: "document"`, which the application @@ -33,6 +34,12 @@ pub const MAX_CLICKS: u64 = 256; /// display, yet small enough that egui's pointer delta between two such points stays finite. pub const MAX_SCREEN_POINT: f64 = 1e6; +/// Most moves one `ui.drag` may ask for (`steps`). +pub const MAX_DRAG_STEPS: u64 = 200; + +/// The moves a `ui.drag` makes when its request names no `steps`. +pub const DRAG_STEPS: u64 = 12; + /// The longest hover rest one `ui.move` may ask for (`rest`, seconds). pub const MAX_REST: f64 = 10.0; @@ -192,6 +199,71 @@ impl Move { } } +/// A validated `ui.drag`: a press at one point, moves in even steps to another with the button down, and the release +/// there. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Drag { + /// Where the button goes down. + pub from: At, + /// Where the button comes up. + pub to: At, + /// The button pressed. + pub button: PointerButton, + /// Moves from `from` to `to`; the last one lands on `to`. + pub steps: u64, + /// Modifiers held from the press to the release. + pub mods: Mods, +} + +impl Drag { + /// `{from, to, button?, steps?, modifiers…}`, no other fields. `from` and `to` are each a point object + /// `{x?, y?, coordinates?, page?}` in its own space, as `ui.click` reads its point; a missing one is + /// ``"missing `from`"``, and the errors inside one name it (``"from.x must be a finite number"``). `button` + /// defaults to `left`. `steps` is an unsigned integer from 1 to [`MAX_DRAG_STEPS`], default [`DRAG_STEPS`]; + /// outside that range is ``"`steps` must be between 1 and 200 (got {steps})"``. + pub fn from_params(params: &Value) -> Result { + let p = Params(params).only(None, &["from", "to", "button", "steps", "modifiers", "shift", "alt", "command", "ctrl"])?; + let p = Params(&p); + let point = |name: &str| -> Result { + let Some(point) = p.0.get(name) else { return Err(format!("missing `{name}`")) }; + let point = Params(point).only(Some(name), &POINT)?; + At::from_params(&Params(&point)).map_err(|error| format!("{name}.{error}")) + }; + let steps = p.uint_field("steps")?.unwrap_or(DRAG_STEPS); + if !(1..=MAX_DRAG_STEPS).contains(&steps) { + return Err(format!("`steps` must be between 1 and {MAX_DRAG_STEPS} (got {steps})")); + } + Ok(Self { + from: point("from")?, + to: point("to")?, + button: button(&p)?.unwrap_or(PointerButton::Primary), + steps, + mods: p.modifiers(&KEY_MODIFIERS)?, + }) + } + + /// Queues a move to `from` and a press there, `steps` moves in even steps to `to` with the button held, and the + /// release at `to`, in `viewport`; the modifiers are then let go unless other input stays held, as after a click. + /// Both points are resolved before anything is queued, so a point that cannot be placed leaves no press down. + /// When the host withdraws the rest of the gesture after its press ran, the button stays down until `ui.release`, + /// as any held input does. + pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { + let (from, to) = (self.from.resolve(map)?, self.to.resolve(map)?); + let steps = u16::try_from(self.steps).unwrap_or(u16::MAX); + host.inject_click(viewport, from, self.button, 1, self.mods, true); + for step in 1..=steps { + let at = if step == steps { to } else { from.lerp(to, f32::from(step) / f32::from(steps)) }; + host.inject_move(viewport, at, self.mods, 0.0); + } + host.inject_release(viewport, Some(to), Released::Button(self.button)); + // A click of no presses at the pointer's place queues no event: it only lets the modifiers go when nothing + // stays held. + host.inject_click(viewport, to, self.button, 0, self.mods, false); + Ok(()) + } +} + /// A validated `ui.wheel`. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] @@ -304,6 +376,7 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V Some(match method { "ui.click" => Click::from_params(params).and_then(|click| click.inject(host, viewport, map)), "ui.move" => Move::from_params(params).and_then(|step| step.inject(host, viewport, map)), + "ui.drag" => Drag::from_params(params).and_then(|drag| drag.inject(host, viewport, map)), "ui.wheel" => Wheel::from_params(params).and_then(|wheel| wheel.inject(host, viewport, map)), "ui.key" => KeyPress::from_params(params).map(|key| key.inject(host, viewport)), "ui.release" => Release::from_params(params).and_then(|release| release.inject(host, viewport, map)), diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index 494cc848d..aa70cb143 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -1,11 +1,11 @@ -//! Synthetic input through the window host: held presses and keys, modifiers, the wheel, Caps Lock, hover rest, +//! Synthetic input through the window host: held presses and keys, drags, modifiers, the wheel, Caps Lock, hover rest, //! document coordinates and input-method compositions, as the passes see them, and the params refused before //! anything is queued. use std::cell::{Cell, RefCell}; use std::rc::Rc; -use craft_automation::synthetic::{At, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; +use craft_automation::synthetic::{At, MAX_CLICKS, MAX_DRAG_STEPS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; use craft_ui::contract::{Bind, Show as _}; use craft_ui::runtime::egui::injected::hook_without_pass; use craft_ui::runtime::windows::WindowHost; @@ -122,6 +122,52 @@ fn a_held_press_stays_down_until_its_release() { assert!(!rig.now().primary_down, "a click without hold releases"); } +/// `ui.drag` presses at `from`, moves to `to` in `steps` even steps with the button down, releases at `to` with its +/// modifiers held throughout, then lets them go. Each point is in its own space: `to` here is a document point. +#[trial] +fn a_drag_presses_moves_in_steps_and_releases_at_its_end() { + let mut rig = Rig::new(); + rig.fx.settle(); + rig.take(); + let to = map(0, pos2(220.0, 40.0)).expect("the test map places every point"); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 20}, "to": {"x": 220, "y": 40, "coordinates": "document"}, "steps": 4, "shift": true})); + let after = rig.now(); + let events: Vec = rig.take().into_iter().flat_map(|pass| pass.events).collect(); + let buttons: Vec<(Pos2, bool, bool)> = events + .iter() + .filter_map(|event| match event { + Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } => Some((*pos, *pressed, modifiers.shift)), + _ => None, + }) + .collect(); + assert_eq!(buttons, vec![(pos2(10.0, 20.0), true, true), (to, false, true)], "one press at `from`, one release at `to`, both with Shift"); + let held = events.iter().skip_while(|event| !matches!(event, Event::PointerButton { pressed: true, .. })); + let moves: Vec = held + .take_while(|event| !matches!(event, Event::PointerButton { pressed: false, .. })) + .filter_map(|event| match event { + Event::PointerMoved(at) => Some(*at), + _ => None, + }) + .collect(); + assert_eq!(moves.len(), 4, "one move per step while the button is down: {moves:?}"); + assert!(moves.windows(2).all(|pair| pair[1].x > pair[0].x), "each step goes further towards `to`: {moves:?}"); + assert_eq!(moves.last(), Some(&to), "the last step lands on `to`"); + assert!(!after.primary_down && !after.shift, "the drag leaves no button or modifier held"); +} + +/// A drag keeps its modifiers held after its release while other input stays down, as a click does. +#[trial] +fn a_drag_keeps_its_modifiers_while_a_held_key_stays_down() { + let mut rig = Rig::new(); + rig.send("ui.key", json!({"key": "Space", "hold": true})); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 10}, "to": {"x": 60, "y": 10}, "steps": 2, "shift": true})); + let after = rig.now(); + assert!(after.space_down && !after.primary_down, "the key stays down and the drag's button is up"); + assert!(after.shift, "the modifiers stay with the held key"); + rig.send("ui.release", json!({})); + assert!(!rig.now().space_down && !rig.now().shift, "the release lets everything go"); +} + /// A move's modifiers stay held after it (a hover with modifiers); a click that holds nothing lets its own go. #[trial] fn a_move_keeps_its_modifiers_and_a_click_lets_them_go() { @@ -291,6 +337,19 @@ fn document_points_need_a_canvas() { assert_eq!(screen, Some(Ok(()))); } +/// A drag whose end cannot be placed is refused whole: its press at a screen point is not queued either. +#[trial] +fn a_drag_with_an_end_it_cannot_place_queues_no_press() { + let mut rig = Rig::new(); + rig.fx.settle(); + let (host, ctx) = (rig.host(), rig.fx.ctx().clone()); + let none = |_: usize, _: Pos2| None; + let params = json!({"from": {"x": 1, "y": 1}, "to": {"x": 5, "y": 5, "coordinates": "document"}}); + assert_eq!(input_method("ui.drag", ¶ms, &host, ViewportId::ROOT, &none), Some(Err(NO_DOCUMENT.to_owned()))); + assert!(host.injected_idle()); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the refused drag queued nothing"); +} + /// A step handed to the input whose pass has not run is withdrawn when the focus moved, and when the application /// withdraws the input because its document changed: the integration's preserved copy leaves the input, no key /// stays down, and the waiters fail with `TARGET_CHANGED`. @@ -356,6 +415,13 @@ fn bad_input_params_are_refused_before_anything_is_queued() { ("ui.move", json!({"x": 10, "rest": "long"})), ("ui.move", json!({"x": 10, "coordinates": "page"})), ("ui.move", json!({"y": -far})), + ("ui.drag", json!({"from": {"x": 10}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20, "nudge": 1}})), + ("ui.drag", json!({"from": {"x": 10}, "to": [20, 20]})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": far}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": 0})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": MAX_DRAG_STEPS + 1})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "x": 5})), ("ui.key", json!({"key": "A", "hold": true, "nudge": 1})), ("ui.key", json!({"key": 5})), ("ui.key", json!({"key": "NoSuchKey", "hold": true})), diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 5e24eaacd..0c87b65c8 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -1124,7 +1124,7 @@ Control channel, screenshot queue, profiler and recorded actions for tests and s | `server` | Loopback JSON-lines TCP transport (native): `listen`, `serve`, stopped by dropping its `Listening` | exists | | `agents`, `ui::agents` | AI agents in the open window: the agent settings, the ArtCraft Launcher's switch, the connection file and the CLI's live client (re-exported from `craft-control`), the link host and the Agents page of Preferences | exists | | `client` | JSON-lines client for tests and command-line tools (native) | exists | -| `synthetic` | Synthetic pointer and keyboard input: `ui.click`, `ui.move`, `ui.key`, `ui.type` | exists | +| `synthetic` | Synthetic pointer and keyboard input: `ui.click`, `ui.move`, `ui.drag`, `ui.key`, `ui.type` | exists | | `dialogs` | `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` over a `DialogHost` | exists | | `profiler` | Frame profiler | exists | | `screenshot` | Screenshot request queue | exists | diff --git a/docs/porting.md b/docs/porting.md index f7a03e41b..fdd930105 100644 --- a/docs/porting.md +++ b/docs/porting.md @@ -130,7 +130,7 @@ The old app is the visual reference, but not automatically right: judge each dif | Command-line values | `args::ControlOptions`, `EnvNames` | Parses its own flags and calls `ControlOptions::resolve` | | Transport | `server::listen`, `server::serve`, `ControlClient` | Calls `listen` (or `serve` on a listener it bound earlier), keeps the `Listening` and owns the `ControlChannel` | | Request queue, replies | `ControlChannel`, `Reply`, `result_reply` | Runs each request and returns a `Reply` | -| Input methods | `synthetic::Click`, `KeyPress`, `move_from_params`: the checked parameters of `ui.click`, `ui.key`, `ui.move` | Dispatches the method names to them | +| Input methods | `synthetic::Click`, `KeyPress`, `move_from_params`, `Drag`: the checked parameters of `ui.click`, `ui.key`, `ui.move`, `ui.drag` | Dispatches the method names to them | | Dialog methods | `dialogs`: `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel` and the dialog list | Dispatches them; may add `ui.dialog.open` for its own dialog kinds | | Screenshots | `Captures` (the bounded queue), `screenshot_reply`, PNG encoding | Allocates a token for `ui.screenshot`, drives the queue each frame, supplies the file writer | | View and window state | nothing | Methods such as `ui.set` (tool, panels, theme), `ui.resize`, `engine.execute` |