diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index f82a4c14f..90ba8da49 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -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"] +ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui", "dep:craft-host"] # P3(pdf-shell-w2): WF-W17 # 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 diff --git a/crates/automation/src/access.rs b/crates/automation/src/access.rs new file mode 100644 index 000000000..9d23bb344 --- /dev/null +++ b/crates/automation/src/access.rs @@ -0,0 +1,38 @@ +//! `ui.inspect`: the reported widgets of a window's access tree, and the lookup of the one node a click or a focus +//! names. + +use craft_ui::runtime::egui::access::{AccessTree, Declared, NodeKey}; +use craft_ui::runtime::windows::WindowHost; +use egui::ViewportId; +use serde_json::Value; + +/// The node a method names: its id or its label. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum NodeTarget { + /// The node's id. + Id(u64), + /// The node's label, matched case-insensitively. + Label(String), +} + +impl NodeTarget { + /// The node `params` name (`id` or `label`), or none when they name none. + pub fn from_params(params: &Value) -> Result, String> { + let _ = params; + todo!("SH-C15") + } +} + +/// The one reported, enabled node of `tree` that declares `action` and that `target` names; an error names none, +/// several, disabled or undeclared. +pub fn resolve(tree: &AccessTree, target: &NodeTarget, action: Declared) -> Result { + let _ = (tree, target, action); + todo!("SH-C15") +} + +/// `inspect {query?, role?, focused?, limit?=500}`: the reply `{widgets, count, truncated}` over the reported nodes +/// of `viewport`'s access tree, in tree order. +pub fn inspect(host: &WindowHost, viewport: ViewportId, params: &Value) -> Result { + let _ = (host, viewport, params); + todo!("SH-C15") +} diff --git a/crates/automation/src/control.rs b/crates/automation/src/control.rs index 22a058119..61d38d301 100644 --- a/crates/automation/src/control.rs +++ b/crates/automation/src/control.rs @@ -20,7 +20,7 @@ use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; use serde_json::{Value, json}; -use crate::screenshot::{Captures, DocumentId, Finished, ScreenshotRequest, screenshot_reply}; +use crate::screenshot::{Captures, DocumentId, Finished, ScreenshotParams, ScreenshotRequest, screenshot_reply}; use crate::synthetic::TARGET_CHANGED; /// A reply: the JSON object the transport writes as one line. @@ -119,6 +119,8 @@ pub enum Reply { token: u64, /// File to write the PNG to, or `None` to inline it. path: Option, + /// The part of the window to capture, in points; `None` captures the whole window. + region: Option, /// The viewport to capture. viewport: egui::ViewportId, }, @@ -132,8 +134,8 @@ pub enum Reply { impl Reply { /// A `ui.screenshot` reply for `token` of `viewport`, writing the PNG to `path` or inlining it /// when `None`. - pub fn screenshot(token: u64, path: Option, viewport: egui::ViewportId) -> Self { - Self::Screenshot { token, path, viewport } + pub fn screenshot(token: u64, params: ScreenshotParams, viewport: egui::ViewportId) -> Self { + Self::Screenshot { token, path: params.path, region: params.region, viewport } } /// `Done` with the [`result_reply`] of a method's result. @@ -197,7 +199,8 @@ impl ControlChannel { } Reply::AfterInput => self.input_waiters.push(reply), Reply::AfterJob(job) => self.job_waiters.push((job, reply)), - Reply::Screenshot { token, path, viewport } => { + 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()) { let _ = reply.send(json!({"ok": false, "error": e})); } @@ -265,7 +268,7 @@ impl ControlChannel { pub fn finish_captures(&mut self, finished: Vec, write: &mut crate::screenshot::PngWriter<'_>) { for f in finished { let reply = match f.result { - Ok(image) => screenshot_reply(f.token, image, f.path.as_deref(), write), + Ok(image) => screenshot_reply(f.token, image, None, f.path.as_deref(), write), // P3(pdf-shell-w2): SH-C18 (`None` until the request carries the region) Err(e) => json!({"ok": false, "error": e}), }; if let Some(tx) = f.reply { diff --git a/crates/automation/src/dock.rs b/crates/automation/src/dock.rs new file mode 100644 index 000000000..9c4dce156 --- /dev/null +++ b/crates/automation/src/dock.rs @@ -0,0 +1,29 @@ +//! `ui.dock.apply`: one dock action applied to the app's workspace, and the workspace's `ui.inspect` listing. + +use std::hash::Hash; + +use craft_behavior::dock::Workspace; +use craft_ui::docking::DockPanels; +use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::Value; + +/// `ui.dock.apply {action}`: deserializes one dock action and applies it to `workspace` with the permissions `panels` +/// gives, as the dock area does. It returns `Ok({applied: [...]})`, the panels the action closed, in group order; an +/// error is the dock error's text. `None` for any other method. +pub fn dock_method( + workspace: &mut Workspace

, + panels: &dyn DockPanels

, + locked: bool, + method: &str, + params: &Value, +) -> Option> { + let _ = (workspace, panels, locked, method, params); + todo!("CH-C22") +} + +/// The `dock` field of the app's one `ui.inspect`: the workspace as JSON. +pub fn inspect(workspace: &Workspace

) -> Value { + let _ = workspace; + todo!("CH-C22") +} diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs new file mode 100644 index 000000000..4713cab6b --- /dev/null +++ b/crates/automation/src/files.rs @@ -0,0 +1,10 @@ +//! `ui.pick`: answers the next file picker of a running app. + +use serde_json::Value; + +/// `None` for any method other than `ui.pick`. `ui.pick` takes exactly one of `{files: [path, ..]}`, `{folder: path}`, +/// `{save: path}` or `{cancel: true}` and answers through `Files::answer_next` with `Picked::Paths` or `Cancelled`. +pub fn pick_method(files: &dyn craft_host::Files, method: &str, params: &Value) -> Option> { + let _ = (files, method, params); + todo!("WF-W17") +} diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 52e967ead..56cced213 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -21,12 +21,18 @@ pub mod agents; #[cfg(feature = "ui")] pub mod ui; +#[cfg(feature = "ui")] +pub mod access; // P3(pdf-shell-w2): SH-C15 #[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 +#[cfg(all(feature = "ui", not(target_arch = "wasm32")))] +pub mod files; // P3(pdf-shell-w2): WF-W17 #[cfg(not(target_arch = "wasm32"))] pub mod profiler; #[cfg(not(target_arch = "wasm32"))] @@ -39,6 +45,8 @@ pub mod security; pub mod synthetic; #[cfg(not(target_arch = "wasm32"))] pub mod trace; +#[cfg(feature = "ui")] +pub mod window; // P3(pdf-shell-w2): CH-C23 #[cfg(not(target_arch = "wasm32"))] pub mod client; diff --git a/crates/automation/src/screenshot.rs b/crates/automation/src/screenshot.rs index f3456c521..f5da104b7 100644 --- a/crates/automation/src/screenshot.rs +++ b/crates/automation/src/screenshot.rs @@ -23,6 +23,7 @@ use std::time::{Duration, Instant}; use base64::Engine as _; use craft_ui::runtime::windows::{ScreenshotFacts, ScreenshotSlot, WindowHost}; use egui::{ColorImage, ViewportId}; +use serde_json::Value; use crate::control::ControlResponse; @@ -678,6 +679,24 @@ pub fn encode_png(width: usize, height: usize, rgba: &[u8]) -> Result, S /// authorized workspace. `Err` is the reply's error text. pub type PngWriter<'a> = dyn FnMut(&str, &[u8]) -> Result<(), String> + 'a; +/// A validated `ui.screenshot`: where the PNG goes and which part of the window it shows. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ScreenshotParams { + /// File to write the PNG to, or `None` to inline it. + pub path: Option, + /// The part of the window to capture as `[x0, y0, x1, y1]` in points, finite and ordered; `None` captures the + /// whole window. + pub region: Option, +} + +impl ScreenshotParams { + /// `{path?, region?}`, no other fields. + pub fn from_params(params: &Value) -> Result { + let _ = params; + todo!("SH-C18") + } +} + /// The reply for a finished image: /// - an image 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"}`; @@ -689,7 +708,14 @@ pub type PngWriter<'a> = dyn FnMut(&str, &[u8]) -> Result<(), String> + 'a; /// - an encode or write error `e`: `{"ok": false, "error": e}`. /// /// Flatten the pixels to RGBA and drop the image before encoding, so the two copies don't overlap. -pub fn screenshot_reply(token: u64, image: Arc, path: Option<&str>, write: &mut PngWriter<'_>) -> ControlResponse { +pub fn screenshot_reply( + token: u64, + image: Arc, + region: Option, + path: Option<&str>, + write: &mut PngWriter<'_>, +) -> ControlResponse { + let _ = region; // P3(pdf-shell-w2): SH-C18 (the writer crops the image to it) 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 { return serde_json::json!({ diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index 90e16fc1b..ed0fc0f4e 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -24,6 +24,7 @@ use craft_ui::runtime::windows::{Released, WindowHost}; use egui::{Pos2, Vec2, ViewportId, pos2, vec2}; use serde_json::Value; +use crate::access::NodeTarget; use crate::protocol::{BUTTONS, KEY_MODIFIERS, Params}; /// Most clicks one `ui.click` may ask for (`count`). @@ -117,12 +118,42 @@ 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. +#[derive(Clone, Debug, PartialEq)] +pub enum ClickTarget { + /// A position. + At(At), + /// A node of the access tree. + Node(NodeTarget), +} + +/// A validated `ui.focus`: moves the focus to a node of the access tree. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Focus { + /// The node that takes the focus. + pub target: NodeTarget, +} + +impl Focus { + /// `{id | label}`: the node to focus. + pub fn from_params(params: &Value) -> Result { + let _ = params; + todo!("SH-C16") + } + + /// Sends the focus request for the node to `viewport`. + pub fn inject(&self, host: &WindowHost, viewport: ViewportId) -> Result<(), String> { + let _ = (host, viewport); + todo!("SH-C16") + } +} + /// A validated `ui.click`. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct Click { - /// Target position. - pub at: At, + /// Where the click goes: a position or a node of the access tree. + pub target: ClickTarget, /// The button pressed. pub button: PointerButton, /// Number of clicks (2 is a double click). @@ -145,7 +176,7 @@ impl Click { return Err(format!("`count` must be at most {MAX_CLICKS} (got {count})")); } Ok(Self { - at: At::from_params(&p)?, + 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)?, @@ -156,7 +187,8 @@ impl Click { /// Queues a move to the target, then `count` presses and releases of the button, in `viewport`. pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { let count = u32::try_from(self.count).unwrap_or(u32::MAX); - host.inject_click(viewport, self.at.resolve(map)?, self.button, count, self.mods, self.hold); + 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(()) } } diff --git a/crates/automation/src/window.rs b/crates/automation/src/window.rs new file mode 100644 index 000000000..927788c48 --- /dev/null +++ b/crates/automation/src/window.rs @@ -0,0 +1,12 @@ +//! `ui.window`: window commands through the framework's one window-command path. + +use craft_ui::runtime::windows::WindowHost; +use egui::ViewportId; +use serde_json::Value; + +/// `ui.window {maximized: bool}` sends `WindowAction::SetMaximized` through `WindowHost::act` and returns `Ok({})`, or +/// `Err` when `act` returns false (no window commands, as on wasm). `None` for any other method. It keeps no state. +pub fn window_method(host: &WindowHost, viewport: ViewportId, method: &str, params: &Value) -> Option> { + let _ = (host, viewport, method, params); + todo!("CH-C23") +} diff --git a/crates/color-ui/src/ui/pair.rs b/crates/color-ui/src/ui/pair.rs index 3b1204c6d..e9bb01550 100644 --- a/crates/color-ui/src/ui/pair.rs +++ b/crates/color-ui/src/ui/pair.rs @@ -496,7 +496,12 @@ impl Component for SwatchPair<'_> { match shown.color.same() { Some(color) if shown.ring => paint_ring(&draw, at, *color, style), color => { - draw.swatch_well(at, style.radius, color.copied()); + // P3(pdf-comments-w5): CM-C25 (`swatch_well` takes a `WellFill`) + draw.swatch_well( + at, + style.radius, + color.copied().map_or(craft_ui::primitives::WellFill::Mixed, craft_ui::primitives::WellFill::Color), + ); draw.stroke(&PaintShape::Rect(at, style.radius), StrokeWidth::Thin, style.mark); draw.stroke(&outline(at, style), StrokeWidth::Thin, style.edge); } diff --git a/crates/color-ui/src/ui/palette.rs b/crates/color-ui/src/ui/palette.rs index c97450556..36b346c76 100644 --- a/crates/color-ui/src/ui/palette.rs +++ b/crates/color-ui/src/ui/palette.rs @@ -7,6 +7,7 @@ use craft_ui::choice::SwatchTable; use craft_ui::contract::{Bind, Held, NoValue, Outcome, Pattern, ShowContainer as _}; use craft_ui::layout_components::Stack; use craft_ui::runtime::env::Label; +use craft_ui::runtime::requests::ColorRequest; use egui::{Response, Ui}; use std::sync::Arc; @@ -23,6 +24,10 @@ pub struct SwatchPaletteOutput { /// The pick of this pass as one `Set` of the swatch's colour; `None` when nothing was picked. The palette has /// already written it to its binding. pub edit: Option>, + /// The request of the Other… row for the host's colour picker, when it was pressed this pass. + pub pick_color: Option, + /// Every swatch click of this pass, also a click on the colour already bound, which files no `edit`. + pub picked: Option, } impl Outcome for SwatchPaletteOutput { @@ -47,19 +52,55 @@ impl Outcome for SwatchPaletteOutput { #[derive(Pattern)] pub struct SwatchPalette<'a> { label: Label, - color: Bind<'a, Srgba>, + color: PaletteColor<'a>, swatches: &'a [(Label, Srgba)], } +/// What a palette binds: a colour, or a colour that may be none. +enum PaletteColor<'a> { + Color(Bind<'a, Srgba>), + Optional(Bind<'a, Mixed>>), +} + impl<'a> SwatchPalette<'a> { /// A palette named `label` of `swatches`, each a name and a colour, choosing the colour bound to `color`. pub fn new(label: impl Into