mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 02:09:00 +00:00
pdf-shell-w2: net change of 2 commits
- pdf-shell-w2: written by an agent - pdf-shell-w2: review fixes (review-1)
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "craft-automation"
|
||||
description = "Drive a running Craft app from tests, agents and the CLI (control channel, screenshot queue, frame profiler and frame trace; native only), and recorded actions with the Actions panel (every target)."
|
||||
description = "Drive a running Craft app from tests, agents and the CLI (control channel, screenshot queue and synthetic input on every target; server, client, frame profiler and frame trace native only), and recorded actions with the Actions panel (every target)."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -21,7 +21,7 @@ default = []
|
||||
# The egui parts: the Actions panel, the control channel's server side (screenshots, synthetic
|
||||
# input) and `ui` stories. Without it the crate has no egui: `ControlOptions`, `ControlClient`,
|
||||
# `Params` and the recorded actions' model and files.
|
||||
ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui", "dep:craft-host"] # P3(pdf-shell-w2): WF-W17
|
||||
ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui", "dep:craft-host"]
|
||||
# The Actions panel's and the Agents page's stories and mock, and the integration binary `tests/it`.
|
||||
screen-testing = ["ui", "agents", "craft-ui/testing"]
|
||||
# Agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file an
|
||||
@@ -30,26 +30,29 @@ screen-testing = ["ui", "agents", "craft-ui/testing"]
|
||||
agents = ["dep:craft-ai-agents", "dep:craft-flags", "dep:craft-atomic", "dep:craft-host"]
|
||||
|
||||
[dependencies]
|
||||
# The screenshot reply's PNG and its inline base64 (the control channel builds on every target with `ui`).
|
||||
base64 = "0.22"
|
||||
craft-behavior = { workspace = true, optional = true }
|
||||
craft-host = { workspace = true, optional = true }
|
||||
craft-keymap = { workspace = true, optional = true }
|
||||
craft-theme = { workspace = true }
|
||||
craft-ui = { workspace = true, optional = true }
|
||||
egui = { workspace = true, optional = true }
|
||||
png = "0.17"
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
# `std::time::Instant` panics on wasm; this is the same type on native.
|
||||
web-time = "1.1"
|
||||
|
||||
# The control channel, its server and client, screenshots, the profiler and the trace.
|
||||
# The server and client, the token files, the profiler and the trace.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
base64 = "0.22"
|
||||
craft-platform = { workspace = true }
|
||||
craft-ai-agents = { workspace = true, optional = true }
|
||||
craft-atomic = { workspace = true, optional = true }
|
||||
craft-flags = { workspace = true, optional = true }
|
||||
craft-host = { workspace = true, optional = true }
|
||||
getrandom = "0.3"
|
||||
hmac = "0.12"
|
||||
log = "0.4"
|
||||
png = "0.17"
|
||||
sha2 = { version = "0.10", default-features = false, features = ["std"] }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
|
||||
+165
-10
@@ -1,10 +1,26 @@
|
||||
//! `ui.inspect`: the reported widgets of a window's access tree, and the lookup of the one node a click or a focus
|
||||
//! names.
|
||||
//!
|
||||
//! Both read the tree the window host keeps from the last presented frame ([`WindowHost::keep_access_tree`], which
|
||||
//! the control server turns on) and walk only the nodes assistive technology reports ([`AccessTree::keys`]): a hidden node,
|
||||
//! one below it and one behind an open modal are neither listed nor reachable.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use craft_behavior::Mixed;
|
||||
use craft_ui::runtime::access::Role;
|
||||
use craft_ui::runtime::egui::access::{AccessTree, Declared, NodeKey};
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use egui::ViewportId;
|
||||
use serde_json::Value;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::protocol::Params;
|
||||
|
||||
/// The widgets `ui.inspect` lists when the request names no `limit`.
|
||||
pub const DEFAULT_LIMIT: u64 = 500;
|
||||
|
||||
/// The error of a request that needs the access tree before the window presented a frame with one.
|
||||
pub const NO_TREE: &str = "no accessibility tree yet; draw a frame first";
|
||||
|
||||
/// The node a method names: its id or its label.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -16,23 +32,162 @@ pub enum NodeTarget {
|
||||
}
|
||||
|
||||
impl NodeTarget {
|
||||
/// The node `params` name (`id` or `label`), or none when they name none.
|
||||
/// The node `params` name (`id` or `label`), or none when they name none. `id` is the id `ui.inspect` lists, a
|
||||
/// decimal string or a number; `label` is a string; naming both is an error. Other fields are the caller's to
|
||||
/// check; a `null` field is absent.
|
||||
pub fn from_params(params: &Value) -> Result<Option<NodeTarget>, String> {
|
||||
let _ = params;
|
||||
todo!("SH-C15")
|
||||
let field = |key: &str| params.get(key).filter(|value| !value.is_null());
|
||||
match (field("id"), field("label")) {
|
||||
(Some(_), Some(_)) => Err("`id` and `label` exclude each other".into()),
|
||||
(Some(id), None) => {
|
||||
let raw = id.as_u64().or_else(|| id.as_str().and_then(|text| text.parse().ok()));
|
||||
raw.map(|raw| Some(NodeTarget::Id(raw))).ok_or_else(|| "id must be a widget id from ui.inspect".into())
|
||||
}
|
||||
(None, Some(Value::String(label))) => Ok(Some(NodeTarget::Label(label.clone()))),
|
||||
(None, Some(_)) => Err("label must be a string".into()),
|
||||
(None, None) => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a node that takes `action` is, for the refusal of one that does not.
|
||||
fn able(action: Declared) -> &'static str {
|
||||
match action {
|
||||
Declared::Click => "clickable",
|
||||
Declared::Focus => "focusable",
|
||||
Declared::ContextMenu => "a widget with a context menu",
|
||||
_ => "a widget that takes this action",
|
||||
}
|
||||
}
|
||||
|
||||
/// The one reported, enabled node of `tree` that declares `action` and that `target` names; an error names none,
|
||||
/// several, disabled or undeclared.
|
||||
/// several, disabled or undeclared. An id must be a reported node; a label matches the reported, enabled nodes that
|
||||
/// declare `action` and whose label equals it, ignoring case, and exactly one must match.
|
||||
pub fn resolve(tree: &AccessTree, target: &NodeTarget, action: Declared) -> Result<NodeKey, String> {
|
||||
let _ = (tree, target, action);
|
||||
todo!("SH-C15")
|
||||
let reported = tree.keys();
|
||||
let label_of = |key: NodeKey| tree.name_of(key).unwrap_or("unlabelled").to_owned();
|
||||
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<NodeKey> = reported.iter().copied().filter(|key| tree.name_of(*key).is_some_and(|name| name.to_lowercase() == wanted)).collect();
|
||||
let usable: Vec<NodeKey> = named.iter().copied().filter(|key| !tree.is_disabled_key(*key) && tree.declares_key(*key, action)).collect();
|
||||
match usable.as_slice() {
|
||||
[one] => *one,
|
||||
[] if named.is_empty() => return Err(format!("no widget labelled {label:?} on screen (try ui.inspect with query)")),
|
||||
[] if named.iter().any(|key| tree.declares_key(*key, action)) => {
|
||||
return Err(format!("the widget labelled {label:?} is disabled"));
|
||||
}
|
||||
[] => return Err(format!("the widget labelled {label:?} is not {}", able(action))),
|
||||
many => return Err(format!("{} widgets are labelled {label:?}; name one by id", many.len())),
|
||||
}
|
||||
}
|
||||
};
|
||||
if tree.is_disabled_key(key) {
|
||||
return Err(format!("widget {} ({}) is disabled", key.raw(), label_of(key)));
|
||||
}
|
||||
if !tree.declares_key(key, action) {
|
||||
return Err(format!("widget {} ({}) is not {}", key.raw(), label_of(key), able(action)));
|
||||
}
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
/// The accesskit role's name as agents' scripts read it (`Button`, `CheckBox`).
|
||||
fn role_name(tree: &AccessTree, key: NodeKey) -> Option<String> {
|
||||
match tree.role_of(key)? {
|
||||
Role::Node(role) => Some(format!("{role:?}")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One listed widget: `{id, role, depth, enabled, clickable, focusable}` and, where the node says, `label`, `value`,
|
||||
/// `description`, `rect` (`[x0, y0, x1, y1]` in points), `toggled` (`true`, `false` or `mixed`), `selected`, and
|
||||
/// `focused: true` for the focused node. The id is a decimal string: 64-bit ids do not survive JSON readers that use
|
||||
/// doubles.
|
||||
fn widget(tree: &AccessTree, key: NodeKey, depth: usize, focused: bool) -> Value {
|
||||
let mut w = Map::new();
|
||||
w.insert("id".into(), json!(key.raw().to_string()));
|
||||
w.insert("role".into(), json!(role_name(tree, key)));
|
||||
w.insert("depth".into(), json!(depth));
|
||||
w.insert("enabled".into(), json!(!tree.is_disabled_key(key)));
|
||||
w.insert("clickable".into(), json!(tree.declares_key(key, Declared::Click)));
|
||||
w.insert("focusable".into(), json!(tree.declares_key(key, Declared::Focus)));
|
||||
if let Some(label) = tree.name_of(key) {
|
||||
w.insert("label".into(), json!(label));
|
||||
}
|
||||
if let Some(value) = tree.value_of(key) {
|
||||
w.insert("value".into(), json!(value));
|
||||
}
|
||||
if let Some(description) = tree.description_of(key) {
|
||||
w.insert("description".into(), json!(description));
|
||||
}
|
||||
if let Some(rect) = tree.bounds_of(key) {
|
||||
w.insert("rect".into(), json!([rect.min.x, rect.min.y, rect.max.x, rect.max.y]));
|
||||
}
|
||||
if let Some(toggled) = tree.toggled_of(key) {
|
||||
let toggled = match toggled {
|
||||
Mixed::Same(true) => "true",
|
||||
Mixed::Same(false) => "false",
|
||||
Mixed::Mixed => "mixed",
|
||||
};
|
||||
w.insert("toggled".into(), json!(toggled));
|
||||
}
|
||||
if let Some(selected) = tree.selected_of(key) {
|
||||
w.insert("selected".into(), json!(selected));
|
||||
}
|
||||
if focused {
|
||||
w.insert("focused".into(), json!(true));
|
||||
}
|
||||
Value::Object(w)
|
||||
}
|
||||
|
||||
/// `inspect {query?, role?, focused?, limit?=500}`: the reply `{widgets, count, truncated}` over the reported nodes
|
||||
/// of `viewport`'s access tree, in tree order.
|
||||
/// of `viewport`'s access tree, in tree order (depth first from the root, which is not listed, children in their
|
||||
/// order). `query` matches a widget whose label, value or description contains it, ignoring case; `role` its role's
|
||||
/// name, ignoring case; `focused` whether it is the focused node. `count` is every widget the filters keep, `widgets`
|
||||
/// the first `limit` of them. No other fields; [`NO_TREE`] before the window presented a frame.
|
||||
pub fn inspect(host: &WindowHost, viewport: ViewportId, params: &Value) -> Result<Value, String> {
|
||||
let _ = (host, viewport, params);
|
||||
todo!("SH-C15")
|
||||
let p = Params(params).only(None, &["query", "role", "focused", "limit"])?;
|
||||
let p = Params(&p);
|
||||
let query = p.str_field("query")?.map(str::to_lowercase);
|
||||
let role = p.str_field("role")?.map(str::to_lowercase);
|
||||
let focused = p.bool_field("focused")?;
|
||||
let limit = usize::try_from(p.uint_field("limit")?.unwrap_or(DEFAULT_LIMIT)).unwrap_or(usize::MAX);
|
||||
let tree = host.access_tree(viewport).ok_or_else(|| NO_TREE.to_owned())?;
|
||||
|
||||
let reported: HashSet<NodeKey> = tree.keys().into_iter().collect();
|
||||
let root = tree.root_key();
|
||||
let focus = tree.focused_key();
|
||||
let (mut widgets, mut count) = (Vec::new(), 0usize);
|
||||
// A stack, not recursion: the tree comes from the app and may be deep. `walked` keeps a malformed tree that lists
|
||||
// a node twice from listing it twice or looping.
|
||||
let mut walked = HashSet::new();
|
||||
let mut pending: Vec<(NodeKey, usize)> = root.into_iter().map(|key| (key, 0)).collect();
|
||||
while let Some((key, depth)) = pending.pop() {
|
||||
if !reported.contains(&key) || !walked.insert(key) {
|
||||
continue;
|
||||
}
|
||||
pending.extend(tree.children_of(key).into_iter().rev().map(|child| (child, depth + 1)));
|
||||
if Some(key) == root {
|
||||
continue;
|
||||
}
|
||||
let text = [tree.name_of(key), tree.value_of(key), tree.description_of(key)].into_iter().flatten().collect::<Vec<_>>().join(" ").to_lowercase();
|
||||
let keep = query.as_ref().is_none_or(|query| text.contains(query.as_str()))
|
||||
&& role.as_ref().is_none_or(|role| role_name(&tree, key).is_some_and(|name| name.to_lowercase() == *role))
|
||||
&& focused.is_none_or(|wanted| (key == focus) == wanted);
|
||||
if !keep {
|
||||
continue;
|
||||
}
|
||||
count += 1;
|
||||
if widgets.len() < limit {
|
||||
widgets.push(widget(&tree, key, depth, key == focus));
|
||||
}
|
||||
}
|
||||
Ok(json!({"widgets": widgets, "count": count, "truncated": count > widgets.len()}))
|
||||
}
|
||||
|
||||
@@ -14,11 +14,11 @@
|
||||
//! two happened, once, between the UI thread and the transport.
|
||||
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
use std::time::Instant;
|
||||
|
||||
use craft_ui::runtime::motion;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use serde_json::{Value, json};
|
||||
use web_time::Instant;
|
||||
|
||||
use crate::screenshot::{Captures, DocumentId, Finished, ScreenshotParams, ScreenshotRequest, screenshot_reply};
|
||||
use crate::synthetic::TARGET_CHANGED;
|
||||
@@ -112,7 +112,8 @@ pub enum Reply {
|
||||
/// Reply with this JSON now.
|
||||
Done(Value),
|
||||
/// A `ui.screenshot`: admit `token` to the queue; `path` is where the app's write authority
|
||||
/// puts the PNG, `None` inlines it as base64 in the reply.
|
||||
/// puts the PNG, `None` inlines it as base64 in the reply; `region` is refused at admission
|
||||
/// when it lies outside the window.
|
||||
#[non_exhaustive]
|
||||
Screenshot {
|
||||
/// Identifies the capture; must differ from every pending token.
|
||||
@@ -132,8 +133,8 @@ pub enum Reply {
|
||||
}
|
||||
|
||||
impl Reply {
|
||||
/// A `ui.screenshot` reply for `token` of `viewport`, writing the PNG to `path` or inlining it
|
||||
/// when `None`.
|
||||
/// A `ui.screenshot` reply for `token` of `viewport` with what [`ScreenshotParams::from_params`] read: the PNG
|
||||
/// goes to `params.path` or is inlined when `None`, and shows `params.region` or the whole window.
|
||||
pub fn screenshot(token: u64, params: ScreenshotParams, viewport: egui::ViewportId) -> Self {
|
||||
Self::Screenshot { token, path: params.path, region: params.region, viewport }
|
||||
}
|
||||
@@ -199,9 +200,9 @@ impl ControlChannel {
|
||||
}
|
||||
Reply::AfterInput => self.input_waiters.push(reply),
|
||||
Reply::AfterJob(job) => self.job_waiters.push((job, reply)),
|
||||
Reply::Screenshot { token, path, region: _, viewport } => {
|
||||
// P3(pdf-shell-w2): SH-C18 (the request carries the region)
|
||||
if let Err((reply, e)) = self.captures.admit(ScreenshotRequest { token, path, viewport, reply, document, settle_ms }, motion::now()) {
|
||||
Reply::Screenshot { token, path, region, viewport } => {
|
||||
let request = ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms };
|
||||
if let Err((reply, e)) = self.captures.admit(request, motion::now()) {
|
||||
let _ = reply.send(json!({"ok": false, "error": e}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
//! Drive a running Craft app from tests, agents and the CLI, and record and play actions.
|
||||
//!
|
||||
//! [`actions`] and [`ui::actions`] build on every target: the recorded-action list, its player
|
||||
//! and the Actions panel; so do the agent settings in [`agents`]. The rest is desktop only.
|
||||
//! and the Actions panel; so do the agent settings in [`agents`] and, with `ui`, the control
|
||||
//! channel, its screenshots, synthetic input and the access-tree lookups (a web page feeds
|
||||
//! [`control::ControlChannel`] from its own request queue). The server, client, token files,
|
||||
//! profiler and trace are desktop only.
|
||||
//!
|
||||
//! A transport thread ([`server`], or a channel in tests) turns each JSON line into a
|
||||
//! [`control::ControlRequest`]; the UI thread drains them between frames through
|
||||
@@ -22,42 +25,43 @@ pub mod agents;
|
||||
pub mod ui;
|
||||
|
||||
#[cfg(feature = "ui")]
|
||||
pub mod access; // P3(pdf-shell-w2): SH-C15
|
||||
pub mod access;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod args;
|
||||
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
|
||||
pub mod control;
|
||||
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
|
||||
pub mod dialogs;
|
||||
#[cfg(feature = "ui")]
|
||||
pub mod dock; // P3(pdf-shell-w2): CH-C22
|
||||
pub mod control;
|
||||
#[cfg(feature = "ui")]
|
||||
pub mod dialogs;
|
||||
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
|
||||
pub mod files; // P3(pdf-shell-w2): WF-W17
|
||||
pub mod dock;
|
||||
#[cfg(feature = "ui")]
|
||||
pub mod files;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod profiler;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
// The native client reads `REPLY_DEADLINE` without `ui`; the control channel reads the validators on every target.
|
||||
#[cfg(any(feature = "ui", not(target_arch = "wasm32")))]
|
||||
pub mod protocol;
|
||||
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
|
||||
#[cfg(feature = "ui")]
|
||||
pub mod screenshot;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod security;
|
||||
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
|
||||
#[cfg(feature = "ui")]
|
||||
pub mod synthetic;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod trace;
|
||||
#[cfg(feature = "ui")]
|
||||
pub mod window; // P3(pdf-shell-w2): CH-C23
|
||||
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
|
||||
pub mod window;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod client;
|
||||
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
|
||||
pub mod server;
|
||||
|
||||
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
|
||||
#[cfg(feature = "ui")]
|
||||
pub use control::{ControlChannel, ControlRequest, ControlResponse, Dispatch, Reply};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use protocol::REPLY_DEADLINE;
|
||||
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
|
||||
#[cfg(feature = "ui")]
|
||||
pub use screenshot::Captures;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use security::AutomationError;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! `ui.screenshot`: bounded, cancellable capture requests over [`WindowHost::screenshot`].
|
||||
//!
|
||||
//! The slot correlates one capture with one image. This queue owns what the slot leaves to the
|
||||
//! app: request identity (token, output path, reply, the viewport it shoots), deadlines and
|
||||
//! app: request identity (token, output path, reply, the viewport it shoots and the region of it,
|
||||
//! refused at admission when outside the window and cropped in [`screenshot_reply`]), deadlines and
|
||||
//! settling, the admission budget ([`MAX_PENDING`] requests, [`MAX_IMAGE_BYTES`] per image,
|
||||
//! [`MAX_TOTAL_BYTES`] in all), the document identity fixed at admission, each viewport's geometry
|
||||
//! epoch recorded at issue so an image is saved only for the layout it was rendered from (a size,
|
||||
@@ -18,14 +19,16 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::Sender;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine as _;
|
||||
use craft_ui::runtime::windows::{ScreenshotFacts, ScreenshotSlot, WindowHost};
|
||||
use egui::{ColorImage, ViewportId};
|
||||
use egui::{ColorImage, Rect, ViewportId};
|
||||
use serde_json::Value;
|
||||
use web_time::Instant;
|
||||
|
||||
use crate::control::ControlResponse;
|
||||
use crate::protocol::Params;
|
||||
|
||||
/// Requests outstanding at once (issued, completed, waiting for geometry or waiting to be issued).
|
||||
pub const MAX_PENDING: usize = 4;
|
||||
@@ -147,6 +150,7 @@ pub struct PendingCapture {
|
||||
token: u64,
|
||||
viewport: ViewportId,
|
||||
path: Option<String>,
|
||||
region: Option<Rect>,
|
||||
reply: Option<Sender<ControlResponse>>,
|
||||
deadline: Instant,
|
||||
ready_at: Instant,
|
||||
@@ -211,6 +215,8 @@ pub struct ScreenshotRequest {
|
||||
pub token: u64,
|
||||
/// Where to write the PNG, when the reply is a file.
|
||||
pub path: Option<String>,
|
||||
/// The part of the window to capture, in points; `None` captures the whole window.
|
||||
pub region: Option<Rect>,
|
||||
/// The viewport to capture.
|
||||
pub viewport: ViewportId,
|
||||
/// Where the reply goes.
|
||||
@@ -222,9 +228,9 @@ pub struct ScreenshotRequest {
|
||||
}
|
||||
|
||||
impl ScreenshotRequest {
|
||||
/// A request for `viewport` answered on `reply`: no file, no document, no settle delay.
|
||||
/// A request for the whole of `viewport` answered on `reply`: no file, no document, no settle delay.
|
||||
pub fn new(token: u64, viewport: ViewportId, reply: Sender<ControlResponse>) -> Self {
|
||||
Self { token, path: None, viewport, reply, document: None, settle_ms: 0.0 }
|
||||
Self { token, path: None, region: None, viewport, reply, document: None, settle_ms: 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -233,6 +239,7 @@ struct WaitingAdmit {
|
||||
token: u64,
|
||||
viewport: ViewportId,
|
||||
path: Option<String>,
|
||||
region: Option<Rect>,
|
||||
reply: Sender<ControlResponse>,
|
||||
deadline: Instant,
|
||||
settle_ms: f64,
|
||||
@@ -325,17 +332,19 @@ impl Captures {
|
||||
/// `the viewport is not capturable ({w}×{h} points at {ppp} px/pt, texture side {side})`,
|
||||
/// `a {N} MiB screenshot is over the {MAX_IMAGE_BYTES / 1 MiB} MiB per-image limit` (`N` the
|
||||
/// expected bytes / 1 MiB, integer division), or
|
||||
/// `screenshot budget exhausted: {total} bytes reserved of a {MAX_TOTAL_BYTES}-byte aggregate limit`.
|
||||
/// `screenshot budget exhausted: {total} bytes reserved of a {MAX_TOTAL_BYTES}-byte aggregate limit`, or
|
||||
/// `screenshot {token} failed: the region must lie inside the {w}×{h}-point window`. The budget is reserved for
|
||||
/// the whole window, region or not: the slot retains the whole image until it is cropped.
|
||||
/// While the viewport's geometry is not recorded the request waits.
|
||||
pub fn admit(&mut self, request: ScreenshotRequest, now: Instant) -> Result<(), (Sender<ControlResponse>, String)> {
|
||||
let ScreenshotRequest { token, path, viewport, reply, document, settle_ms } = request;
|
||||
let ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms } = request;
|
||||
if self.records.iter().any(|r| r.token == token) || self.waiting.iter().any(|w| w.token == token) {
|
||||
return Err((reply, format!("screenshot token {token} is already pending")));
|
||||
}
|
||||
if self.pending() >= MAX_PENDING {
|
||||
return Err((reply, format!("too many screenshots pending (at most {MAX_PENDING})")));
|
||||
}
|
||||
let request = WaitingAdmit { token, viewport, path, reply, deadline: now + DEADLINE, settle_ms, document };
|
||||
let request = WaitingAdmit { token, viewport, path, region, reply, deadline: now + DEADLINE, settle_ms, document };
|
||||
match self.windows.get(&viewport).copied() {
|
||||
None => {
|
||||
self.waiting.push(request);
|
||||
@@ -348,7 +357,7 @@ impl Captures {
|
||||
|
||||
/// Queues `request` at `geometry` and `epoch`, what its viewport's window recorded.
|
||||
fn admit_with_geometry(&mut self, request: WaitingAdmit, geometry: CaptureGeometry, epoch: u64) -> Result<(), (Sender<ControlResponse>, String)> {
|
||||
let WaitingAdmit { token, viewport, path, reply, deadline, settle_ms, document } = request;
|
||||
let WaitingAdmit { token, viewport, path, region, reply, deadline, settle_ms, document } = request;
|
||||
// The request's clock started when it arrived.
|
||||
let arrived = deadline - DEADLINE;
|
||||
if self.records.iter().any(|r| r.token == token) {
|
||||
@@ -361,6 +370,9 @@ impl Captures {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => return Err((reply, e)),
|
||||
};
|
||||
if let Err(e) = check_region(token, region, &geometry) {
|
||||
return Err((reply, e));
|
||||
}
|
||||
if let Err(e) = aggregate_budget(self.reserved_bytes(), expected) {
|
||||
return Err((reply, e));
|
||||
}
|
||||
@@ -370,6 +382,7 @@ impl Captures {
|
||||
token,
|
||||
viewport,
|
||||
path,
|
||||
region,
|
||||
reply: Some(reply),
|
||||
deadline,
|
||||
ready_at: arrived + Duration::from_secs_f64(settle / 1000.0),
|
||||
@@ -551,8 +564,9 @@ impl Captures {
|
||||
finished.push(Finished {
|
||||
token: w.token,
|
||||
path: w.path,
|
||||
region: None, // P3(pdf-shell-w2): SH-C18
|
||||
geometry: CaptureGeometry::new([0.0, 0.0], 0), // P3(pdf-shell-w2): SH-C18 (a waiting request has none recorded)
|
||||
region: w.region,
|
||||
// No geometry was recorded for a waiting request; the result is an error, so nothing reads it.
|
||||
geometry: CaptureGeometry::new([0.0, 0.0], 0),
|
||||
reply: Some(w.reply),
|
||||
result: Err(format!("screenshot {} cancelled: {reason}", w.token)),
|
||||
});
|
||||
@@ -564,7 +578,7 @@ impl Captures {
|
||||
finished.push(Finished {
|
||||
token: r.token,
|
||||
path: r.path.take(),
|
||||
region: None, // P3(pdf-shell-w2): SH-C18
|
||||
region: r.region,
|
||||
geometry: r.geometry,
|
||||
reply: r.reply.take(),
|
||||
result: Err(format!("screenshot {} cancelled: {reason}", r.token)),
|
||||
@@ -597,11 +611,23 @@ fn aggregate_budget(others: usize, expected: usize) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `region` lies inside the window of `geometry`: the request is refused otherwise, never cropped to a
|
||||
/// smaller image than it asked for. `None` (the whole window) always fits.
|
||||
fn check_region(token: u64, region: Option<Rect>, geometry: &CaptureGeometry) -> Result<(), String> {
|
||||
let Some(region) = region else { return Ok(()) };
|
||||
let [width, height] = geometry.size_points;
|
||||
if region.min.x >= 0.0 && region.min.y >= 0.0 && region.max.x <= width && region.max.y <= height {
|
||||
return Ok(());
|
||||
}
|
||||
Err(format!("screenshot {token} failed: the region must lie inside the {width}×{height}-point window"))
|
||||
}
|
||||
|
||||
/// Finalise a request at a new geometry: recheck the per-image and aggregate limits (excluding
|
||||
/// its old reservation), take the new reservation and restart settling.
|
||||
/// its old reservation) and that its region still fits, take the new reservation and restart settling.
|
||||
fn revalidate_reservation(r: &mut PendingCapture, others: usize, geometry: CaptureGeometry, epoch: u64) -> Result<(), String> {
|
||||
let expected = image_budget(&geometry)?;
|
||||
aggregate_budget(others, expected)?;
|
||||
check_region(r.token, r.region, &geometry)?;
|
||||
r.reserved_bytes = expected;
|
||||
r.geometry = geometry;
|
||||
r.epoch = epoch;
|
||||
@@ -614,7 +640,7 @@ fn finish(r: &mut PendingCapture, result: Result<Arc<ColorImage>, String>) -> Fi
|
||||
if let Some(slot) = r.slot.take() {
|
||||
slot.cancel();
|
||||
}
|
||||
Finished { token: r.token, path: r.path.take(), region: None, geometry: r.geometry, reply: r.reply.take(), result } // P3(pdf-shell-w2): SH-C18 (`region`)
|
||||
Finished { token: r.token, path: r.path.take(), region: r.region, geometry: r.geometry, reply: r.reply.take(), result }
|
||||
}
|
||||
|
||||
/// The returned image must be the issued viewport (within a pixel) or a uniform renderer fit
|
||||
@@ -706,23 +732,63 @@ pub struct ScreenshotParams {
|
||||
}
|
||||
|
||||
impl ScreenshotParams {
|
||||
/// `{path?, region?}`, no other fields.
|
||||
/// `{path?, region?}`, no other fields. `path` is a string; `region` is `[x0, y0, x1, y1]` in points, four finite
|
||||
/// numbers with `x0 < x1` and `y0 < y1`: ``"region must be [x0, y0, x1, y1] in points, finite, with x0 < x1 and
|
||||
/// y0 < y1"`` otherwise. Whether it lies inside the window is checked at admission, against the window's geometry.
|
||||
pub fn from_params(params: &Value) -> Result<ScreenshotParams, String> {
|
||||
let _ = params;
|
||||
todo!("SH-C18")
|
||||
let p = Params(params).only(None, &["path", "region"])?;
|
||||
let p = Params(&p);
|
||||
let path = p.str_field("path")?.map(str::to_owned);
|
||||
let region = p.0.get("region").map(region_param).transpose()?;
|
||||
Ok(ScreenshotParams { path, region })
|
||||
}
|
||||
}
|
||||
|
||||
/// The reply for a finished image:
|
||||
/// - an image over [`MAX_IMAGE_BYTES`] as RGBA (or whose size overflows):
|
||||
/// `region`: `[x0, y0, x1, y1]`, finite and ordered.
|
||||
fn region_param(region: &Value) -> Result<Rect, String> {
|
||||
const SHAPE: &str = "region must be [x0, y0, x1, y1] in points, finite, with x0 < x1 and y0 < y1";
|
||||
let number = |v: &Value| v.as_f64().map(|n| n as f32).filter(|n| n.is_finite());
|
||||
let corners = match region.as_array().map(Vec::as_slice) {
|
||||
Some([x0, y0, x1, y1]) => number(x0).zip(number(y0)).zip(number(x1).zip(number(y1))),
|
||||
_ => None,
|
||||
};
|
||||
corners
|
||||
.filter(|((x0, y0), (x1, y1))| x0 < x1 && y0 < y1)
|
||||
.map(|((x0, y0), (x1, y1))| Rect::from_min_max(egui::pos2(x0, y0), egui::pos2(x1, y1)))
|
||||
.ok_or_else(|| SHAPE.into())
|
||||
}
|
||||
|
||||
/// The pixel columns and rows `[x0, y0, x1, y1)` of `region` in an image of `size` captured at `geometry`. The image
|
||||
/// scale is `size / geometry.size_points`, never `pixels_per_point`: a renderer that fitted the surface to its
|
||||
/// texture side returns a smaller image of the same layout. Edges round to the nearest pixel and are clamped to the
|
||||
/// image; `None` when nothing of the region is left or the geometry has no area.
|
||||
fn crop_pixels(region: Rect, geometry: &CaptureGeometry, size: [usize; 2]) -> Option<[usize; 4]> {
|
||||
let [width, height] = geometry.size_points;
|
||||
if !(width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let (sx, sy) = (size[0] as f32 / width, size[1] as f32 / height);
|
||||
// `as usize` saturates: a negative or NaN edge is 0, an edge past the image is clamped below.
|
||||
let px = |v: f32, scale: f32, max: usize| ((v * scale).round() as usize).min(max);
|
||||
let [x0, x1] = [px(region.min.x, sx, size[0]), px(region.max.x, sx, size[0])];
|
||||
let [y0, y1] = [px(region.min.y, sy, size[1]), px(region.max.y, sy, size[1])];
|
||||
(x0 < x1 && y0 < y1).then_some([x0, y0, x1, y1])
|
||||
}
|
||||
|
||||
/// The reply for a finished image, cropped to `region` (in points; `None` keeps the whole image) at the scale of the
|
||||
/// image to `geometry`, the layout it was captured from:
|
||||
/// - a region with no pixels left in the image:
|
||||
/// `{"ok": false, "error": "screenshot {token} failed: the region has no pixels in the captured image"}`;
|
||||
/// - a crop over [`MAX_IMAGE_BYTES`] as RGBA (or whose size overflows):
|
||||
/// `{"ok": false, "error": "screenshot {token} failed: the image exceeds the {MAX_IMAGE_BYTES / 1 MiB} MiB encode budget"}`;
|
||||
/// - no `path`: `{"ok": true, "result": {"base64": <standard base64 of the PNG>, "mime": "image/png", "width", "height"}}`,
|
||||
/// with no size limit beyond the encode budget;
|
||||
/// - no `path`: `{"ok": true, "result": {"base64": <standard base64 of the PNG>, "mime": "image/png", "width", "height",
|
||||
/// "pixels_per_point"}}`, with no size limit beyond the encode budget;
|
||||
/// - a `path`: the PNG goes to `write(path, bytes)`, the app's file authority (limited to its
|
||||
/// authorized workspace), and the reply is
|
||||
/// `{"ok": true, "result": {"path", "width", "height"}}`;
|
||||
/// `{"ok": true, "result": {"path", "width", "height", "pixels_per_point"}}`;
|
||||
/// - an encode or write error `e`: `{"ok": false, "error": e}`.
|
||||
///
|
||||
/// `width` and `height` are the crop's pixels; `pixels_per_point` is `geometry`'s, the window's scale.
|
||||
/// Flatten the pixels to RGBA and drop the image before encoding, so the two copies don't overlap.
|
||||
pub fn screenshot_reply(
|
||||
token: u64,
|
||||
@@ -732,29 +798,49 @@ pub fn screenshot_reply(
|
||||
path: Option<&str>,
|
||||
write: &mut PngWriter<'_>,
|
||||
) -> ControlResponse {
|
||||
let _ = (region, geometry); // P3(pdf-shell-w2): SH-C18 (the writer crops the image to the region and replies with the geometry's scale)
|
||||
let [w, h] = image.size;
|
||||
let Some(bytes) = w.checked_mul(h).and_then(|n| n.checked_mul(4)).filter(|&n| n <= MAX_IMAGE_BYTES) else {
|
||||
let crop = match region {
|
||||
None => Some([0, 0, w, h]),
|
||||
Some(region) => crop_pixels(region, &geometry, [w, h]),
|
||||
};
|
||||
let Some([x0, y0, x1, y1]) = crop.filter(|[x0, y0, x1, y1]| x0 < x1 && y0 < y1) else {
|
||||
return serde_json::json!({"ok": false, "error": format!("screenshot {token} failed: the region has no pixels in the captured image")});
|
||||
};
|
||||
let (cw, ch) = (x1 - x0, y1 - y0);
|
||||
let Some(bytes) = cw.checked_mul(ch).and_then(|n| n.checked_mul(4)).filter(|&n| n <= MAX_IMAGE_BYTES) else {
|
||||
return serde_json::json!({
|
||||
"ok": false,
|
||||
"error": format!("screenshot {token} failed: the image exceeds the {} MiB encode budget", MAX_IMAGE_BYTES / (1 << 20)),
|
||||
});
|
||||
};
|
||||
let mut rgba = Vec::with_capacity(bytes);
|
||||
rgba.extend(image.pixels.iter().flat_map(|c| c.to_array()));
|
||||
for y in y0..y1 {
|
||||
let row = y.checked_mul(w).and_then(|start| image.pixels.get(start + x0..start + x1));
|
||||
let Some(row) = row else {
|
||||
return serde_json::json!({"ok": false, "error": format!("screenshot {token} failed: the image has fewer pixels than its size")});
|
||||
};
|
||||
rgba.extend(row.iter().flat_map(|c| c.to_array()));
|
||||
}
|
||||
drop(image);
|
||||
let png = match encode_png(w, h, &rgba) {
|
||||
let png = match encode_png(cw, ch, &rgba) {
|
||||
Ok(png) => png,
|
||||
Err(e) => return serde_json::json!({"ok": false, "error": e}),
|
||||
};
|
||||
let ppp = geometry.pixels_per_point;
|
||||
let Some(path) = path else {
|
||||
return serde_json::json!({
|
||||
"ok": true,
|
||||
"result": {"base64": base64::engine::general_purpose::STANDARD.encode(png), "mime": "image/png", "width": w, "height": h},
|
||||
"result": {
|
||||
"base64": base64::engine::general_purpose::STANDARD.encode(png),
|
||||
"mime": "image/png",
|
||||
"width": cw,
|
||||
"height": ch,
|
||||
"pixels_per_point": ppp,
|
||||
},
|
||||
});
|
||||
};
|
||||
match write(path, &png) {
|
||||
Ok(()) => serde_json::json!({"ok": true, "result": {"path": path, "width": w, "height": h}}),
|
||||
Ok(()) => serde_json::json!({"ok": true, "result": {"path": path, "width": cw, "height": ch, "pixels_per_point": ppp}}),
|
||||
Err(e) => serde_json::json!({"ok": false, "error": e}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,11 +271,15 @@ fn token_conflict() -> AutomationError {
|
||||
AutomationError::BadRequest("use either a control token or a control token file, not both".into())
|
||||
}
|
||||
|
||||
/// The most a Windows token file read takes: a token, its newline and room for stray whitespace.
|
||||
#[cfg(windows)]
|
||||
const TOKEN_FILE_MAX_BYTES: u64 = 4096;
|
||||
|
||||
/// Validates what was opened, not just the name: the file must be a regular file that no other
|
||||
/// local principal can read, so a group- or world-readable token is refused rather than trusted.
|
||||
fn read_token_file(path: &Path) -> Result<String, AutomationError> {
|
||||
let io = |e: std::io::Error| AutomationError::Io(format!("{}: {e}", path.display()));
|
||||
let mut file = std::fs::File::open(path).map_err(io)?;
|
||||
let file = std::fs::File::open(path).map_err(io)?;
|
||||
let meta = file.metadata().map_err(io)?;
|
||||
if !meta.is_file() {
|
||||
return Err(AutomationError::Io(format!("{}: control token file is not a regular file", path.display())));
|
||||
@@ -291,7 +295,25 @@ fn read_token_file(path: &Path) -> Result<String, AutomationError> {
|
||||
)));
|
||||
}
|
||||
}
|
||||
let token = std::io::read_to_string(&mut file).map_err(io)?;
|
||||
// A Windows file inherits its folder's access list, so the owner and the access list are read with the contents
|
||||
// through one handle: nothing swapped in at the path between the check and the read gets through.
|
||||
|
||||
#[cfg(windows)]
|
||||
let token = {
|
||||
use craft_platform::owner_only;
|
||||
drop(file);
|
||||
let me = owner_only::current_user_sid().map_err(io)?;
|
||||
let (sddl, bytes) = owner_only::read_with_sddl(path, TOKEN_FILE_MAX_BYTES).map_err(io)?;
|
||||
if let Some(problem) = owner_only::foreign_access(&sddl, &me) {
|
||||
return Err(AutomationError::Io(format!(
|
||||
"{}: control token file can be reached by others: {problem}; restrict it to its owner",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
String::from_utf8(bytes).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let token = std::io::read_to_string(&file).map_err(io)?;
|
||||
let token = token.trim().to_owned();
|
||||
validate_token(&token)?;
|
||||
Ok(token)
|
||||
@@ -309,6 +331,17 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> {
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;
|
||||
// On Windows the new file has its folder's access list: it is restricted to its user and SYSTEM before the token
|
||||
// is written, and a file that cannot be restricted is removed rather than left for the token to go into later.
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use craft_platform::owner_only;
|
||||
if let Err(e) = owner_only::current_user_sid().and_then(|me| owner_only::restrict_to_owner(path, &me)) {
|
||||
drop(file);
|
||||
let _ = std::fs::remove_file(path);
|
||||
return Err(AutomationError::Io(format!("{}: cannot restrict the control token file to its owner: {e}", path.display())));
|
||||
}
|
||||
}
|
||||
writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))
|
||||
}
|
||||
|
||||
@@ -317,10 +350,12 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> {
|
||||
/// validated. Neither given: a generated token. A `token_file` that exists is read: it must be a
|
||||
/// regular file (`I/O: <path>: control token file is not a regular file`) and on Unix have no
|
||||
/// group or other permission bits (`I/O: <path>: control token file is readable by group or
|
||||
/// others (mode {mode & 0o777:o}); restrict it to its owner (e.g. chmod 600)`), and its trimmed
|
||||
/// content is validated. A missing one is created with a generated token (parent directories
|
||||
/// created, `create_new`, mode 0600 on Unix, the token and a newline); losing that create race to
|
||||
/// another process reads the winner's file instead.
|
||||
/// others (mode {mode & 0o777:o}); restrict it to its owner (e.g. chmod 600)`), on Windows be
|
||||
/// owned by the user with an access list of the user and SYSTEM only (`I/O: <path>: control token
|
||||
/// file can be reached by others: <why>; restrict it to its owner`), and its trimmed content is
|
||||
/// validated. A missing one is created with a generated token (parent directories created,
|
||||
/// `create_new`, mode 0600 on Unix, the user and SYSTEM only on Windows, the token and a
|
||||
/// newline); losing that create race to another process reads the winner's file instead.
|
||||
pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result<String, AutomationError> {
|
||||
if supplied.is_some() && token_file.is_some() {
|
||||
return Err(token_conflict());
|
||||
|
||||
@@ -56,7 +56,8 @@ pub fn listen(port: u16, token: String, host: WindowHost) -> std::io::Result<(Re
|
||||
|
||||
/// Serves a listener bound earlier (an app's `--control`, bound before its window opens) until the
|
||||
/// returned [`Listening`] is dropped: authenticates each connection with `token`, forwards its
|
||||
/// requests to the receiver and wakes the root window through `host`. The app prints
|
||||
/// requests to the receiver and wakes the root window through `host`, which keeps each window's access tree
|
||||
/// ([`WindowHost::keep_access_tree`]) for [`crate::access`]. The app prints
|
||||
/// `control server listening on <addr>`.
|
||||
pub fn serve(listener: TcpListener, token: String, host: WindowHost) -> std::io::Result<(Receiver<ControlRequest>, Listening)> {
|
||||
serve_with_deadline(listener, token, host, AUTH_DEADLINE)
|
||||
@@ -73,6 +74,9 @@ pub fn serve_with_deadline(
|
||||
) -> std::io::Result<(Receiver<ControlRequest>, Listening)> {
|
||||
let (tx, rx) = channel::<ControlRequest>();
|
||||
let addr = listener.local_addr()?;
|
||||
// `ui.inspect`, `ui.click {label}` and `ui.focus` read the kept tree of the last presented frame; it is kept
|
||||
// from before the first connection, so the first request already finds it.
|
||||
host.keep_access_tree();
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let stopped = Arc::clone(&stop);
|
||||
let accept = std::thread::Builder::new().name("control server".into()).spawn(move || {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! 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, 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`.
|
||||
//!
|
||||
//! This module reads and validates the protocol's parameters; the window host queues the input
|
||||
//! ([`WindowHost::inject_move`], [`WindowHost::inject_click`], [`WindowHost::inject_wheel`],
|
||||
//! [`WindowHost::inject_key`], [`WindowHost::inject_release`], [`WindowHost::inject_text`],
|
||||
//! [`WindowHost::inject_ime`]), one step per pass, so a move, a press, a release, a key's down and up and each
|
||||
//! [`WindowHost::inject_ime`], [`WindowHost::inject_files`], [`WindowHost::inject_access`]), one step per pass, so a
|
||||
//! move, a press, a release, a key's down and up and each
|
||||
//! composition step land on separate passes as real input does. A request is validated whole before anything of it is
|
||||
//! queued, so a refused one leaves no half-queued press. The host answers the
|
||||
//! waiting replies once [`WindowHost::injected_idle`] turns true ([`crate::control::ControlChannel::poll_input`]), and
|
||||
@@ -17,14 +18,22 @@
|
||||
//! Points are screen points (egui points), or document points with `coordinates: "document"`, which the application
|
||||
//! maps to the screen through its canvas ([`DocumentMap`]). Document-coordinate `ui.pointer` events are the
|
||||
//! application's own method: they drive its tool host, not the window.
|
||||
//!
|
||||
//! 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`.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use craft_behavior::PointerButton;
|
||||
use craft_keymap::{Key, Mods};
|
||||
use craft_ui::runtime::egui::access::Declared;
|
||||
use craft_ui::runtime::windows::{Released, WindowHost};
|
||||
use egui::{Pos2, Vec2, ViewportId, pos2, vec2};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::access::NodeTarget;
|
||||
use crate::access::{NO_TREE, NodeTarget, resolve};
|
||||
use crate::protocol::{BUTTONS, KEY_MODIFIERS, Params};
|
||||
|
||||
/// Most clicks one `ui.click` may ask for (`count`).
|
||||
@@ -135,19 +144,27 @@ pub struct Focus {
|
||||
}
|
||||
|
||||
impl Focus {
|
||||
/// `{id | label}`: the node to focus.
|
||||
/// `{id | label}`: the node to focus, exactly one of the two, no other fields (``"missing `id` or `label`"``).
|
||||
pub fn from_params(params: &Value) -> Result<Focus, String> {
|
||||
let _ = params;
|
||||
todo!("SH-C16")
|
||||
let p = Params(params).only(None, &["id", "label"])?;
|
||||
NodeTarget::from_params(&p)?.map(|target| Focus { target }).ok_or_else(|| "missing `id` or `label`".into())
|
||||
}
|
||||
|
||||
/// Sends the focus request for the node to `viewport`.
|
||||
/// Queues the focus request for the node in `viewport`; a node the kept tree does not have as one reported,
|
||||
/// enabled, focusable node is refused ([`resolve`]).
|
||||
pub fn inject(&self, host: &WindowHost, viewport: ViewportId) -> Result<(), String> {
|
||||
let _ = (host, viewport);
|
||||
todo!("SH-C16")
|
||||
inject_node(host, viewport, &self.target, Declared::Focus)
|
||||
}
|
||||
}
|
||||
|
||||
/// Queues `action` on the node `target` names in `viewport`'s kept access tree.
|
||||
fn inject_node(host: &WindowHost, viewport: ViewportId, target: &NodeTarget, action: Declared) -> Result<(), String> {
|
||||
let tree = host.access_tree(viewport).ok_or_else(|| NO_TREE.to_owned())?;
|
||||
let node = resolve(&tree, target, action)?;
|
||||
host.inject_access(viewport, node, action);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A validated `ui.click`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
@@ -165,31 +182,60 @@ pub struct Click {
|
||||
}
|
||||
|
||||
impl Click {
|
||||
/// `{x?, y?, coordinates?, button?, count?, hold?, modifiers…}`, no other fields (`Params::only`). `button`
|
||||
/// defaults to `left`. `count` is an unsigned integer, default 1; over [`MAX_CLICKS`] is
|
||||
/// ``"`count` must be at most 256 (got {count})"``. Other errors are the `Params` validators'.
|
||||
/// `{x?, y?, coordinates?, button?, count?, hold?, modifiers…}` for a point, or `{id | label, button?}` for a node
|
||||
/// of the access tree ([`NodeTarget::from_params`]); no other fields (`Params::only`). `button` defaults to
|
||||
/// `left`. `count` is an unsigned integer, default 1; over [`MAX_CLICKS`] is
|
||||
/// ``"`count` must be at most 256 (got {count})"``. A node is clicked by its own action, so with one only the
|
||||
/// primary button (its click) and the secondary one (its context menu) are allowed, and a point, `count` above 1,
|
||||
/// `hold` and held modifiers are refused. Other errors are the `Params` validators'.
|
||||
pub fn from_params(params: &Value) -> Result<Self, String> {
|
||||
let p = only(params, &["button", "count", "hold"])?;
|
||||
let p = only(params, &["button", "count", "hold", "id", "label"])?;
|
||||
let p = Params(&p);
|
||||
let count = p.uint_field("count")?.unwrap_or(1);
|
||||
if count > MAX_CLICKS {
|
||||
return Err(format!("`count` must be at most {MAX_CLICKS} (got {count})"));
|
||||
}
|
||||
Ok(Self {
|
||||
target: ClickTarget::At(At::from_params(&p)?), // P3(pdf-shell-w2): SH-C16
|
||||
button: button(&p)?.unwrap_or(PointerButton::Primary),
|
||||
count,
|
||||
mods: p.modifiers(&KEY_MODIFIERS)?,
|
||||
hold: p.bool_field("hold")?.unwrap_or(false),
|
||||
})
|
||||
let pressed = button(&p)?;
|
||||
let mods = p.modifiers(&KEY_MODIFIERS)?;
|
||||
let hold = p.bool_field("hold")?.unwrap_or(false);
|
||||
if let Some(node) = NodeTarget::from_params(p.0)? {
|
||||
if POINT.iter().any(|field| p.0.get(field).is_some()) {
|
||||
return Err("a click names a node (`id` or `label`) or a point (`x`, `y`), not both".into());
|
||||
}
|
||||
if count > 1 {
|
||||
return Err("`count` goes with a point, not a node".into());
|
||||
}
|
||||
if hold {
|
||||
return Err("`hold` goes with a point, not a node".into());
|
||||
}
|
||||
if !mods.is_none() {
|
||||
return Err("modifiers go with a point, not a node".into());
|
||||
}
|
||||
let button = match pressed {
|
||||
None | Some(PointerButton::Primary) => PointerButton::Primary,
|
||||
Some(PointerButton::Secondary) => PointerButton::Secondary,
|
||||
Some(_) => return Err("a node takes a primary or a secondary click, not the middle button".into()),
|
||||
};
|
||||
return Ok(Self { target: ClickTarget::Node(node), button, count: 1, mods, hold: false });
|
||||
}
|
||||
Ok(Self { target: ClickTarget::At(At::from_params(&p)?), button: pressed.unwrap_or(PointerButton::Primary), count, mods, hold })
|
||||
}
|
||||
|
||||
/// Queues a move to the target, then `count` presses and releases of the button, in `viewport`.
|
||||
/// Queues a move to the point, then `count` presses and releases of the button, in `viewport`; for a node, its
|
||||
/// click, or its context menu for the secondary button, once the kept tree has it as one reported, enabled node
|
||||
/// that declares the action ([`resolve`]).
|
||||
pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> {
|
||||
let count = u32::try_from(self.count).unwrap_or(u32::MAX);
|
||||
let ClickTarget::At(at) = &self.target else { todo!("SH-C16") }; // P3(pdf-shell-w2): SH-C16
|
||||
host.inject_click(viewport, at.resolve(map)?, self.button, count, self.mods, self.hold);
|
||||
Ok(())
|
||||
match &self.target {
|
||||
ClickTarget::At(at) => {
|
||||
let count = u32::try_from(self.count).unwrap_or(u32::MAX);
|
||||
host.inject_click(viewport, at.resolve(map)?, self.button, count, self.mods, self.hold);
|
||||
Ok(())
|
||||
}
|
||||
ClickTarget::Node(node) => {
|
||||
let action = if matches!(self.button, PointerButton::Secondary) { Declared::ContextMenu } else { Declared::Click };
|
||||
inject_node(host, viewport, node, action)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,6 +381,8 @@ pub fn caps_lock_from_params(params: &Value) -> Result<Option<bool>, String> {
|
||||
pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Option<Result<(), String>> {
|
||||
Some(match method {
|
||||
"ui.click" => Click::from_params(params).and_then(|click| click.inject(host, viewport, map)),
|
||||
"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.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)),
|
||||
@@ -346,6 +394,32 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V
|
||||
})
|
||||
}
|
||||
|
||||
/// `ui.drop {paths, hover_only?, x?, y?, coordinates?}`: hovers the files `paths` names (a non-empty array of
|
||||
/// strings) over the point, where the pointer is when neither `x` nor `y` is given, and drops them in the following
|
||||
/// step unless `hover_only`. The point is mapped as every request's is; a drop carries no modifiers, so a held one is
|
||||
/// refused.
|
||||
fn drop_files(params: &Value, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> {
|
||||
const PATHS: &str = "paths must be a non-empty array of strings";
|
||||
let p = only(params, &["paths", "hover_only"])?;
|
||||
let p = Params(&p);
|
||||
if !p.modifiers(&KEY_MODIFIERS)?.is_none() {
|
||||
return Err("`ui.drop` takes no modifiers".into());
|
||||
}
|
||||
let paths: Vec<PathBuf> = match p.0.get("paths") {
|
||||
None => return Err("missing `paths`".into()),
|
||||
Some(Value::Array(items)) => items.iter().map(|item| item.as_str().map(PathBuf::from)).collect::<Option<_>>().ok_or(PATHS)?,
|
||||
Some(_) => return Err(PATHS.into()),
|
||||
};
|
||||
if paths.is_empty() {
|
||||
return Err(PATHS.into());
|
||||
}
|
||||
let hover_only = p.bool_field("hover_only")?.unwrap_or(false);
|
||||
let at = (p.0.get("x").is_some() || p.0.get("y").is_some()).then(|| At::from_params(&p)).transpose()?;
|
||||
let at = at.map(|at| at.resolve(map)).transpose()?;
|
||||
host.inject_files(viewport, at, paths, !hover_only);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A validated `ui.type`: `{text}`, a string.
|
||||
fn text(params: &Value) -> Result<String, String> {
|
||||
let p = Params(params).only(None, &["text"])?;
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
//! `ui.inspect` over the window's kept access tree, and `ui.click` and `ui.focus` on a node it names: tree order and
|
||||
//! filters, what an open modal hides, a click, a context menu and a focus reaching their widget, and the targets
|
||||
//! refused before anything is queued.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_automation::access::{NodeTarget, inspect, resolve};
|
||||
use craft_automation::synthetic::input_method;
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::dialog::Dialog;
|
||||
use craft_ui::menu::{Menu, MenuItem};
|
||||
use craft_ui::runtime::egui::access::Declared;
|
||||
use craft_ui::runtime::egui::injected::hook_without_pass;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use craft_ui::sections::{DialogRole, FooterButton};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui::text::TextField;
|
||||
use egui::{Pos2, ViewportId};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The listed widgets of `params`, from the window's kept tree.
|
||||
fn listed(host: &WindowHost, params: Value) -> Value {
|
||||
inspect(host, ViewportId::ROOT, ¶ms).expect("an inspect reply")
|
||||
}
|
||||
|
||||
/// The labels of a reply's widgets, in its order.
|
||||
fn labels(reply: &Value) -> Vec<String> {
|
||||
reply["widgets"].as_array().into_iter().flatten().filter_map(|w| w["label"].as_str().map(str::to_owned)).collect()
|
||||
}
|
||||
|
||||
/// The widget of a reply labelled `label`.
|
||||
fn widget<'a>(reply: &'a Value, label: &str) -> &'a Value {
|
||||
reply["widgets"].as_array().into_iter().flatten().find(|w| w["label"] == label).unwrap_or_else(|| panic!("{label} is listed: {reply}"))
|
||||
}
|
||||
|
||||
/// Where `label` sits in `order`.
|
||||
fn place(order: &[String], label: &str) -> usize {
|
||||
order.iter().position(|l| l == label).unwrap_or_else(|| panic!("{label} is listed in {order:?}"))
|
||||
}
|
||||
|
||||
/// Every reported node is listed once in tree order with its state, the root left out; `query`, `role` and `focused`
|
||||
/// keep a subset, `limit` cuts the list but not the count; a node behind an open modal is neither listed nor
|
||||
/// resolved, and the modal's own buttons are.
|
||||
#[trial]
|
||||
fn inspect_lists_reported_nodes_in_tree_order_with_their_filters() {
|
||||
let open = Rc::new(Cell::new(false));
|
||||
let (shown, name) = (open.clone(), Rc::new(RefCell::new(String::from("Draft"))));
|
||||
let mut fx = Fixture::new(move |ui| {
|
||||
Button::new("Open").show(ui);
|
||||
Button::new("Save").show(ui);
|
||||
Button::new("Archive").enabled(false).show(ui);
|
||||
TextField::new("Name", Bind::bound(&mut *name.borrow_mut())).show(ui);
|
||||
let mut now = shown.get();
|
||||
Dialog::new("Options").opened(Bind::bound(&mut now)).buttons([FooterButton::new("Apply", DialogRole::Accept)]).show(ui, |_, _| {});
|
||||
shown.set(now);
|
||||
});
|
||||
let host = WindowHost::of(fx.ctx());
|
||||
host.keep_access_tree();
|
||||
fx.settle();
|
||||
|
||||
let all = listed(&host, json!({}));
|
||||
let order = labels(&all);
|
||||
assert!(place(&order, "Open") < place(&order, "Save") && place(&order, "Save") < place(&order, "Archive"), "tree order: {order:?}");
|
||||
let widgets = all["widgets"].as_array().expect("a widget list");
|
||||
assert_eq!(all["count"].as_u64(), Some(widgets.len() as u64), "{all}");
|
||||
assert_eq!(all["truncated"], false);
|
||||
assert!(widgets.iter().all(|w| w["depth"].as_u64().is_some_and(|depth| depth >= 1)), "the root is not listed: {all}");
|
||||
let ids: Vec<&str> = widgets.iter().filter_map(|w| w["id"].as_str()).collect();
|
||||
assert!(ids.iter().enumerate().all(|(i, id)| !ids[..i].contains(id)), "each node once: {ids:?}");
|
||||
let (save, archive) = (widget(&all, "Save"), widget(&all, "Archive"));
|
||||
assert!(save["enabled"] == true && save["clickable"] == true, "{save}");
|
||||
assert!(archive["enabled"] == false, "{archive}");
|
||||
let rect = |w: &Value| w["rect"].as_array().map(|r| r.iter().filter_map(Value::as_f64).collect::<Vec<_>>()).expect("a rect");
|
||||
assert!(rect(widget(&all, "Open"))[3] <= rect(save)[1] + 0.5, "Open lies above Save");
|
||||
|
||||
let queried = listed(&host, json!({"query": "SAV"}));
|
||||
assert!(labels(&queried).contains(&"Save".to_owned()) && !labels(&queried).contains(&"Open".to_owned()), "{queried}");
|
||||
let buttons = listed(&host, json!({"role": "button"}));
|
||||
assert!(["Open", "Save", "Archive"].iter().all(|label| labels(&buttons).contains(&(*label).to_owned())), "{buttons}");
|
||||
assert!(buttons["widgets"].as_array().into_iter().flatten().all(|w| w["role"].as_str().is_some_and(|role| role.eq_ignore_ascii_case("button"))));
|
||||
let fields = listed(&host, json!({"role": "textinput"}));
|
||||
assert_eq!(fields["count"], 1, "the one text field, its role matched ignoring case: {fields}");
|
||||
assert!(buttons["widgets"].as_array().into_iter().flatten().all(|w| w["id"] != fields["widgets"][0]["id"]), "the field is no button");
|
||||
|
||||
let (focused, unfocused) = (listed(&host, json!({"focused": true})), listed(&host, json!({"focused": false})));
|
||||
assert_eq!(focused["count"].as_u64().unwrap_or(0) + unfocused["count"].as_u64().unwrap_or(0), all["count"].as_u64().unwrap_or(0));
|
||||
assert!(focused["widgets"].as_array().into_iter().flatten().all(|w| w["focused"] == true), "{focused}");
|
||||
|
||||
let first = listed(&host, json!({"limit": 1}));
|
||||
assert_eq!(first["widgets"].as_array().map(Vec::len), Some(1));
|
||||
assert_eq!((first["count"].clone(), first["truncated"].clone()), (all["count"].clone(), json!(true)));
|
||||
assert_eq!(first["widgets"][0], all["widgets"][0], "the limit keeps the first in tree order");
|
||||
assert!(inspect(&host, ViewportId::ROOT, &json!({"nodes": true})).is_err(), "an unknown field is refused");
|
||||
|
||||
open.set(true);
|
||||
fx.idle(30);
|
||||
let tree = host.access_tree(ViewportId::ROOT).expect("the kept tree");
|
||||
let behind = listed(&host, json!({}));
|
||||
assert!(!labels(&behind).contains(&"Open".to_owned()), "a node behind the modal is not listed: {behind}");
|
||||
assert!(labels(&behind).contains(&"Apply".to_owned()), "the modal's own button is: {behind}");
|
||||
assert!(resolve(&tree, &NodeTarget::Label("Open".into()), Declared::Click).is_err(), "nor is it resolved");
|
||||
assert!(resolve(&tree, &NodeTarget::Label("apply".into()), Declared::Click).is_ok(), "a label matches ignoring case");
|
||||
}
|
||||
|
||||
/// A click by label activates its button once; a secondary click opens the node's context menu; a focus by the id
|
||||
/// `ui.inspect` lists moves the key focus there. A missing, ambiguous, disabled or undeclared target is refused and
|
||||
/// queues nothing.
|
||||
#[trial]
|
||||
fn click_and_focus_by_label_or_id_reach_the_widget_and_refuse_what_they_cannot_name() {
|
||||
let saves = Rc::new(Cell::new(0));
|
||||
let (counted, name) = (saves.clone(), Rc::new(RefCell::new(String::new())));
|
||||
let mut fx = Fixture::new(move |ui| {
|
||||
if Button::new("Save").show(ui).clicked() {
|
||||
counted.set(counted.get() + 1);
|
||||
}
|
||||
let layer = Button::new("Layer").show(ui);
|
||||
Menu::context("Layer menu", &layer).show(ui, |ui, _| {
|
||||
MenuItem::new("Delete layer").show(ui);
|
||||
});
|
||||
Button::new("Copy").id_salt("first copy").show(ui);
|
||||
Button::new("Copy").id_salt("second copy").show(ui);
|
||||
Button::new("Archive").enabled(false).show(ui);
|
||||
TextField::new("Name", Bind::bound(&mut *name.borrow_mut())).show(ui);
|
||||
});
|
||||
let (host, ctx) = (WindowHost::of(fx.ctx()), fx.ctx().clone());
|
||||
host.keep_access_tree();
|
||||
fx.settle();
|
||||
let none = |_: Pos2| None;
|
||||
let send = |fx: &mut Fixture, method: &str, params: Value| {
|
||||
input_method(method, ¶ms, &host, ViewportId::ROOT, &none).expect("an input method").expect("a target it can name");
|
||||
fx.run_injected().settle();
|
||||
};
|
||||
|
||||
send(&mut fx, "ui.click", json!({"label": "save"}));
|
||||
assert_eq!(saves.get(), 1, "the click by label activated Save once");
|
||||
|
||||
let field = listed(&host, json!({"role": "TextInput"}))["widgets"][0]["id"].clone();
|
||||
assert!(field.is_string(), "the text field is listed with its id");
|
||||
let before = listed(&host, json!({"focused": true}));
|
||||
assert!(before["widgets"].as_array().into_iter().flatten().all(|w| w["id"] != field), "the field has no focus yet: {before}");
|
||||
send(&mut fx, "ui.focus", json!({"id": field}));
|
||||
let focused = listed(&host, json!({"focused": true}));
|
||||
assert_eq!(focused["widgets"].as_array().map(|w| w.iter().map(|w| w["id"].clone()).collect::<Vec<_>>()), Some(vec![field]), "{focused}");
|
||||
|
||||
// Refused while no popup is open, so each is refused for what it names, not for a covered window.
|
||||
let refused = [
|
||||
("ui.click", json!({"label": "Nothing here"})),
|
||||
("ui.click", json!({"id": "1"})),
|
||||
("ui.click", json!({"label": "copy"})),
|
||||
("ui.click", json!({"label": "Archive"})),
|
||||
("ui.click", json!({"label": "Save", "button": "secondary"})),
|
||||
("ui.focus", json!({"label": "Nothing here"})),
|
||||
];
|
||||
for (method, params) in refused {
|
||||
let answer = input_method(method, ¶ms, &host, ViewportId::ROOT, &none);
|
||||
assert!(matches!(answer, Some(Err(_))), "{method} {params} is refused: {answer:?}");
|
||||
assert!(host.injected_idle(), "{method} {params} left nothing waiting");
|
||||
assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "{method} {params} queued nothing");
|
||||
}
|
||||
fx.settle();
|
||||
assert_eq!(saves.get(), 1, "no refused request clicked");
|
||||
|
||||
assert_eq!(listed(&host, json!({"query": "Delete layer"}))["count"], 0, "the menu starts closed");
|
||||
send(&mut fx, "ui.click", json!({"label": "Layer", "button": "secondary"}));
|
||||
assert!(listed(&host, json!({"query": "Delete layer"}))["count"].as_u64().is_some_and(|n| n >= 1), "the context menu opened");
|
||||
assert_eq!(saves.get(), 1, "nothing else was clicked");
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `ControlChannel` deadlines and the loopback server's limits.
|
||||
//! `ControlChannel` deadlines and the loopback server's limits: connections, request size, authentication.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::{SocketAddr, TcpListener, TcpStream};
|
||||
@@ -8,7 +8,7 @@ use std::time::Duration;
|
||||
use craft_automation::client::ControlClient;
|
||||
use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse, Reply, expired_error, result_reply, timeout_error};
|
||||
use craft_automation::protocol::MAX_RESPONSE_BYTES;
|
||||
use craft_automation::security::{CHALLENGE_METHOD, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches};
|
||||
use craft_automation::security::{CHALLENGE_METHOD, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches};
|
||||
use craft_automation::server;
|
||||
use craft_ui::runtime::motion;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
@@ -123,6 +123,69 @@ fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() {
|
||||
assert!(rx.try_recv().is_err(), "nothing was dispatched");
|
||||
}
|
||||
|
||||
/// Whether the server closed the connection: the next read is the end of the stream, not a timeout or an error.
|
||||
fn is_closed(reader: &mut impl BufRead) -> bool {
|
||||
let mut line = String::new();
|
||||
matches!(reader.read_line(&mut line), Ok(0))
|
||||
}
|
||||
|
||||
/// With `MAX_CONNECTIONS` connections open, the next one is told `connection limit reached` and closed; once one of
|
||||
/// the open ones ends, its place serves a new connection.
|
||||
#[trial]
|
||||
fn connections_past_the_limit_are_refused_with_the_reason() {
|
||||
let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started");
|
||||
let connect = || {
|
||||
let stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
(stream, reader)
|
||||
};
|
||||
// Unauthenticated, so each holds its place until it closes or the authentication deadline passes.
|
||||
let mut open: Vec<TcpStream> = (0..MAX_CONNECTIONS).map(|_| connect().0).collect();
|
||||
|
||||
let (_extra, mut reader) = connect();
|
||||
let refused = read_json(&mut reader).expect("a refusal");
|
||||
assert_eq!(refused, json!({"id": null, "ok": false, "error": "connection limit reached"}));
|
||||
assert!(is_closed(&mut reader), "the refused connection is closed");
|
||||
|
||||
drop(open.pop());
|
||||
// The server frees the place when it reads the close; a new connection is served once it has.
|
||||
let started = motion::now();
|
||||
let served = loop {
|
||||
let (mut stream, mut reader) = connect();
|
||||
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written");
|
||||
let reply = read_json(&mut reader).expect("a reply");
|
||||
if reply["ok"] == true || started.elapsed() > Duration::from_secs(5) {
|
||||
break reply;
|
||||
}
|
||||
assert_eq!(reply["error"], "connection limit reached", "{reply}");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
assert_eq!(served["result"]["authenticated"], true, "the freed place serves: {served}");
|
||||
assert!(rx.try_recv().is_err(), "nothing was dispatched");
|
||||
drop(open);
|
||||
}
|
||||
|
||||
/// A first frame that is not JSON, and one with a wrong token, each get the `authentication required` refusal and the
|
||||
/// connection closes at once, without waiting for the deadline and without dispatching anything: a client cannot keep
|
||||
/// guessing on one connection.
|
||||
#[trial]
|
||||
fn a_refused_first_frame_closes_the_connection() {
|
||||
let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started");
|
||||
let wrong = "f".repeat(TOKEN.len());
|
||||
for (first, id) in [("not json".to_owned(), Value::Null), (json!({"id": 4, "method": "auth", "params": {"token": wrong}}).to_string(), json!(4))] {
|
||||
let mut stream = TcpStream::connect(server.addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
writeln!(stream, "{first}").expect("written");
|
||||
assert_eq!(read_json(&mut reader).expect("a refusal"), json!({"id": id, "ok": false, "error": "authentication required"}), "{first}");
|
||||
// The server may already have closed while this is written.
|
||||
let _ = writeln!(stream, "{}", json!({"id": 5, "method": "auth", "params": {"token": TOKEN}}));
|
||||
assert!(is_closed(&mut reader), "{first}: the connection is closed, the second guess unanswered");
|
||||
}
|
||||
assert!(rx.try_recv().is_err(), "nothing was dispatched");
|
||||
}
|
||||
|
||||
/// A request line over `MAX_REQUEST_BYTES` without a newline gets an error reply and the connection is closed.
|
||||
#[trial]
|
||||
fn an_over_long_request_is_refused_and_closes_the_connection() {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Unwrapping, expecting and panicking on failure is fine in tests, unlike in shipped code.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
mod access;
|
||||
mod actions;
|
||||
mod agents;
|
||||
mod control;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! `Captures`: admission budgets, settling, deadlines, cancellation, document identity, the
|
||||
//! geometry epoch per viewport, the window a capture names, and the image checks.
|
||||
//! geometry epoch per viewport, the window a capture names, the image checks, and the region a
|
||||
//! reply is cropped to.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Arc;
|
||||
@@ -396,6 +397,98 @@ fn the_image_must_match_the_issued_viewport() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The first pixel of a PNG, decoded.
|
||||
fn first_pixel(png: &[u8]) -> [u8; 4] {
|
||||
let mut reader = png::Decoder::new(std::io::Cursor::new(png)).read_info().expect("a PNG");
|
||||
let mut pixels = vec![0; reader.output_buffer_size()];
|
||||
reader.next_frame(&mut pixels).expect("a frame");
|
||||
[pixels[0], pixels[1], pixels[2], pixels[3]]
|
||||
}
|
||||
|
||||
/// A region is checked against the window at admission (and again when the layout changed before issue) and refused
|
||||
/// when it does not lie inside; the whole window is reserved for it. The reply crops it at the image's own scale to
|
||||
/// the window, so a fitted image is cropped at its fit, and both reply shapes carry the window's point scale.
|
||||
#[trial]
|
||||
fn a_region_is_cropped_at_the_image_scale_and_one_outside_the_window_is_refused() {
|
||||
use craft_automation::control::ControlChannel;
|
||||
use craft_automation::screenshot::ScreenshotParams;
|
||||
use serde_json::json;
|
||||
|
||||
let params = |value| ScreenshotParams::from_params(&value);
|
||||
let region = Rect::from_min_max(Pos2::new(10.0, 5.0), Pos2::new(60.0, 30.0));
|
||||
assert_eq!(params(json!({"path": "a.png", "region": [10, 5, 60, 30]})).map(|p| (p.path, p.region)), Ok((Some("a.png".to_owned()), Some(region))));
|
||||
for bad in [json!({"region": [60, 5, 10, 30]}), json!({"region": [10, 5, 60]}), json!({"region": [10, 5, 60, "30"]}), json!({"zoom": 2})] {
|
||||
assert!(params(bad.clone()).is_err(), "{bad} is refused");
|
||||
}
|
||||
|
||||
let ctx = Context::default();
|
||||
let now = motion::now();
|
||||
let (_transport, requests) = channel();
|
||||
let mut control = ControlChannel::new(requests);
|
||||
let mut g = geometry(100.0, 50.0);
|
||||
g.pixels_per_point = 2.0;
|
||||
control.captures.note_geometry(ViewportId::ROOT, g);
|
||||
let request = |token: u64, region: Rect| {
|
||||
let (tx, rx) = channel();
|
||||
let mut request = ScreenshotRequest::new(token, ViewportId::ROOT, tx);
|
||||
request.region = Some(region);
|
||||
(request, rx)
|
||||
};
|
||||
|
||||
let (outside, _) = request(1, Rect::from_min_max(Pos2::new(90.0, 40.0), Pos2::new(110.0, 60.0)));
|
||||
let e = control.captures.admit(outside, now).map_err(|(_, e)| e).expect_err("outside the window");
|
||||
assert!(e.contains("inside"), "{e}");
|
||||
assert_eq!(control.captures.pending(), 0);
|
||||
|
||||
let (inside, rx) = request(2, region);
|
||||
control.captures.admit(inside, now).map_err(|(_, e)| e).expect("inside the window");
|
||||
assert_eq!(control.captures.reserved_bytes(), 200 * 100 * 4, "the whole window is reserved");
|
||||
let mut picture = ColorImage::filled([200, 100], Color32::BLUE);
|
||||
picture.pixels[10 * 200 + 20] = Color32::RED;
|
||||
issue_one(&mut control.captures, &ctx, now).complete(Arc::new(picture));
|
||||
let finished = control.captures.drain(now, None);
|
||||
let mut written = Vec::new();
|
||||
control.finish_captures(finished, &mut |_, bytes| {
|
||||
written = bytes.to_vec();
|
||||
Ok(())
|
||||
});
|
||||
let reply = rx.try_recv().expect("a reply");
|
||||
assert_eq!((reply["result"]["width"].clone(), reply["result"]["height"].clone()), (json!(100), json!(50)), "{reply}");
|
||||
assert_eq!(reply["result"]["pixels_per_point"], 2.0);
|
||||
assert!(written.is_empty(), "no path, no file");
|
||||
use base64::Engine as _;
|
||||
let png = base64::engine::general_purpose::STANDARD.decode(reply["result"]["base64"].as_str().expect("an inline PNG")).expect("base64");
|
||||
assert_eq!(first_pixel(&png), Color32::RED.to_array(), "the crop starts at the region's corner at two pixels per point");
|
||||
|
||||
// A fitted surface: 600×300 points through a 400-pixel texture side come back as 400×200.
|
||||
let mut fitted = geometry(600.0, 300.0);
|
||||
fitted.max_texture_side = 400;
|
||||
control.captures.note_geometry(ViewportId::ROOT, fitted);
|
||||
let (mut half, rx) = request(3, Rect::from_min_max(Pos2::new(300.0, 150.0), Pos2::new(600.0, 300.0)));
|
||||
half.path = Some("half.png".into());
|
||||
control.captures.admit(half, now).map_err(|(_, e)| e).expect("inside the window");
|
||||
issue_one(&mut control.captures, &ctx, now).complete(filled([400, 200], Color32::WHITE));
|
||||
let finished = control.captures.drain(now, None);
|
||||
control.finish_captures(finished, &mut |path, bytes| {
|
||||
assert_eq!(path, "half.png");
|
||||
written = bytes.to_vec();
|
||||
Ok(())
|
||||
});
|
||||
let reply = rx.try_recv().expect("a reply");
|
||||
assert_eq!((reply["result"]["width"].clone(), reply["result"]["height"].clone()), (json!(200), json!(100)), "{reply}");
|
||||
assert_eq!(reply["result"]["pixels_per_point"], 1.0);
|
||||
assert!(!written.is_empty(), "the PNG went to the writer");
|
||||
|
||||
// A region that a shrink before issue leaves outside is refused then, not cut to a smaller picture.
|
||||
let (late, _reply) = request(4, region);
|
||||
control.captures.admit(late, now).map_err(|(_, e)| e).expect("inside the window");
|
||||
control.captures.note_geometry(ViewportId::ROOT, geometry(40.0, 20.0));
|
||||
let (finished, callbacks) = settle_and_issue(&mut control.captures, &ctx, now, None);
|
||||
assert!(callbacks.is_empty(), "nothing is captured for it");
|
||||
assert!(finished.len() == 1 && error(&finished[0]).contains("inside"), "refused at issue");
|
||||
assert_eq!(control.captures.pending(), 0);
|
||||
}
|
||||
|
||||
const ROOT_SIZE: Vec2 = Vec2::new(800.0, 600.0);
|
||||
const CHILD_SIZE: Vec2 = Vec2::new(400.0, 300.0);
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
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, Click, Focus, MAX_CLICKS, 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;
|
||||
@@ -264,7 +264,8 @@ fn queued_input_is_withdrawn_when_its_target_changes() {
|
||||
}
|
||||
|
||||
/// An unknown field, a wrong type, an unknown name, too many clicks or a point too far out refuses the whole request
|
||||
/// before any of it is queued: no half-queued press or held key is left behind.
|
||||
/// before any of it is queued: no half-queued press or held key is left behind. A node target takes no point, repeat,
|
||||
/// hold, modifier or button but the secondary one, and names exactly one of `id` and `label`.
|
||||
#[trial]
|
||||
fn bad_input_params_are_refused_before_anything_is_queued() {
|
||||
let mut rig = Rig::new();
|
||||
@@ -285,13 +286,84 @@ fn bad_input_params_are_refused_before_anything_is_queued() {
|
||||
("ui.key", json!({"key": 5})),
|
||||
("ui.key", json!({"key": "NoSuchKey", "hold": true})),
|
||||
("ui.ime", json!({"preedit": "ab", "cursor": [1, 9]})),
|
||||
("ui.click", json!({"x": 10, "y": 10, "label": "Save"})),
|
||||
("ui.click", json!({"label": "Save", "count": 2})),
|
||||
("ui.click", json!({"label": "Save", "hold": true})),
|
||||
("ui.click", json!({"label": "Save", "shift": true})),
|
||||
("ui.click", json!({"label": "Save", "button": "middle"})),
|
||||
("ui.click", json!({"id": "12", "button": "middle"})),
|
||||
("ui.click", json!({"id": "twelve"})),
|
||||
("ui.focus", json!({"id": "12", "label": "Save"})),
|
||||
("ui.focus", json!({})),
|
||||
("ui.drop", json!({"paths": []})),
|
||||
("ui.drop", json!({"paths": ["a.pdf"], "alt": true})),
|
||||
];
|
||||
for (method, params) in refused {
|
||||
let answer = input_method(method, ¶ms, &host, ViewportId::ROOT, &map);
|
||||
for (method, params) in &refused {
|
||||
let answer = input_method(method, params, &host, ViewportId::ROOT, &map);
|
||||
assert!(matches!(answer, Some(Err(_))), "{method} {params} is refused: {answer:?}");
|
||||
assert!(host.injected_idle(), "{method} {params} left nothing waiting");
|
||||
assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "{method} {params} queued nothing");
|
||||
}
|
||||
// This window keeps no access tree, so a node request is refused there whatever it says; its parameters alone
|
||||
// refuse the node rows, and the secondary button, a node's context menu, is allowed.
|
||||
for (method, params) in refused.iter().filter(|(_, params)| params.get("id").is_some() || params.get("label").is_some() || params == &json!({})) {
|
||||
let by_params = if *method == "ui.focus" { Focus::from_params(params).is_err() } else { Click::from_params(params).is_err() };
|
||||
assert!(by_params, "{method} {params} is refused by its parameters");
|
||||
}
|
||||
assert!(Click::from_params(&json!({"label": "Save", "button": "secondary"})).is_ok());
|
||||
}
|
||||
|
||||
/// A key whose press moves the focus (Tab from one field to the next) still has its release reach egui in a pass of
|
||||
/// its own: the release is not withdrawn as input whose focus changed, no key stays down, and the waiter is answered
|
||||
/// as processed, not cancelled.
|
||||
#[trial]
|
||||
fn a_key_release_reaches_egui_after_its_press_moves_focus() {
|
||||
use craft_automation::control::{ControlChannel, ControlRequest, Reply};
|
||||
|
||||
let passes: Rc<RefCell<Vec<Seen>>> = Rc::default();
|
||||
let rects = Rc::new(Cell::new([Rect::NOTHING; 2]));
|
||||
let (seen, shown) = (passes.clone(), rects.clone());
|
||||
let (first, second) = (Rc::new(RefCell::new(String::new())), Rc::new(RefCell::new(String::new())));
|
||||
let fx = Fixture::new(move |ui| {
|
||||
let a = TextField::new("First", Bind::bound(&mut *first.borrow_mut())).show(ui).response.rect;
|
||||
let b = TextField::new("Second", Bind::bound(&mut *second.borrow_mut())).show(ui).response.rect;
|
||||
shown.set([a, b]);
|
||||
seen.borrow_mut().push(ui.input(|i| Seen { any_key_down: !i.keys_down.is_empty(), events: i.events.clone(), ..Seen::default() }));
|
||||
});
|
||||
let mut rig = Rig { fx, passes };
|
||||
rig.fx.settle();
|
||||
let at = rects.get()[0].center();
|
||||
rig.send("ui.click", json!({"x": at.x, "y": at.y}));
|
||||
let before = rig.fx.focused();
|
||||
assert!(before.is_some(), "the click focused the first field");
|
||||
|
||||
let (_transport, requests) = std::sync::mpsc::channel();
|
||||
let mut channel = ControlChannel::new(requests);
|
||||
let host = rig.host();
|
||||
rig.take();
|
||||
input_method("ui.key", &json!({"key": "Tab"}), &host, ViewportId::ROOT, &map).expect("a method").expect("valid");
|
||||
let (req, reply) = ControlRequest::new("ui.key", json!({"key": "Tab"}));
|
||||
channel.settle(req, Reply::AfterInput, None, 0.0);
|
||||
let mut answer = None;
|
||||
for _ in 0..32 {
|
||||
rig.fx.frame(Vec::new());
|
||||
channel.poll_input(&host);
|
||||
answer = reply.try_recv().ok();
|
||||
if answer.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
rig.fx.frame(Vec::new());
|
||||
|
||||
let answer = answer.expect("the waiter is answered");
|
||||
assert_eq!(answer["ok"], true, "processed, not cancelled: {answer}");
|
||||
assert!(rig.fx.focused().is_some() && rig.fx.focused() != before, "the press moved the focus");
|
||||
let passes = rig.take();
|
||||
let tab = |pressed: bool| move |event: &Event| matches!(event, Event::Key { key: Key::Tab, pressed: p, .. } if *p == pressed);
|
||||
let press = passes.iter().position(|pass| pass.events.iter().any(tab(true))).expect("a pass saw the press");
|
||||
let release = passes.iter().position(|pass| pass.events.iter().any(tab(false))).expect("a pass saw the release");
|
||||
assert!(press < release, "the release has a pass of its own, after the press's");
|
||||
assert!(passes.last().is_some_and(|pass| !pass.any_key_down), "no key stays down");
|
||||
}
|
||||
|
||||
/// `ui.ime` queues behind the input before it: typed text, then the composition with its converted segment, then
|
||||
|
||||
+12
-5
@@ -130,9 +130,10 @@ 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::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` |
|
||||
| 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 | `Captures` (the bounded queue), `screenshot_reply`, PNG encoding | Allocates a token for `ui.screenshot`, drives the queue each frame, supplies the file writer |
|
||||
| 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 |
|
||||
| View and window state | nothing | Methods such as `ui.set` (tool, panels, theme), `ui.resize`, `engine.execute` |
|
||||
|
||||
Not provided yet, so the porter supplies each today:
|
||||
@@ -171,8 +172,9 @@ Each frame, in the logic phase, the app runs the queued requests. In the UI phas
|
||||
|
||||
```rust
|
||||
use craft_automation::control::{Reply, result_reply};
|
||||
use craft_automation::screenshot::{CaptureGeometry, settle_ms};
|
||||
use craft_automation::screenshot::{CaptureGeometry, ScreenshotParams, settle_ms};
|
||||
use craft_ui::runtime::motion;
|
||||
use egui::ViewportId;
|
||||
|
||||
// Logic phase.
|
||||
let Some(mut channel) = self.control.take() else { return };
|
||||
@@ -184,7 +186,10 @@ channel.finish_captures(finished, &mut |path, bytes| self.write_automation_file(
|
||||
let settle = settle_ms(ctx.global_style().animation_time);
|
||||
while let Some(req) = channel.next_request() {
|
||||
let reply = match req.method.as_str() {
|
||||
"ui.screenshot" => Reply::screenshot(self.next_capture_token(), path_param(&req.params)),
|
||||
"ui.screenshot" => match ScreenshotParams::from_params(&req.params) {
|
||||
Ok(params) => Reply::screenshot(self.next_capture_token(), params, ViewportId::ROOT),
|
||||
Err(e) => Reply::from_result(Err(e)),
|
||||
},
|
||||
"ui.resize" => { /* send ViewportCommand::InnerSize */ Reply::from_result(Ok(json!(null))) }
|
||||
"ui.set" => Reply::from_result(self.ui_set(&req.params)),
|
||||
other => Reply::from_result(Err(format!("unknown method {other}"))),
|
||||
@@ -198,7 +203,9 @@ channel.captures.note_pass();
|
||||
let finished = channel.captures.issue(&WindowHost::of(ctx), motion::now(), document);
|
||||
```
|
||||
|
||||
`write_automation_file` is the app's file authority: it must refuse paths outside the folder the app lets automation write to. A `ui.screenshot` without a `path` returns the PNG as base64 in the reply.
|
||||
`write_automation_file` is the app's file authority: it must refuse paths outside the folder the app lets automation write to. A `ui.screenshot` without a `path` returns the PNG as base64 in the reply. A `region` (`[x0, y0, x1, y1]` in points) crops the picture; one outside the window is refused. Both replies carry the window's `pixels_per_point`.
|
||||
|
||||
On the web there is no server: the app feeds `ControlChannel::new(rx)` from the request closure of `craft_web_api::page::PageApi`, sending each page request as a `ControlRequest::new(method, params)` and answering the page from its reply receiver. The channel, `Reply` and the screenshot queue are the same as on the desktop.
|
||||
|
||||
#### States file
|
||||
|
||||
|
||||
@@ -453,8 +453,8 @@ note = "`#[non_exhaustive]`; `deadline` stays a public field."
|
||||
[[setter]]
|
||||
type = "Reply"
|
||||
old = "Reply::Screenshot { token, path } (struct literal)"
|
||||
new = "Reply::screenshot(token, path)"
|
||||
note = "`Reply` and its `Screenshot` variant are `#[non_exhaustive]`."
|
||||
new = "Reply::screenshot(token, params, viewport)"
|
||||
note = "`Reply` and its `Screenshot` variant are `#[non_exhaustive]`. `params` is a `ScreenshotParams` (`ScreenshotParams::from_params(&req.params)?`): the path and the region."
|
||||
|
||||
[[setter]]
|
||||
type = "ControlChannel"
|
||||
@@ -477,14 +477,14 @@ note = "`#[non_exhaustive]`: `from_facts` builds it from the window's facts; `ne
|
||||
[[setter]]
|
||||
type = "Finished"
|
||||
old = "Finished { token, path, reply, result } (struct literal)"
|
||||
new = "Finished::new(token, path, reply, result)"
|
||||
note = "`#[non_exhaustive]`."
|
||||
new = "Finished::new(token, path, region, geometry, reply, result)"
|
||||
note = "`#[non_exhaustive]`. `region` and `geometry` (the `CaptureGeometry` the image was captured at) are what `screenshot_reply` crops with."
|
||||
|
||||
[[setter]]
|
||||
type = "Click"
|
||||
old = "Click { at, button, count } (struct literal)"
|
||||
new = "Click::from_params(params)"
|
||||
note = "`#[non_exhaustive]`."
|
||||
note = "`#[non_exhaustive]`. The `target` field replaces `at`: `ClickTarget::At` for a point, `ClickTarget::Node` for a node of the access tree named by `id` or `label`."
|
||||
|
||||
[[setter]]
|
||||
type = "KeyPress"
|
||||
|
||||
Reference in New Issue
Block a user