Merge pull request #2956 from dotCooCoo/feat/automation-ui-drag

craft-automation: ui.drag presses, moves in even steps and releases as one request
This commit is contained in:
BFlat
2026-11-26 10:24:55 +07:00
committed by GitHub
5 changed files with 155 additions and 10 deletions
+1 -1
View File
@@ -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`, `Move`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. |
| `synthetic` | `Click`, `Move`, `Drag`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `ui.drag` (a press, moves in even steps and the release, from one request), `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. |
| `access` | Named controls over the window's access tree (`ui` feature): `Target` (`{name, role?, within?, index?}`, found in reading order), `describe`, and `access_method`, which answers `ui.find` from the tree `ControlChannel::poll_input` has the host keep. |
| `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. |
+76 -4
View File
@@ -1,5 +1,5 @@
//! Synthetic pointer, keyboard, input-method, file-drop and access-tree input: `ui.click`, `ui.focus`, `ui.move`,
//! `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` and `ui.capsLock`.
//! `ui.drag`, `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` 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`],
@@ -12,7 +12,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
@@ -22,8 +23,7 @@
//!
//! A node of the access tree (`id` or `label`, [`NodeTarget`]) is clicked or focused through the node's own action
//! instead of a point: [`crate::access::resolve`] finds it in the window's kept tree when the request arrives, so a
//! missing, ambiguous, disabled or undeclared node is refused before anything is queued. There is no `ui.drag`: a
//! drag is `ui.click {hold}`, `ui.move` and `ui.release`.
//! missing, ambiguous, disabled or undeclared node is refused before anything is queued.
use std::path::PathBuf;
@@ -43,6 +43,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;
@@ -302,6 +308,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?, control?}` 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<Self, String> {
let p = Params(params).only(None, &["from", "to", "button", "steps", "modifiers", "shift", "alt", "command", "ctrl"])?;
let p = Params(&p);
let point = |name: &str| -> Result<At, String> {
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 placed before anything is queued (a control point against the access tree the host kept for
/// `viewport`), 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.place(host, viewport, map)?, self.to.place(host, viewport, 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(())
}
}
/// The most notches one `ui.wheel` turn in lines may ask for, either way.
pub const MAX_NOTCHES: f32 = 100.0;
@@ -429,6 +500,7 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V
"ui.focus" => Focus::from_params(params).and_then(|focus| focus.inject(host, viewport)),
"ui.drop" => drop_files(params, 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)),
+76 -3
View File
@@ -1,12 +1,12 @@
//! 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::access::NO_TREE;
use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method};
use craft_automation::access::{NO_CONTROL, NO_TREE};
use craft_automation::synthetic::{At, Click, Focus, 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;
@@ -123,6 +123,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<Event> = 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<Pos2> = 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() {
@@ -292,6 +338,25 @@ 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. That holds
/// for a document end without a canvas and for a control end that names no control of the window.
#[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", &params, &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");
let params = json!({"from": {"x": 1, "y": 1}, "to": {"control": {"name": "Save"}, "x": 4}});
let answer = input_method("ui.drag", &params, &host, ViewportId::ROOT, &map);
assert!(matches!(&answer, Some(Err(error)) if error.starts_with(NO_CONTROL)), "{answer:?}");
assert!(host.injected_idle());
assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the drag to an unplaced control 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`.
@@ -358,6 +423,14 @@ fn bad_input_params_are_refused_before_anything_is_queued() {
("ui.move", json!({"x": 10, "y": 10, "rest": "long"})),
("ui.move", json!({"x": 10, "y": 10, "coordinates": "page"})),
("ui.move", json!({"x": 10, "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.drag", json!({"from": {"x": 10}, "to": {"control": {"name": "Save"}, "coordinates": "document"}})),
("ui.key", json!({"key": "A", "hold": true, "nudge": 1})),
("ui.key", json!({"key": 5})),
("ui.key", json!({"key": "NoSuchKey", "hold": true})),
+1 -1
View File
@@ -1132,7 +1132,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 |
+1 -1
View File
@@ -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::input_method`, or one by one `synthetic::Click` (a point, or a node of the access tree by `id` or `label` as its `target`), `Focus`, `KeyPress`, `Move::from_params`: the checked parameters of `ui.click`, `ui.focus`, `ui.key`, `ui.move` and the other input methods | Dispatches the method names to them and replies `Reply::AfterInput` |
| Input methods | `synthetic::input_method`, or one by one `synthetic::Click` (a point, or a node of the access tree by `id` or `label` as its `target`), `Focus`, `KeyPress`, `Move::from_params`, `Drag`: the checked parameters of `ui.click`, `ui.focus`, `ui.key`, `ui.move`, `ui.drag` and the other input methods | Dispatches the method names to them and replies `Reply::AfterInput` |
| Widget tree | `access::inspect` (`ui.inspect`'s widget list), `access::resolve` (the one node an `id` or `label` names), read from the tree `server::serve` has the window host keep | Adds its own fields to `ui.inspect`'s reply |
| 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 | `ScreenshotParams` (`ui.screenshot {path?, region?}`), `Captures` (the bounded queue), `screenshot_reply` (the crop to the region, PNG encoding) | Allocates a token for `ui.screenshot`, drives the queue each frame, supplies the file writer |