diff --git a/crates/automation/README.md b/crates/automation/README.md index 2d2a9db108..1c0fce5ff2 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`, `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` (also to the centre of a node named by `label` or `id`), `ui.drag` (a held press, `steps` moves and the release), `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), or `listen_with` / `serve_with` with `ServerLimits`: 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. | diff --git a/crates/automation/src/access.rs b/crates/automation/src/access.rs index d25f93d112..43d8026e07 100644 --- a/crates/automation/src/access.rs +++ b/crates/automation/src/access.rs @@ -164,6 +164,34 @@ pub fn resolve(tree: &AccessTree, target: &NodeTarget, action: Declared) -> Resu Ok(key) } +/// The rect of the one reported node `target` names in `viewport`'s kept tree, for a request that points at the node +/// instead of acting on it (`ui.move {label}`): an id must be a reported node; a label matches the reported nodes +/// whose label equals it, ignoring case, and exactly one must match. A node with no area is [`NO_PLACE`]. +pub fn node_rect(host: &WindowHost, viewport: ViewportId, target: &NodeTarget) -> Result { + let tree = host.access_tree_view(viewport).ok_or_else(|| NO_TREE.to_owned())?; + let reported = tree.keys(); + let key = match target { + NodeTarget::Id(raw) => { + let key = NodeKey::from_raw(*raw); + if !reported.contains(&key) { + return Err(format!("no widget with id {raw} on screen (run ui.inspect again)")); + } + key + } + NodeTarget::Label(label) => { + let wanted = label.to_lowercase(); + let named: Vec = + reported.iter().copied().filter(|key| tree.name_of(*key).is_some_and(|name| name.to_lowercase() == wanted)).collect(); + match named.as_slice() { + [one] => *one, + [] => return Err(format!("no widget labelled {label:?} on screen (try ui.inspect with query)")), + many => return Err(format!("{} widgets are labelled {label:?}; name one by id", many.len())), + } + } + }; + tree.bounds_of(key).filter(|rect| rect.is_finite() && rect.width() > 0.0 && rect.height() > 0.0).ok_or_else(|| NO_PLACE.to_owned()) +} + /// The accesskit role's name as agents' scripts read it (`Button`, `CheckBox`). fn role_name(tree: &AccessTree, key: NodeKey) -> Option { match tree.role_of(key)? { diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index 9ef4e222e1..77f56c3621 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -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`], @@ -24,8 +24,9 @@ //! //! 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. `ui.move` to a node goes to the +//! centre of its rect ([`access::node_rect`]). `ui.drag` is a held press, moves and a release in one request; a drag +//! with modifiers or a pause is `ui.click {hold}`, `ui.move` and `ui.release`. use std::path::PathBuf; @@ -169,7 +170,7 @@ fn key(p: &Params<'_>) -> Result, String> { p.choice("key", "key", &[])?.map(|name| Key::parse(name).ok_or_else(|| format!("unknown key `{name}`"))).transpose() } -/// Where a `ui.click` goes. +/// Where a `ui.click` or a `ui.move` goes. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub enum ClickTarget { @@ -282,8 +283,8 @@ impl Click { #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct Move { - /// Target position. - pub at: At, + /// Target position: a point, or the centre of a node of the access tree. + pub target: ClickTarget, /// Modifiers held from the move on. pub mods: Mods, /// Seconds the pointer rests there before the reply. @@ -291,25 +292,83 @@ pub struct Move { } impl Move { - /// `{x, y, coordinates?, rest?, modifiers…}`, no other fields. `rest` is seconds between 0 and [`MAX_REST`]. + /// `{x, y, coordinates?, rest?, modifiers…}` for a point, or `{id | label, rest?, modifiers…}` for the centre of a + /// node of the access tree ([`NodeTarget::from_params`]); no other fields. `rest` is seconds between 0 and + /// [`MAX_REST`]. pub fn from_params(params: &Value) -> Result { - let p = only(params, &["rest"])?; + let p = only(params, &["rest", "id", "label"])?; let p = Params(&p); - Ok(Self { - at: At::required(&p)?, - mods: p.modifiers(&KEY_MODIFIERS)?, - rest: p.number_in("rest", "rest", Some((0.0, MAX_REST)))?.unwrap_or(0.0), - }) + let target = match NodeTarget::from_params(p.0)? { + Some(_) if POINT.iter().any(|field| p.0.get(field).is_some()) => { + return Err("a move names a node (`id` or `label`) or a point (`x`, `y`), not both".into()); + } + Some(node) => ClickTarget::Node(node), + None => ClickTarget::At(At::required(&p)?), + }; + Ok(Self { target, mods: p.modifiers(&KEY_MODIFIERS)?, rest: p.number_in("rest", "rest", Some((0.0, MAX_REST)))?.unwrap_or(0.0) }) } - /// Queues the move in `viewport`. + /// Queues the move in `viewport`; a node is placed through the kept tree ([`access::node_rect`]). pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { - let at = self.at.place(host, viewport, map)?; + let at = match &self.target { + ClickTarget::At(at) => at.place(host, viewport, map)?, + ClickTarget::Node(node) => access::node_rect(host, viewport, node)?.center(), + }; host.inject_move(viewport, at, self.mods, self.rest); Ok(()) } } +/// The most moves one `ui.drag` may ask for (`steps`). +pub const MAX_DRAG_STEPS: u64 = 120; + +/// The moves of a `ui.drag` that names no `steps`. +pub const DRAG_STEPS: u64 = 8; + +/// A validated `ui.drag`: a press at one point, moves to another and the release there. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Drag { + /// Where the press goes down. + pub from: At, + /// Where it is let go. + pub to: At, + /// The button held. + pub button: PointerButton, + /// Moves from `from` to `to`, evenly spaced, the last one at `to`. + pub steps: u64, +} + +impl Drag { + /// `{x, y, toX, toY, coordinates?, page?, steps?, button?}`, no other fields: both points in the space + /// `coordinates` names, on the same page. `steps` is 1 to [`MAX_DRAG_STEPS`], default [`DRAG_STEPS`]; `button` + /// defaults to `left`. + pub fn from_params(params: &Value) -> Result { + let p = Params(params).only(None, &["x", "y", "toX", "toY", "coordinates", "page", "steps", "button"])?; + let p = Params(&p); + let range = Some((-MAX_SCREEN_POINT, MAX_SCREEN_POINT)); + let to_x = p.number_in("toX", "toX", range)?.ok_or_else(|| "missing `toX`".to_owned())? as f32; + let to_y = p.number_in("toY", "toY", range)?.ok_or_else(|| "missing `toY`".to_owned())? as f32; + let steps = p.uint_field("steps")?.unwrap_or(DRAG_STEPS); + if !(1..=MAX_DRAG_STEPS).contains(&steps) { + return Err(format!("`steps` must be 1 to {MAX_DRAG_STEPS} (got {steps})")); + } + Ok(Self { from: At::required(&p)?, to: At::in_space(&p, pos2(to_x, to_y))?, button: button(&p)?.unwrap_or(PointerButton::Primary), steps }) + } + + /// Queues the press at `from`, the moves and the release at `to` in `viewport`, one step per pass. Both points are + /// placed first, so one that cannot be placed queues nothing. + 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)?); + host.inject_click(viewport, from, self.button, 1, Mods::default(), true); + for step in 1..=self.steps { + host.inject_move(viewport, from.lerp(to, step as f32 / self.steps as f32), Mods::default(), 0.0); + } + host.inject_release(viewport, Some(to), Released::Button(self.button)); + Ok(()) + } +} + /// The most notches one `ui.wheel` turn in lines may ask for, either way. pub const MAX_NOTCHES: f32 = 100.0; @@ -437,6 +496,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)), diff --git a/crates/automation/tests/it/access.rs b/crates/automation/tests/it/access.rs index b043a9fd3f..9b6c15602d 100644 --- a/crates/automation/tests/it/access.rs +++ b/crates/automation/tests/it/access.rs @@ -99,6 +99,29 @@ fn a_click_on_a_named_control_lands_on_it() { assert_eq!(rig.find(json!({"name": "Name"})).expect("found")["focused"], json!(true), "the click focused the field"); } +/// `ui.move {label}` puts the pointer inside the one widget with that label, ignoring case, and clicks nothing; a +/// label two widgets share or none has is refused before anything is queued. +#[trial] +fn a_move_to_a_label_hovers_that_widget() { + let mut rig = Rig::kept(["Save", "Cancel"]); + let rect: Vec = rig.find(json!({"name": "Cancel"})).expect("found")["rect"] + .as_array() + .expect("a rect") + .iter() + .map(|v| v.as_f64().expect("a number")) + .collect(); + rig.send("ui.move", json!({"label": "cancel"})).expect("valid"); + let at = rig.pointer.get().expect("the pointer arrived"); + let (x, y) = (f64::from(at.x), f64::from(at.y)); + assert!(x >= rect[0] && x <= rect[0] + rect[2] && y >= rect[1] && y <= rect[1] + rect[3], "{at:?} lies in {rect:?}"); + assert_eq!(rig.counts(), [0, 0], "a move clicks nothing"); + + let mut twins = Rig::kept(["Go", "Go"]); + assert!(twins.send("ui.move", json!({"label": "Go"})).is_err(), "two widgets share the label"); + assert!(twins.send("ui.move", json!({"label": "Stop"})).is_err(), "no widget has it"); + assert!(twins.host.injected_idle(), "nothing was queued"); +} + /// A name two controls share needs an `index`; an unknown name matches none; neither queues anything. Before the /// first kept pass there is no tree to look in. #[trial] diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index 5da112993a..f6feeeed0a 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -6,7 +6,7 @@ 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::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,29 @@ fn a_held_press_stays_down_until_its_release() { assert!(!rig.now().primary_down, "a click without hold releases"); } +/// `ui.drag` presses at its start, moves with the button down through `steps` points towards its end, each on a pass +/// of its own, and lets go at the end. Its points are mapped as every request's are. +#[trial] +fn a_drag_presses_moves_held_and_releases_at_its_end() { + let mut rig = Rig::new(); + rig.fx.settle(); + rig.take(); + rig.send("ui.drag", json!({"x": 200, "y": 100, "toX": 600, "toY": 300, "coordinates": "document", "steps": 4})); + let (from, to) = (pos2(100.0, 50.0), pos2(300.0, 150.0)); + let passes = rig.take(); + let held: Vec = passes.iter().filter(|pass| pass.primary_down).filter_map(|pass| pass.pos).collect(); + assert_eq!(held.first(), Some(&from), "the press goes down at the mapped start"); + let moved: Vec = held.iter().copied().filter(|at| *at != from).collect(); + assert!(moved.len() >= 3, "the moves land on passes of their own with the button down: {held:?}"); + assert!(moved.windows(2).all(|pair| pair[1].x >= pair[0].x && pair[1].y >= pair[0].y), "they head for the end: {moved:?}"); + let released = passes.iter().flat_map(|pass| &pass.events).find_map(|event| match event { + Event::PointerButton { pressed: false, pos, .. } => Some(*pos), + _ => None, + }); + assert_eq!(released, Some(to), "the release is at the mapped end"); + assert!(passes.last().is_some_and(|pass| !pass.primary_down), "nothing stays held"); +} + /// 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() { @@ -411,6 +434,10 @@ fn bad_input_params_are_refused_before_anything_is_queued() { ("ui.focus", json!({})), ("ui.drop", json!({"paths": []})), ("ui.drop", json!({"paths": ["a.pdf"], "alt": true})), + ("ui.drag", json!({"x": 10, "y": 10, "toX": 50})), + ("ui.drag", json!({"x": 10, "y": 10, "toX": 50, "toY": 50, "steps": 0})), + ("ui.drag", json!({"x": 10, "y": 10, "toX": 50, "toY": 50, "steps": MAX_DRAG_STEPS + 1})), + ("ui.drag", json!({"x": 10, "y": 10, "toX": 50, "toY": 50, "shift": true})), ]; for (method, params) in &refused { let answer = input_method(method, params, &host, ViewportId::ROOT, &map); diff --git a/crates/table/src/ui/grid.rs b/crates/table/src/ui/grid.rs index 5369f83697..5d931624bd 100644 --- a/crates/table/src/ui/grid.rs +++ b/crates/table/src/ui/grid.rs @@ -176,6 +176,7 @@ pub struct CellGrid<'a> { common: Common, #[container] props: ContainerProps, + #[collection(natural_height)] items: CollectionProps, /// Whether the row and column headings show. #[style_key] diff --git a/crates/table/tests/it/grid.rs b/crates/table/tests/it/grid.rs index 0d1d3f4544..603d1cb846 100644 --- a/crates/table/tests/it/grid.rs +++ b/crates/table/tests/it/grid.rs @@ -338,6 +338,56 @@ fn a_pass_runs_only_the_rows_in_view() { assert!(painted.iter().all(|&row| row < in_view), "rows past the view ran: {painted:?}"); } +/// A short sheet, five rows of two columns, that records the rows it paints. +struct Short { + rows: LineIndex, + columns: LineIndex, + painted: Rc>>, +} + +impl GridModel for Short { + fn rows(&self) -> &LineIndex { + &self.rows + } + + fn columns(&self) -> &LineIndex { + &self.columns + } + + fn last_used(&self) -> CellAt { + CellAt::new(4, 1) + } + + fn paint_cell(&self, ui: &mut PaintUi<'_>, rect: Rect, cell: CellAt, _zoom: f32) { + self.painted.borrow_mut().insert(cell.row); + ui.draw().text(rect, &TextRun::new(self.cell_text(cell)).elide()); + } + + fn cell_text(&self, cell: CellAt) -> String { + format!("{}", cell.row * 10 + cell.column) + } +} + +/// A sheet with the natural height shows every row, though its room holds fewer, and owns no scroll: a sheet inside a +/// scrolling dialog body (a chart's data) leaves the scrolling to the body. +#[trial] +fn a_sheet_with_the_natural_height_shows_every_row() { + const ROOM: Vec2 = Vec2::new(400.0, ROW * 2.0); + let painted = Rc::new(RefCell::new(BTreeSet::new())); + let rows = painted.clone(); + let state = RefCell::new(GridState::new(a1(), 1.0)); + let mut fixture = Fixture::new(move |ui| { + let model = Short { rows: LineIndex::uniform(ROW, 5), columns: LineIndex::uniform(COLUMN, 2), painted: rows.clone() }; + let mut shown = state.borrow().clone(); + CellGrid::new("Sheet", &model, &mut shown).headings(false).natural_height(true).show_sheet(ui); + *state.borrow_mut() = shown; + }); + fixture.room(ROOM).settle(); + painted.borrow_mut().clear(); + fixture.idle(1); + assert_eq!(painted.borrow().len(), 5, "every row is shown: {:?}", painted.borrow()); +} + /// Alt+Enter and Ctrl+Enter open the active cell's editor, as F2 does. #[trial] fn alt_or_ctrl_enter_opens_the_active_cell() {