diff --git a/apps/vectorcraft-web/src/api.rs b/apps/vectorcraft-web/src/api.rs index 1be921baf3..8755b44578 100644 --- a/apps/vectorcraft-web/src/api.rs +++ b/apps/vectorcraft-web/src/api.rs @@ -26,10 +26,10 @@ use std::pin::Pin; use std::rc::Rc; use std::sync::mpsc::{Receiver, Sender, TryRecvError}; +use craft_automation::{ControlRequest, Dispatch}; use craft_web_api::methods::Methods; use craft_web_api::page::{PageApi, Request}; use serde_json::{Value, json}; -use vectorcraft_ui_egui::{ControlRequest, ControlTicket as Ticket}; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::{JsFuture, future_to_promise}; @@ -92,7 +92,7 @@ const POLL_MS: i32 = 16; /// timeout fired) gives the request up if the app has not started it, so the app never runs it late. struct Waiting { reply: Receiver, - ticket: Ticket, + dispatch: Dispatch, answered: bool, } @@ -116,7 +116,7 @@ impl Waiting { impl Drop for Waiting { fn drop(&mut self) { if !self.answered { - self.ticket.give_up(); + self.dispatch.give_up(); } } } @@ -125,13 +125,13 @@ impl Drop for Waiting { /// `{ok: false, error}` object. fn send(method: &str, params: Value) -> Pin>> { let (req, rx) = ControlRequest::new(method, params); - let ticket = req.ticket(); + let dispatch = req.dispatch.clone(); let sent = TX.with(|t| t.borrow().as_ref().is_some_and(|tx| tx.send(req).is_ok())); if !sent { return Box::pin(async { json!({"ok": false, "error": "VectorCraft is not running yet"}) }); } repaint(); - let mut waiting = Waiting { reply: rx, ticket, answered: false }; + let mut waiting = Waiting { reply: rx, dispatch, answered: false }; Box::pin(async move { loop { if let Some(reply) = waiting.poll() { diff --git a/apps/vectorcraft/src/automation_args.rs b/apps/vectorcraft/src/automation_args.rs index 979f42e7bd..c0bf311cc9 100644 --- a/apps/vectorcraft/src/automation_args.rs +++ b/apps/vectorcraft/src/automation_args.rs @@ -1,10 +1,11 @@ -//! Parse the control port and automation roots before starting any desktop services. A malformed +//! Parse the control flags and automation roots before starting any desktop services. A malformed //! flag must not silently remove a root and leave the control channel unconfined, or leave the app //! running without the control channel that was asked for. -use std::ffi::OsString; use std::path::PathBuf; +use craft_automation::args::{ControlOptions, OptionsError, Source, control_port}; + pub struct AutomationArgs { pub read_roots: Vec, pub write_roots: Vec, @@ -50,50 +51,61 @@ impl AutomationArgs { } } -/// `--control ` or `--control=`, given at most once. +/// `--control `, `--control-token ` and `--control-token-file `, each in either +/// spelling (`--control=`) and given at most once. #[derive(Default)] pub struct ControlArg { - pub port: Option, + options: ControlOptions, } impl ControlArg { - /// Returns whether this argument is `--control`. The next argument is its port whatever it - /// is, so `--control --automation-read-root` reports the flag rather than reading it as a root. + /// What the command line gave, each value marked as a flag's, for + /// [`ControlOptions::resolve`] to put over the environment. + pub fn options(&self) -> ControlOptions { + self.options.clone() + } + + /// Returns whether this argument is one of the control flags. The next argument is the value + /// whatever it is, so `--control --automation-read-root` reports the flag rather than reading + /// it as a root. pub fn consume(&mut self, arg: &str, args: &mut impl Iterator) -> Result { - let value = match arg.strip_prefix("--control") { - Some("") => args.next(), - Some(rest) => match rest.strip_prefix('=') { - Some(value) => Some(value.to_owned()), - None => return Ok(false), - }, - None => return Ok(false), + let (flag, inline) = arg.split_once('=').map_or((arg, None), |(flag, value)| (flag, Some(value))); + let given = match flag { + "--control" => self.options.port.is_some(), + "--control-token" => self.options.token.is_some(), + "--control-token-file" => self.options.token_file.is_some(), + _ => return Ok(false), }; - if self.port.is_some() { - return Err("--control given twice".into()); + let value = match inline { + Some(value) => value.to_owned(), + None => args.next().ok_or_else(|| format!("a value is required for '{flag}' but none was supplied"))?, + }; + if given { + return Err(format!("the argument '{flag}' cannot be used multiple times")); + } + let options = &mut self.options; + let from_flag = Some(Source::Flag); + match flag { + "--control" => { + let not_a_port = || OptionsError::NotAPort { value: value.clone(), shown: "--control ".into() }.to_string(); + options.port = Some(control_port(&value).map_err(|_| not_a_port())?); + options.sources.port = from_flag; + } + // A blank token or path would leave the channel open to anyone or name no file. + _ if value.trim().is_empty() => return Err(format!("a value is required for '{flag}' but none was supplied")), + "--control-token" => { + options.token = Some(value); + options.sources.token = from_flag; + } + _ => { + options.token_file = Some(PathBuf::from(value)); + options.sources.token_file = from_flag; + } } - self.port = Some(port("--control", value.as_deref())?); Ok(true) } } -/// `VECTORCRAFT_CONTROL_PORT`, for when `--control` isn't given: unset or empty is no control -/// channel, anything else must be a port. -pub fn env_control_port(value: Option) -> Result, String> { - match value { - Some(v) if !v.is_empty() => port("VECTORCRAFT_CONTROL_PORT", Some(&v.to_string_lossy())).map(Some), - _ => Ok(None), - } -} - -/// A port from 1 to 65535 (the server would listen on 0's random port without saying which). -fn port(name: &str, value: Option<&str>) -> Result { - let need = format!("{name} needs a port number from 1 to 65535"); - match value { - None => Err(need), - Some(v) => v.parse().ok().filter(|&p| p != 0).ok_or(format!("{need}, not `{v}`")), - } -} - #[cfg(test)] mod tests { use super::*; @@ -147,27 +159,38 @@ mod tests { assert_eq!(roots.write_roots, [PathBuf::from("./-folder")]); } - fn control(args: &[&str]) -> Result, String> { + fn control(args: &[&str]) -> Result { let mut control = ControlArg::default(); let mut args = args.iter().map(|a| a.to_string()); while let Some(a) = args.next() { assert!(control.consume(&a, &mut args)?, "{a}"); } - Ok(control.port) + Ok(control.options()) } #[test] - fn control_needs_a_port_from_1_to_65535() { - let need = "--control needs a port number from 1 to 65535"; - assert_eq!(control(&["--control"]), Err(need.into())); - assert_eq!(control(&["--control", "--automation-read-root"]), Err(format!("{need}, not `--automation-read-root`"))); - for bad in ["abc", "0", "70000", "-1", ""] { - assert_eq!(control(&["--control", bad]), Err(format!("{need}, not `{bad}`"))); - assert_eq!(control(&[&format!("--control={bad}")]), Err(format!("{need}, not `{bad}`"))); + fn a_control_flag_takes_the_next_argument_whatever_it_is() { + assert!(control(&["--control"]).is_err(), "a flag with no value"); + let err = control(&["--control", "--automation-read-root"]).unwrap_err(); + assert!(err.contains("--automation-read-root"), "the next argument is the port, not a root flag: {err}"); + for bad in ["abc", "70000", "-1", ""] { + assert!(control(&["--control", bad]).is_err(), "{bad}"); + assert!(control(&[&format!("--control={bad}")]).is_err(), "{bad}"); } - assert_eq!(control(&["--control", "7979"]), Ok(Some(7979))); - assert_eq!(control(&["--control=65535"]), Ok(Some(65535))); - assert_eq!(control(&["--control", "7979", "--control=7980"]), Err("--control given twice".into())); + for twice in [ + ["--control", "7979", "--control=7980"], + ["--control-token", "a", "--control-token=b"], + ["--control-token-file", "a", "--control-token-file=b"], + ] { + assert!(control(&twice).is_err(), "{twice:?}"); + } + assert!(control(&["--control-token="]).is_err(), "an empty token"); + let port = control(&["--control", "7979"]).unwrap(); + assert_eq!(port, control(&["--control=7979"]).unwrap(), "both spellings agree"); + assert_eq!((port.port, port.sources.port), (Some(7979), Some(Source::Flag))); + assert_eq!(control(&["--control=0"]).unwrap().port, Some(0), "port 0 picks a free port"); + let secret = control(&["--control-token", "--odd", "--control-token-file=key.txt"]).unwrap(); + assert_eq!((secret.token.as_deref(), secret.token_file), (Some("--odd"), Some(PathBuf::from("key.txt")))); } #[test] @@ -178,21 +201,9 @@ mod tests { assert!(!control.consume(other, &mut args).unwrap(), "{other}"); } assert_eq!(args.next().as_deref(), Some("7979")); - assert_eq!(control.port, None); - } - - #[test] - fn control_port_variable_is_a_port_or_unset() { - assert_eq!(env_control_port(None), Ok(None)); - assert_eq!(env_control_port(Some("".into())), Ok(None)); - assert_eq!(env_control_port(Some("7979".into())), Ok(Some(7979))); - let need = "VECTORCRAFT_CONTROL_PORT needs a port number from 1 to 65535"; - assert_eq!(env_control_port(Some("abc".into())), Err(format!("{need}, not `abc`"))); - assert_eq!(env_control_port(Some("0".into())), Err(format!("{need}, not `0`"))); - #[cfg(unix)] - { - use std::os::unix::ffi::OsStringExt; - assert_eq!(env_control_port(Some(OsString::from_vec(vec![0x39, 0xff]))), Err(format!("{need}, not `9\u{fffd}`"))); + assert_eq!(control.options(), ControlOptions::default()); + for token_flag in ["--control-token", "--control-token-file"] { + assert!(ControlArg::default().consume(token_flag, &mut ["x".to_owned()].into_iter()).unwrap(), "{token_flag}"); } } } diff --git a/apps/vectorcraft/src/control_server.rs b/apps/vectorcraft/src/control_server.rs deleted file mode 100644 index 1a44eba288..0000000000 --- a/apps/vectorcraft/src/control_server.rs +++ /dev/null @@ -1,320 +0,0 @@ -//! Loopback JSON-lines control server: one request per line, one reply per line. -//! This is the transport the MCP server (`vectorcraft mcp --connect`) wraps. -//! -//! The server only ever reads requests: a line that is not a JSON object with a string `method` -//! (an HTTP request line from a browser's cross-origin `fetch`, a stray `nc`, binary junk) gets -//! one error reply and the connection is closed, so nothing after it is executed. Lines are -//! bounded ([`MAX_LINE`]) and so is the number of open connections ([`MAX_CONNECTIONS`]); junk -//! never reaches the UI thread. See `docs/control-protocol.md`. - -use std::io::{BufRead, BufReader, BufWriter, Read, Write}; -use std::net::{TcpListener, TcpStream}; -use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::mpsc::{Receiver, Sender, channel}; -use std::time::Duration; - -use serde_json::{Value, json}; -use vectorcraft_ui_egui::ControlRequest; - -#[path = "control_deadlines.rs"] -mod deadlines; -use deadlines::{DeadlineReader, DeadlineWriter}; - -/// Longest accepted request line (bytes, without the newline). Requests are small JSON objects; -/// anything longer is refused and the connection closed. -pub const MAX_LINE: usize = 4 * 1024 * 1024; -/// Connections served at once; further ones get an error line and are closed. -pub const MAX_CONNECTIONS: usize = 16; -/// Size in bytes of the buffer that [`write_line`] writes a reply line through. -const REPLY_CHUNK: usize = 64 * 1024; - -/// How long a request waits for the app's reply. -const REPLY_WAIT: Duration = Duration::from_secs(60); - -/// The reply to a request the app didn't answer in [`REPLY_WAIT`]. One it had not started is -/// withdrawn, so it never runs after its caller was told it failed; one it is running can't be -/// stopped, and the reply says its outcome isn't known. -fn timed_out(ticket: &vectorcraft_ui_egui::ControlTicket) -> Value { - let error = if ticket.give_up() { - "timeout: the app did not start the request in time; it was withdrawn and will not run" - } else { - "timeout: the app is still running the request; it may yet complete" - }; - json!({"ok": false, "error": error}) -} - -#[derive(Clone, Copy)] -struct ConnectionTimeouts { - idle: Duration, - line: Duration, - write: Duration, -} - -impl Default for ConnectionTimeouts { - fn default() -> Self { - Self { idle: Duration::from_secs(300), line: Duration::from_secs(30), write: Duration::from_secs(60) } - } -} - -pub fn start(port: u16, ctx: egui::Context) -> Receiver { - let (tx, rx) = channel::(); - let listener = match TcpListener::bind(("127.0.0.1", port)) { - Ok(l) => l, - Err(e) => { - eprintln!("vectorcraft: control server failed to bind 127.0.0.1:{port}: {e}"); - return rx; - } - }; - eprintln!("vectorcraft: control server listening on 127.0.0.1:{port}"); - #[cfg(target_os = "macos")] - keep_answering(); - std::thread::spawn(move || accept_loop(listener, tx, ctx)); - rx -} - -/// The activity the control channel holds on macOS: work the user asked for, which may let the -/// system sleep when idle, with full timer precision. Without it, App Nap lowers every thread to -/// the lowest priority within about a minute of the window no longer being visible. -#[cfg(target_os = "macos")] -fn activity_options() -> objc2_foundation::NSActivityOptions { - use objc2_foundation::NSActivityOptions; - NSActivityOptions::UserInitiatedAllowingIdleSystemSleep | NSActivityOptions::LatencyCritical -} - -/// Begins the control channel's activity. It lasts until the process ends. -#[cfg(target_os = "macos")] -fn keep_answering() { - use objc2_foundation::{NSProcessInfo, NSString}; - let reason = NSString::from_str("Answering control requests"); - let activity = NSProcessInfo::processInfo().beginActivityWithOptions_reason(activity_options(), &reason); - // The token is never released or passed to `endActivity`, so the activity lasts for the process's lifetime. - std::mem::forget(activity); -} - -fn accept_loop(listener: TcpListener, tx: Sender, ctx: egui::Context) { - let open = Arc::new(AtomicUsize::new(0)); - for stream in listener.incoming().flatten() { - let Some(slot) = acquire_slot(&open) else { - let mut out = DeadlineWriter::new(stream, ConnectionTimeouts::default().write); - // Best effort: the connection is dropped either way, and a peer that can't read the reason loses nothing. - if out.begin_reply().is_ok() { - let _ = write_line(&mut out, &json!({"ok": false, "error": "too many control connections"})); - } - continue; - }; - if let Err(e) = spawn_connection(stream, tx.clone(), ctx.clone(), slot, ConnectionTimeouts::default()) { - eprintln!("vectorcraft: control worker failed to start: {e}"); - } - } -} - -struct ConnectionSlot(Arc); - -fn acquire_slot(open: &Arc) -> Option { - let mut n = open.load(Ordering::SeqCst); - loop { - if n >= MAX_CONNECTIONS { - return None; - } - match open.compare_exchange_weak(n, n + 1, Ordering::SeqCst, Ordering::SeqCst) { - Ok(_) => return Some(ConnectionSlot(Arc::clone(open))), - Err(current) => n = current, - } - } -} - -impl Drop for ConnectionSlot { - fn drop(&mut self) { - // Each successful acquisition creates exactly one non-cloneable guard. - self.0.fetch_sub(1, Ordering::SeqCst); - } -} - -fn spawn_connection( - stream: TcpStream, - tx: Sender, - ctx: egui::Context, - slot: ConnectionSlot, - timeouts: ConnectionTimeouts, -) -> std::io::Result> { - std::thread::Builder::new().name("vectorcraft-control".into()).spawn(move || { - let _slot = slot; - serve_socket(stream, timeouts, |method, params| { - let (req, rrx) = ControlRequest::new(method, params); - let ticket = req.ticket(); - tx.send(req).ok()?; - ctx.request_repaint(); - Some(rrx.recv_timeout(REPLY_WAIT).unwrap_or_else(|_| timed_out(&ticket))) - }); - }) -} - -fn serve_socket(stream: TcpStream, timeouts: ConnectionTimeouts, handle: impl FnMut(String, Value) -> Option) { - let Ok(read) = stream.try_clone() else { return }; - let closer = stream.try_clone().ok(); - let read = DeadlineReader::new(read, timeouts.idle, timeouts.line); - // Replies reach the writer in [`REPLY_CHUNK`] pieces ([`write_line`]), so checking the remaining - // budget costs one socket option call per piece, not one per JSON token. - let out = DeadlineWriter::new(stream, timeouts.write); - serve_lines_with( - read, - out, - handle, - |reader| { - let buffered = !reader.buffer().is_empty(); - reader.get_mut().begin_line(buffered) - }, - DeadlineWriter::begin_reply, - ); - if let Some(s) = closer { - close_gracefully(s); - } -} - -/// How long [`close_gracefully`] waits for the peer to close its side. -const CLOSE_DRAIN: Duration = Duration::from_secs(1); - -/// The most [`close_gracefully`] reads from a peer that keeps sending. -const MAX_DRAIN: usize = 1 << 20; - -/// Ends a connection: no more replies (the peer reads them all, then end of stream), then what the -/// peer still sends is read and dropped until it closes too, for at most [`CLOSE_DRAIN`] and -/// [`MAX_DRAIN`] bytes. On Windows, dropping a socket with unread input resets the connection, and -/// the reset can discard replies the peer has not read yet. -fn close_gracefully(mut s: TcpStream) { - // Each step is best effort: a peer that is already gone needs none of them. - let _ = s.shutdown(std::net::Shutdown::Write); - let _ = s.set_read_timeout(Some(CLOSE_DRAIN)); - let deadline = std::time::Instant::now() + CLOSE_DRAIN; - let (mut buf, mut left) = ([0u8; 4096], MAX_DRAIN); - while left > 0 && std::time::Instant::now() < deadline { - match s.read(&mut buf) { - Ok(0) | Err(_) => break, - Ok(n) => left = left.saturating_sub(n), - } - } -} - -/// One parsed line. -enum Line { - Request { - id: Value, - method: String, - params: Value, - }, - Blank, - /// Not a request: reply with this error and close the connection. - Reject(String), -} - -fn parse_line(bytes: &[u8]) -> Line { - let Ok(text) = std::str::from_utf8(bytes) else { - return Line::Reject("not a control request (invalid UTF-8); closing the connection".into()); - }; - let text = text.trim(); - if text.is_empty() { - return Line::Blank; - } - let msg = match serde_json::from_str::(text) { - Ok(v) => v, - Err(e) => return Line::Reject(format!("bad JSON ({e}); expected one JSON request object per line; closing the connection")), - }; - let Some(obj) = msg.as_object() else { - return Line::Reject("not a control request (expected a JSON object); closing the connection".into()); - }; - let Some(method) = obj.get("method").and_then(Value::as_str) else { - return Line::Reject("not a control request (missing string `method`); closing the connection".into()); - }; - Line::Request { - id: obj.get("id").cloned().unwrap_or(Value::Null), - method: method.to_string(), - params: obj.get("params").cloned().unwrap_or(json!({})), - } -} - -/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped). -/// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails. -fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usize) -> Result { - buf.clear(); - // `take` bounds the bytes buffered for one line: a peer can't make us allocate more than `max`. - let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1); - let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| match e.kind() { - // The line's deadline ran out (Windows reports it as TimedOut, Unix as WouldBlock). - std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => "request line not completed in time; closing the connection".to_string(), - _ => e.to_string(), - })?; - if n == 0 { - return Ok(false); - } - if buf.last() == Some(&b'\n') { - buf.pop(); - if buf.last() == Some(&b'\r') { - buf.pop(); - } - return Ok(true); - } - if buf.len() > max { - return Err(format!("request line longer than {max} bytes; closing the connection")); - } - // Last line without a newline, then end of stream. - Ok(true) -} - -/// Write `v` and a newline to `out` through a buffer of [`REPLY_CHUNK`] bytes, then flush `out`. -fn write_line(out: &mut impl Write, v: &Value) -> std::io::Result<()> { - let mut out = BufWriter::with_capacity(REPLY_CHUNK, out); - writeln!(out, "{v}")?; - out.flush() -} - -/// Serve requests from `read`, answering on `out`, until the peer closes, sends something that is -/// not a request, or `handle` returns `None` (app gone). `handle` gets `(method, params)` and -/// returns the reply object (the request's `id` is added here). -#[cfg(test)] -fn serve_lines(read: R, out: W, handle: impl FnMut(String, Value) -> Option) { - serve_lines_with(read, out, handle, |_| Ok(()), |_| Ok(())); -} - -fn serve_lines_with( - read: R, - mut out: W, - mut handle: impl FnMut(String, Value) -> Option, - mut begin_line: impl FnMut(&mut BufReader) -> std::io::Result<()>, - mut begin_reply: impl FnMut(&mut W) -> std::io::Result<()>, -) { - let mut reader = BufReader::new(read); - let mut buf = Vec::new(); - loop { - if begin_line(&mut reader).is_err() { - return; - } - let reject = match read_bounded_line(&mut reader, &mut buf, MAX_LINE) { - Ok(false) => return, - // Nothing of a line arrived (the idle wait ran out, or the peer is gone): close without - // a word. A line nobody asked for would be read as the reply to the client's next request. - Err(_) if buf.is_empty() => return, - Err(e) => e, - Ok(true) => match parse_line(&buf) { - Line::Blank => continue, - Line::Reject(e) => e, - Line::Request { id, method, params } => { - let Some(mut r) = handle(method, params) else { return }; - if let Some(o) = r.as_object_mut() { - o.insert("id".into(), id); - } - if begin_reply(&mut out).and_then(|()| write_line(&mut out, &r)).is_err() { - return; - } - continue; - } - }, - }; - // Best effort: the connection closes either way, and a peer that can't read the reason loses nothing. - let _ = begin_reply(&mut out).and_then(|()| write_line(&mut out, &json!({"ok": false, "error": reject}))); - return; - } -} - -#[cfg(test)] -mod tests; diff --git a/apps/vectorcraft/src/control_server/tests.rs b/apps/vectorcraft/src/control_server/tests.rs deleted file mode 100644 index 7aa290e01f..0000000000 --- a/apps/vectorcraft/src/control_server/tests.rs +++ /dev/null @@ -1,411 +0,0 @@ -use super::*; - -fn short_timeouts() -> ConnectionTimeouts { - ConnectionTimeouts { idle: Duration::from_millis(150), line: Duration::from_millis(120), write: Duration::from_millis(150) } -} - -/// How long a test waits for the server to reply or to close a connection. The wait only ends a -/// test whose server never does either; the budgets under test are 120 and 150 ms, and 1 s in the -/// persistent test. On a busy machine the server's thread can pause for seconds before or between -/// its reads and writes, and a wait of a few seconds then fails a server that closes the -/// connection on time. -const WAIT: Duration = Duration::from_secs(20); - -/// The short line deadline, with idle and reply budgets longer than [`WAIT`]. On a busy machine -/// either thread can pause for more than 150 ms between connecting and sending, or between -/// starting a reply and writing it, and a short budget then closes the connection with no reply. -fn line_timeouts() -> ConnectionTimeouts { - ConnectionTimeouts { idle: Duration::from_secs(30), write: Duration::from_secs(30), ..short_timeouts() } -} - -fn socket_fixture( - timeouts: ConnectionTimeouts, - handle: impl FnMut(String, Value) -> Option + Send + 'static, -) -> (TcpStream, Receiver<()>, std::thread::JoinHandle<()>) { - let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let addr = listener.local_addr().unwrap(); - let (finished, done) = channel(); - let worker = std::thread::spawn(move || { - let (stream, _) = listener.accept().unwrap(); - socket2::SockRef::from(&stream).set_send_buffer_size(4096).unwrap(); - serve_socket(stream, timeouts, handle); - finished.send(()).unwrap(); - }); - let client = TcpStream::connect(addr).unwrap(); - socket2::SockRef::from(&client).set_recv_buffer_size(4096).unwrap(); - client.set_read_timeout(Some(WAIT)).unwrap(); - (client, done, worker) -} - -fn expect_socket_deadline(client: TcpStream, done: Receiver<()>, worker: std::thread::JoinHandle<()>) { - let stopped = done.recv_timeout(WAIT).is_ok(); - // Always unblock the old implementation too, so a failed regression leaves no worker behind. - let _ = client.shutdown(std::net::Shutdown::Both); - drop(client); - worker.join().unwrap(); - assert!(stopped, "the server retained a stalled connection beyond its transport deadline"); -} - -#[test] -fn idle_control_socket_releases_its_worker() { - let (client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected")); - expect_socket_deadline(client, done, worker); -} - -/// An idle connection is closed without a line: a client that sends its next request late -/// must not find an error waiting where its reply should be. -#[test] -fn idle_expiry_closes_without_writing_a_line() { - let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected")); - let mut got = Vec::new(); - match client.read_to_end(&mut got) { - // On Windows the server's close can reach the client as a reset. - Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => {} - Ok(_) => {} - Err(e) => panic!("reading the idle connection: {e}"), - } - assert_eq!(String::from_utf8_lossy(&got), "", "the app wrote to an idle connection"); - expect_socket_deadline(client, done, worker); -} - -/// A line that stalls is refused in words a client's author can act on, not the system's. -#[test] -fn stalled_control_line_is_refused_with_the_reason() { - let (mut client, done, worker) = socket_fixture(line_timeouts(), |_, _| panic!("incomplete requests must not execute")); - client.write_all(b"{\"method\":").unwrap(); - let mut line = String::new(); - BufReader::new(client.try_clone().unwrap()).read_line(&mut line).unwrap(); - assert_eq!( - serde_json::from_str::(&line).unwrap(), - json!({"ok": false, "error": "request line not completed in time; closing the connection"}) - ); - expect_socket_deadline(client, done, worker); -} - -#[test] -fn partial_control_line_releases_its_worker() { - let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("incomplete requests must not execute")); - client.write_all(b"{\"method\":").unwrap(); - expect_socket_deadline(client, done, worker); -} - -#[test] -fn trickled_control_line_has_an_absolute_deadline() { - let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("incomplete requests must not execute")); - client.write_all(b"{").unwrap(); - let mut writer = client.try_clone().unwrap(); - let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let writing = Arc::clone(&stop); - let trickle = std::thread::spawn(move || { - while !writing.load(Ordering::SeqCst) { - if writer.write_all(b" ").is_err() { - break; - } - std::thread::sleep(Duration::from_millis(20)); - } - }); - let stopped = done.recv_timeout(WAIT).is_ok(); - stop.store(true, Ordering::SeqCst); - // Both socket copies belong to this fixture; shutdown cleans up the baseline failure as well. - let _ = client.shutdown(std::net::Shutdown::Both); - trickle.join().unwrap(); - worker.join().unwrap(); - assert!(stopped, "trickled bytes restarted the line's deadline"); -} - -#[test] -fn a_nonreading_control_peer_cannot_retain_the_writer() { - let payload = "x".repeat(2 * 1024 * 1024); - let (mut client, done, worker) = socket_fixture(short_timeouts(), move |_, _| Some(json!({"ok": true, "result": payload}))); - client.write_all(b"{\"method\":\"large\"}\n").unwrap(); - expect_socket_deadline(client, done, worker); -} - -/// Each request gets its own line and reply budgets. The handler takes longer than both budgets, -/// so a deadline kept from the previous request runs out. The line and reply budgets are 1 s, and -/// the idle budget is 30 s, longer than the client's [`WAIT`]: on a busy machine either thread can -/// pause for more than the short budgets of [`short_timeouts`] between starting a budget and the -/// read or write it covers. -#[test] -fn persistent_control_requests_get_fresh_transport_deadlines() { - let timeouts = ConnectionTimeouts { idle: Duration::from_secs(30), line: Duration::from_secs(1), write: Duration::from_secs(1) }; - let (mut client, done, worker) = socket_fixture(timeouts, |_, _| { - // Application processing is not transport time; begin the reply budget afterwards. - std::thread::sleep(Duration::from_millis(1250)); - Some(json!({"ok": true})) - }); - let mut reader = BufReader::new(client.try_clone().unwrap()); - for id in [1, 2] { - // The client sends each line in one write. `writeln!` on the socket sends the JSON in many - // small writes, and when the machine is busy, a pause of more than the line deadline between - // two of them closes the connection. - client.write_all(format!("{}\n", json!({"id": id, "method": "inspect"})).as_bytes()).unwrap(); - let mut line = String::new(); - reader.read_line(&mut line).unwrap(); - assert_eq!(serde_json::from_str::(&line).unwrap(), json!({"id": id, "ok": true})); - } - client.shutdown(std::net::Shutdown::Write).unwrap(); - done.recv_timeout(WAIT).unwrap(); - worker.join().unwrap(); -} - -#[test] -fn buffered_partial_control_line_also_expires() { - let (mut client, done, worker) = socket_fixture(line_timeouts(), |_, _| Some(json!({"ok": true}))); - client.write_all(b"{\"id\":1,\"method\":\"inspect\"}\n{").unwrap(); - let mut line = String::new(); - BufReader::new(client.try_clone().unwrap()).read_line(&mut line).unwrap(); - assert_eq!(serde_json::from_str::(&line).unwrap()["id"], 1); - expect_socket_deadline(client, done, worker); -} - -#[test] -fn timed_out_worker_returns_its_connection_slot() { - let open = Arc::new(AtomicUsize::new(0)); - let held: Vec<_> = (0..MAX_CONNECTIONS - 1).map(|_| acquire_slot(&open).unwrap()).collect(); - let slot = acquire_slot(&open).unwrap(); - assert!(acquire_slot(&open).is_none()); - let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); - let (stream, _) = listener.accept().unwrap(); - let (tx, _rx) = channel(); - let worker = spawn_connection(stream, tx, egui::Context::default(), slot, short_timeouts()).unwrap(); - let start = std::time::Instant::now(); - while open.load(Ordering::SeqCst) == MAX_CONNECTIONS && start.elapsed() < WAIT { - std::thread::sleep(Duration::from_millis(10)); - } - let released = open.load(Ordering::SeqCst) < MAX_CONNECTIONS; - // Clean up an old implementation that never returned its slot as well. - let _ = client.shutdown(std::net::Shutdown::Both); - worker.join().unwrap(); - assert!(released, "the deadline did not free capacity for the next client"); - let replacement = acquire_slot(&open).expect("a new client can reserve the freed slot"); - drop(replacement); - drop(held); - assert_eq!(open.load(Ordering::SeqCst), 0); -} - -fn run(input: &[u8]) -> (Vec, Vec) { - let mut out = Vec::new(); - let mut calls = Vec::new(); - serve_lines(input, &mut out, |m, _p| { - calls.push(m); - Some(json!({"ok": true, "result": null})) - }); - let replies = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str::(l).unwrap()).collect(); - (replies, calls) -} - -/// Counts the `write` calls made on it and keeps the bytes they write. -#[derive(Default)] -struct Writes { - calls: usize, - bytes: Vec, -} - -impl Write for Writes { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - self.calls += 1; - self.bytes.extend_from_slice(buf); - Ok(buf.len()) - } - - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } -} - -/// A reply shaped like `document.inspect`'s for a layer of `n` squares in rows of 200. -fn inspect_reply(n: u64) -> Value { - let paths: Vec = (0..n) - .map(|k| { - let (x, y) = ((k % 200) as f64 * 20.0, (k / 200) as f64 * 20.0); - json!({"anchors": 4, "bounds": {"height": 10.0, "width": 10.0, "x": x, "y": y}, "closed": true, "fill": "#f4a261", - "id": k + 2, "kind": "Path", "locked": false, "name": "", "stroke": "None", "strokeWidth": 0.0, "visible": true}) - }) - .collect(); - json!({"ok": true, "result": {"layers": [{"children": paths, "id": 1, "kind": "Layer", "name": "Layer 1"}]}}) -} - -/// #1725: a request its caller gave up before the app took it never runs; one the app took -/// first can't be withdrawn, and the timeout says so. -#[test] -fn a_timed_out_request_is_withdrawn_unless_it_started() { - let (waiting, _rx) = ControlRequest::new("engine.execute", json!({})); - assert!(timed_out(&waiting.ticket())["error"].as_str().unwrap().contains("will not run")); - assert!(!waiting.claim(), "the app skips a withdrawn request"); - let (running, _rx) = ControlRequest::new("engine.execute", json!({})); - assert!(running.claim()); - assert!(timed_out(&running.ticket())["error"].as_str().unwrap().contains("still running")); - assert!(!running.claim(), "a request is taken once"); -} - -#[test] -fn requests_are_answered_in_order_with_ids() { - let (r, calls) = run(b"{\"id\":1,\"method\":\"a\"}\n\n{\"id\":2,\"method\":\"b\",\"params\":{}}\r\n{\"method\":\"c\"}"); - assert_eq!(calls, ["a", "b", "c"]); - assert_eq!(r.len(), 3); - assert_eq!(r[0]["id"], 1); - assert_eq!(r[1]["id"], 2); - assert_eq!(r[2]["id"], Value::Null); -} - -#[test] -fn replies_are_written_in_few_large_writes() { - for reply in [json!({"ok": true, "result": null}), inspect_reply(2_000)] { - let mut out = Writes::default(); - let mut once = Some(reply.clone()); - serve_lines(&b"{\"id\":1,\"method\":\"document.inspect\"}\n"[..], &mut out, |_, _| once.take()); - let mut want = reply; - want["id"] = json!(1); - let text = String::from_utf8(out.bytes).unwrap(); - // The writer receives the bytes that `writeln!(out, "{want}")` writes, in at most one write per 4 KiB. - assert_eq!(text, format!("{want}\n")); - assert!(out.calls <= text.len().div_ceil(4096), "{} writes for {} bytes", out.calls, text.len()); - } - // A refusal is one write as well. - let mut out = Writes::default(); - serve_lines(&b"hello\n"[..], &mut out, |_, _| None); - assert_eq!(out.calls, 1); -} - -#[test] -fn http_request_closes_before_the_body_runs() { - // A browser's cross-origin `fetch` POST: the request line is rejected and the - // connection closed, so the JSON body is never executed. - let http = b"POST / HTTP/1.1\r\nHost: 127.0.0.1:7979\r\nOrigin: https://attacker.example\r\nContent-Type: text/plain\r\n\r\n\ - {\"id\":7,\"method\":\"engine.execute\",\"params\":{\"command\":\"file.new\",\"params\":{}}}\n"; - let (r, calls) = run(http); - assert!(calls.is_empty(), "nothing may run: {calls:?}"); - assert_eq!(r.len(), 1); - assert_eq!(r[0]["ok"], false); - assert!(r[0]["error"].as_str().unwrap().contains("closing the connection")); -} - -#[test] -fn non_request_json_closes_the_connection() { - for junk in [ - &b"[1,2]\n{\"method\":\"a\"}\n"[..], - b"{\"id\":1}\n{\"method\":\"a\"}\n", - b"{\"method\":5}\n{\"method\":\"a\"}\n", - b"\xff\xfe\n{\"method\":\"a\"}\n", - ] { - let (r, calls) = run(junk); - assert!(calls.is_empty(), "{calls:?}"); - assert_eq!(r.len(), 1); - assert_eq!(r[0]["ok"], false); - } -} - -#[test] -fn a_request_before_junk_still_runs() { - let (r, calls) = run(b"{\"method\":\"a\"}\nGET / HTTP/1.1\n{\"method\":\"b\"}\n"); - assert_eq!(calls, ["a"]); - assert_eq!(r.len(), 2); - assert_eq!(r[1]["ok"], false); -} - -#[test] -fn overlong_line_is_refused() { - // One byte over the limit, then a valid request: neither runs. - let mut input = vec![b'x'; MAX_LINE + 1]; - input.extend_from_slice(b"\n{\"method\":\"a\"}\n"); - let (r, calls) = run(&input); - assert!(calls.is_empty(), "{calls:?}"); - assert_eq!(r.len(), 1); - assert!(r[0]["error"].as_str().unwrap().contains("longer than")); -} - -#[test] -fn line_at_the_limit_is_accepted() { - let mut buf = Vec::new(); - let line = vec![b'a'; 10]; - let mut input = line.clone(); - input.push(b'\n'); - assert_eq!(read_bounded_line(&mut &input[..], &mut buf, 10), Ok(true)); - assert_eq!(buf, line); - assert!(read_bounded_line(&mut &[b'a'; 11][..], &mut buf, 10).is_err()); -} - -#[test] -fn tcp_connection_is_closed_after_junk() { - // End to end over a real loopback socket (the transport the app uses). - let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let addr = listener.local_addr().unwrap(); - let server = std::thread::spawn(move || { - let (s, _) = listener.accept().unwrap(); - serve_socket(s, ConnectionTimeouts::default(), |_, _| Some(json!({"ok": true}))); - }); - let mut c = TcpStream::connect(addr).unwrap(); - c.set_read_timeout(Some(WAIT)).unwrap(); - // The server closes gracefully ([`close_gracefully`]): the client reads both replies and then - // the end of the stream, not a reset. - c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n").unwrap(); - let mut text = String::new(); - c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection - server.join().unwrap(); - let lines: Vec<&str> = text.lines().collect(); - assert_eq!(lines.len(), 2, "{text}"); - assert!(lines[0].contains("\"id\":7")); - assert!(lines[1].contains("closing the connection")); -} - -#[test] -fn ten_inspect_replies_for_10000_objects_arrive_within_20_s() { - let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let addr = listener.local_addr().unwrap(); - let reply = inspect_reply(10_000); - let mut want = reply.clone(); - want["id"] = json!(1); - let want = format!("{want}\n"); - std::thread::spawn(move || { - let (s, _) = listener.accept().unwrap(); - let read = s.try_clone().unwrap(); - serve_lines(read, s, |_, _| Some(reply.clone())); - }); - // The client sends each request line and reads its reply line through a `BufReader`, as `vectorcraft_mcp::Remote` does. - let (tx, rx) = channel(); - std::thread::spawn(move || { - let mut c = TcpStream::connect(addr).unwrap(); - let mut read = BufReader::new(c.try_clone().unwrap()); - let mut lines = vec![]; - for _ in 0..10 { - c.write_all(b"{\"id\":1,\"method\":\"document.inspect\"}\n").unwrap(); - let mut line = String::new(); - read.read_line(&mut line).unwrap(); - lines.push(line); - } - tx.send(lines).ok(); - }); - let lines = rx.recv_timeout(Duration::from_secs(20)).unwrap_or_else(|_| panic!("ten replies did not arrive within 20 s")); - assert!(lines.iter().all(|l| *l == want), "a reply differs from the bytes `writeln!` writes"); -} - -#[test] -fn extra_connections_are_refused() { - let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); - let addr = listener.local_addr().unwrap(); - let (tx, _rx) = channel::(); - std::thread::spawn(move || accept_loop(listener, tx, egui::Context::default())); - // Idle connections are accepted in order and held open. - let held: Vec = (0..16).map(|_| TcpStream::connect(addr).unwrap()).collect(); - let mut extra = TcpStream::connect(addr).unwrap(); - extra.set_read_timeout(Some(WAIT)).unwrap(); - let mut line = String::new(); - BufReader::new(&mut extra).read_line(&mut line).unwrap(); - assert!(line.contains("too many control connections"), "{line}"); - drop(held); -} - -// A test process is not an app that App Nap applies to, so this checks the activity the -// channel asks for; the throttling itself shows only in a running app with its window hidden. -#[cfg(target_os = "macos")] -#[test] -fn the_control_channel_keeps_the_app_at_full_priority_on_macos() { - use objc2_foundation::NSActivityOptions; - let options = activity_options(); - assert!(options.contains(NSActivityOptions::LatencyCritical), "without it App Nap still lowers the priority to 20"); - assert!(options.contains(NSActivityOptions::UserInitiatedAllowingIdleSystemSleep)); - assert!(!options.contains(NSActivityOptions::IdleSystemSleepDisabled), "the channel must not keep the Mac awake"); - keep_answering(); -} diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index 4a74c6bdfb..a12c6a96b7 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -22,6 +22,7 @@ vectorcraft-format = { workspace = true } vectorcraft-tools = { workspace = true } vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } +craft-automation = { workspace = true } serde_json = { workspace = true } log = { workspace = true } diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 97c990b88e..e5c4f397a5 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -1,10 +1,10 @@ //! Where MCP tool calls end up: a control-channel method call. -use std::io::{BufReader, Write}; -use std::net::{TcpStream, ToSocketAddrs}; -use std::time::Duration; +use std::net::{SocketAddr, ToSocketAddrs}; -use serde_json::{Value, json}; +use craft_automation::args::{ControlOptions, EnvNames}; +use craft_automation::client::ControlClient; +use serde_json::Value; /// Something that answers control-channel methods (`engine.execute`, `document.inspect`, /// `ui.pointer`, `ui.render`, `app.export`, …). See `vectorcraft_ui_egui::control` for the list. @@ -17,171 +17,79 @@ pub trait Backend { fn describe(&self) -> String; } +/// The control token a running app was started with: `VECTORCRAFT_CONTROL_TOKEN`, else the +/// trimmed content of the file `VECTORCRAFT_CONTROL_TOKEN_FILE` names. One place reads it, for +/// MCP and the CLI alike. +pub fn control_token() -> Result { + let names = EnvNames::for_app("VECTORCRAFT"); + let options = ControlOptions::from_env(&names).map_err(|e| e.to_string())?; + let missing = || format!("no control token: set {} (or {} to a file that holds it)", names.token, names.token_file); + if let Some(token) = options.token { + return Ok(token); + } + let file = options.token_file.ok_or_else(missing)?; + let text = std::fs::read_to_string(&file).map_err(|e| format!("cannot read the control token file {}: {e}", file.display()))?; + match text.trim() { + "" => Err(missing()), + token => Ok(token.to_owned()), + } +} + /// A running VectorCraft app, reached through its loopback control port. pub struct Remote { addr: String, - conn: Option<(BufReader, TcpStream)>, - next_id: u64, + sock: SocketAddr, + token: String, + client: Option, } -/// Longest accepted control-channel reply line (bytes, without the newline). The app answers -/// small JSON objects except for images, which reach tens of megabytes; anything longer is refused -/// and the connection dropped, so a faulty endpoint can't make the server buffer without bound -/// (#1727). -const MAX_REPLY_BYTES: usize = 256 * 1024 * 1024; - impl Remote { - /// Connect to `addr` (e.g. `127.0.0.1:7979`), failing fast when nothing is listening. - pub fn connect(addr: &str) -> std::io::Result { - let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1 }; - r.reconnect()?; - Ok(r) + /// Connect to `addr` (e.g. `127.0.0.1:7979`) with the app's control `token`, failing fast when + /// nothing is listening. + pub fn connect(addr: &str, token: &str) -> std::io::Result { + let sock = addr + .to_socket_addrs()? + .next() + .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {addr}")))?; + let client = ControlClient::connect(sock, token).map_err(std::io::Error::other)?; + Ok(Self { addr: addr.to_string(), sock, token: token.to_string(), client: Some(client) }) } pub fn addr(&self) -> &str { &self.addr } - #[cfg(test)] - pub(crate) fn connection_probe(&self) -> TcpStream { - self.conn.as_ref().unwrap().1.try_clone().unwrap() - } - - fn reconnect(&mut self) -> std::io::Result<()> { - self.conn = None; - let mut last = std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {}", self.addr)); - for sa in self.addr.to_socket_addrs()? { - match TcpStream::connect_timeout(&sa, Duration::from_millis(800)) { - Ok(s) => { - s.set_nodelay(true).ok(); - // The app answers within 60 s (its own timeout); leave headroom. - s.set_read_timeout(Some(Duration::from_secs(90))).ok(); - let read = s.try_clone()?; - self.conn = Some((BufReader::new(read), s)); - return Ok(()); - } - Err(e) => last = e, - } + /// The open connection; a new one when the app closed the last (an idle connection, a restart). + fn open_client(&mut self, method: &str) -> Result<&mut ControlClient, String> { + if !self.client.as_ref().is_some_and(ControlClient::is_open) { + self.client = None; + let client = ControlClient::connect(self.sock, &self.token) + .map_err(|e| format!("VectorCraft app at {} is not reachable: {e}; `{method}`: nothing was sent", self.addr))?; + self.client = Some(client); } - Err(last) - } - - fn prepare_connection(&mut self) -> std::io::Result<()> { - if let Some((_, stream)) = self.conn.as_ref() { - stream.set_nonblocking(true)?; - let probe = stream.peek(&mut [0]); - stream.set_nonblocking(false)?; - match probe { - // Closed by the app, or holding bytes nobody asked for (an app that explains why it - // closes): either way no reply to the next request can be read from it. - Ok(_) => self.conn = None, - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {} - Err(_) => self.conn = None, - } - } - if self.conn.is_none() { - self.reconnect()?; - } - Ok(()) - } - - /// Wait until the app starts to answer, giving up when the call is cancelled - /// ([`vectorcraft_engine::cancel`]): the app has no way to stop what it runs, but this server - /// stops waiting for it (the connection is dropped, so a late answer can't be mistaken for - /// the next call's). Without a cancellable call this is just the read the caller does next. - fn wait_for_reply(stream: &TcpStream) -> std::io::Result<()> { - const POLL: Duration = Duration::from_millis(100); - const LIMIT: Duration = Duration::from_secs(90); - if !vectorcraft_engine::cancel::is_cancellable() { - return Ok(()); - } - let start = std::time::Instant::now(); - let kept = stream.read_timeout()?; - stream.set_read_timeout(Some(POLL))?; - let outcome = loop { - match stream.peek(&mut [0]) { - // Bytes (or the end of the stream) to read now. - Ok(_) => break Ok(()), - Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => { - if vectorcraft_engine::cancel::is_cancelled() { - break Err(std::io::Error::new( - std::io::ErrorKind::Interrupted, - "cancelled; the app may still finish what it was asked, which can't be stopped from here", - )); - } - if start.elapsed() >= LIMIT { - break Err(e); - } - } - Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} - Err(e) => break Err(e), - } - }; - stream.set_read_timeout(kept)?; - outcome - } - - fn roundtrip(&mut self, line: &str) -> std::io::Result { - let Some((reader, writer)) = self.conn.as_mut() else { - return Err(std::io::Error::new(std::io::ErrorKind::NotConnected, "not connected to the app")); - }; - writer.write_all(line.as_bytes())?; - writer.write_all(b"\n")?; - writer.flush()?; - Self::wait_for_reply(writer)?; - let mut buf = Vec::new(); - if !crate::server::read_line_capped(reader, &mut buf, MAX_REPLY_BYTES)? { - return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "control channel closed")); - } - if buf.len() > MAX_REPLY_BYTES { - // A faulty endpoint's endless line is refused rather than buffered: the connection is - // dropped and the call reports uncertainty, as for any reply that never arrived whole. - return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("control reply longer than {MAX_REPLY_BYTES} bytes"))); - } - String::from_utf8(buf).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) + self.client.as_mut().ok_or_else(|| format!("VectorCraft app at {} is not reachable; `{method}`: nothing was sent", self.addr)) } } impl Backend for Remote { fn call(&mut self, method: &str, params: Value) -> Result { - self.prepare_connection().map_err(|e| { - self.conn = None; - format!("VectorCraft app at {} is not reachable: {e}; `{method}`: nothing was sent", self.addr) - })?; - let id = self.next_id; - self.next_id += 1; - let line = json!({"id": id, "method": method, "params": params}).to_string(); - let v: Value = self - .roundtrip(&line) - .and_then(|reply| { - serde_json::from_str(reply.trim()) - .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, format!("bad reply from app: {e}"))) - }) - .map_err(|e| { - self.conn = None; - format!("VectorCraft app at {}: `{method}` failed: {e}; operation may have completed; inspect state before retrying", self.addr) - })?; - if v.get("id").is_none() && v.get("ok").and_then(Value::as_bool) == Some(false) { - // The app's refusals carry no id (too many connections, a line it would not read): - // it ran nothing and closes the connection, so the next call starts a fresh one. - self.conn = None; - let why = v.get("error").and_then(Value::as_str).unwrap_or("unknown error"); - return Err(format!("VectorCraft app at {} refused `{method}`: {why}; nothing was run", self.addr)); - } - if v.get("id") != Some(&json!(id)) { - // Not the answer to this call: the stream is desynchronised (or the endpoint faulty), - // so the connection is dropped and the next call starts a fresh one. The operation may - // still have completed, as with any reply that never arrived whole (#1728). - self.conn = None; - return Err(format!( - "VectorCraft app at {}: reply id mismatch (expected {id}); connection dropped; operation may have completed; inspect state before retrying", - self.addr - )); - } - if v.get("ok").and_then(Value::as_bool) == Some(true) { - Ok(v.get("result").cloned().unwrap_or(Value::Null)) + let addr = self.addr.clone(); + let client = self.open_client(method)?; + // The app can't stop what it runs, but a cancelled call stops waiting for it. + let cancellable = vectorcraft_engine::cancel::is_cancellable(); + let result = if cancellable { + client.call_until(method, params, &vectorcraft_engine::cancel::is_cancelled) } else { - Err(v.get("error").and_then(Value::as_str).unwrap_or("unknown error").to_string()) + client.call(method, params) + }; + match result { + Ok(value) => Ok(value), + // The connection survived: the app answered with this error. + Err(e) if client.is_open() => Err(e), + Err(_) if cancellable && vectorcraft_engine::cancel::is_cancelled() => Err(format!( + "VectorCraft app at {addr}: `{method}` cancelled; the app may still finish what it was asked, which can't be stopped from here" + )), + Err(e) => Err(format!("VectorCraft app at {addr}: `{method}` failed: {e}; operation may have completed; inspect state before retrying")), } } diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index fcbc9cf708..931e910315 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -314,7 +314,7 @@ pub fn tool_definitions() -> Vec { tool( "answer_dialog", "Answer dialog", - "Set fields of the desktop app's open dialog in order, then confirm (OK) or cancel it, as the control protocol's ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel do. The app stores all the fields or none and answers that same dialog in the same request (ui.dialog.set with action). When the app refuses the ui.dialog.set, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. inspect_ui shows the open dialog and its fields (ui.dialog). After invoke_menu app.quit or file.close replies {\"pending\":\"saveChanges\"}: {action:\"confirm\"} saves, {set:[{field:\"discard\",value:true}],action:\"confirm\"} closes without saving, {action:\"cancel\"} cancels. Returns {dialog, result}: the dialog after the fields were set, and the reply to confirm or cancel. Desktop app only.", + "Set fields of the desktop app's open dialog in order, then confirm (OK) or cancel it, as the control protocol's ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel do. The app stores all the fields or none and answers that same dialog in the same request (ui.dialog.set with action). When the app refuses the ui.dialog.set, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. inspect_ui shows the open dialog and its fields (ui.dialog). After invoke_menu app.quit or file.close replies {\"pending\":\"saveChanges\"}: {action:\"confirm\"} saves, {set:[{field:\"choice\",value:\"dontSave\"}],action:\"confirm\"} closes without saving, {action:\"cancel\"} cancels. Returns {dialog, result}: the dialog after the fields were set, and the reply to confirm or cancel. Desktop app only.", obj( json!({ "set": { diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 5ef64dfa3f..2ab3ed1eb6 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -1,164 +1,88 @@ -use super::{ - MAX_PENDING_SCREENSHOTS, MAX_SCREENSHOT_BYTES, MAX_SCREENSHOT_TOTAL_BYTES, PendingScreenshot, QueuedScreenshot, SCREENSHOT_TIMEOUT_MS, - VectorcraftApp, canvas, file_access, json, now_ms, -}; +use craft_automation::screenshot::{DocumentId, Finished, settle_ms}; +use craft_ui::runtime::motion; +use craft_ui::runtime::windows::WindowHost; +use serde_json::json; +use vectorcraft_engine::file_access::AutomationRoots; + +use super::{VectorcraftApp, file_access}; use crate::control; +use crate::services::WriteFn; + +/// Writes a capture's PNG where the app's file authority allows: through the host's writer, inside +/// the automation roots. An error shows the `path` sent as its file name only when it lies outside +/// the read root, as every reply does (`hiding`). +fn write_automation_file( + roots: Option<&std::sync::Arc>, + write: &mut Option, + hiding: &control::Hiding, + path: &str, + png: &[u8], +) -> Result<(), String> { + file_access::confine(roots, || { + let written = match write { + Some(write) => write(path, png), + None => Err("no writer configured".to_owned()), + }; + // PLAN: assumed `Hiding::hide_error(&self, error: &str, sent: &Value) -> String` (hub-w2's split of `hide_in_deferred_reply`) + written.map_err(|error| hiding.hide_error(&error, &json!({"path": path}))) + }) +} impl VectorcraftApp { - pub(crate) fn drain_control(&mut self, ctx: &egui::Context) { - let Some(rx) = self.control_rx.take() else { return }; - let mut handled = 0; - while handled < control::MAX_CONTROL_REQUESTS_PER_FRAME { - let Some(req) = self.deferred_control.take().or_else(|| rx.try_recv().ok()) else { break }; - // Synthetic input sent before this tool action was dropped (see - // `discard_stale_injected_batch`): it would reach the tool without that input. - let tool_action = matches!(req.method.as_str(), "ui.pointer" | "ui.tool.select"); - if tool_action && req.made_before(self.synthetic_dropped_before) { - // One its caller gave up is skipped without counting toward this frame's limit. - if req.claim() { - handled += 1; - let _ = req.reply.send(json!({ - "ok": false, - "error": "input sent before this tool action was dropped because the document, dialog or focus changed" - })); - } - continue; - } - // `ui.pointer` and `ui.tool.select` act at once, while `ui.key` and other synthetic - // input reach the tool in a later UI pass. Wait for that earlier input, so a key - // pressed during a drag reaches its tool before a pointer event or tool switch. - // One its caller gave up meanwhile is dropped below instead of holding back the rest. - if tool_action && !req.given_up() && (!self.synthetic.is_empty() || self.synthetic_injected) { - self.deferred_control = Some(req); - ctx.request_repaint(); - break; - } - // Its caller stopped waiting (the app was busy or its window not drawn for too long) - // and was told it won't run: an edit applied now would come from nowhere (#1725). - if !req.claim() { - continue; - } - handled += 1; - let reply = req.reply.clone(); - // Guarded per request: a panic must not drop the channel (taken out of `self` above). + /// Once per host iteration: answers the finished captures, runs the control requests the + /// transport queued, each inside the automation roots, and answers the requests that waited for + /// injected input. + pub(crate) fn run_control(&mut self, ctx: &egui::Context) { + let host = WindowHost::of(ctx); + let document = self.document_identity(); + self.channel.captures.note_windows(&host, document); + let finished = self.channel.captures.drain(motion::now(), document); + self.finish_captures(finished); + let settle = settle_ms(ctx.global_style().animation_time); + while let Some(req) = self.channel.next_request() { let roots = self.automation_roots.clone(); self.ui.answering_control = true; + // Guarded per request: a panic must not stop the requests behind it. let answer = file_access::confine(roots.as_ref(), || vectorcraft_engine::guard::catch_panic(|| control::handle(self, ctx, &req))); self.ui.answering_control = false; - let outcome = match answer { - Ok(outcome) => outcome, + let reply = match answer { + Ok(reply) => reply, Err(msg) => { self.picks.recover(); self.session.set_replaying(false); control::err(format!("internal error: {msg} (please report this bug)")) } }; - match outcome { - control::Outcome::Done(v) => { - let _ = reply.send(v); - } - control::Outcome::Screenshot { path, data } => { - // Admit with the shared ceilings (4 requests, 128 MiB each, 256 MiB together) - // before issue, reserving the checked bytes this viewport would need. - match self.screenshot_pixels(ctx) { - Ok((width, height, bytes)) if bytes > MAX_SCREENSHOT_BYTES => { - let _ = reply.send(json!({"ok": false, "error": format!( - "screenshot would use {bytes} bytes ({width}×{height}), over the {MAX_SCREENSHOT_BYTES}-byte limit" - )})); - } - Ok((width, height, bytes)) if data && path.is_none() && bytes > control::MAX_SCREENSHOT_PNG_REPLY_BYTES => { - let _ = reply.send(json!({"ok": false, "error": format!( - "a PNG reply of this {width}×{height} screenshot ({bytes} bytes of pixels) would exceed the {}-byte reply-encoding limit; write it to a path instead", - control::MAX_SCREENSHOT_PNG_REPLY_BYTES - )})); - } - Ok((_, _, _)) if self.pending_screenshots.len() >= MAX_PENDING_SCREENSHOTS => { - let _ = reply.send(json!({"ok": false, "error": format!( - "already {MAX_PENDING_SCREENSHOTS} screenshots are waiting; wait for one to finish" - )})); - } - Ok((width, height, bytes)) if self.screenshot_reserved.saturating_add(bytes) > MAX_SCREENSHOT_TOTAL_BYTES => { - let _ = reply.send(json!({ - "ok": false, - "error": format!( - "screenshots already reserved {} bytes; {bytes} more ({width}×{height}) would pass the {MAX_SCREENSHOT_TOTAL_BYTES}-byte limit", - self.screenshot_reserved - ) - })); - } - Ok((_, _, bytes)) => { - self.screenshot_token += 1; - let id = self.screenshot_token; - let settle = ctx.global_style().animation_time as f64 * 2000.0 + 80.0; - let due_ms = now_ms() + settle; - self.screenshot_reserved = self.screenshot_reserved.saturating_add(bytes); - self.queued_screenshots.push(QueuedScreenshot { id, due_ms, frames: 0 }); - let document = self.document_identity(); - self.pending_screenshots.push(PendingScreenshot { - id, - path, - data, - reply, - deadline_ms: due_ms + SCREENSHOT_TIMEOUT_MS, - reserved_bytes: bytes, - document, - slot: None, - issued: None, - attempts: 0, - }); - } - Err(e) => { - let _ = reply.send(json!({"ok": false, "error": e})); - } - } - } - control::Outcome::AfterToolEdit { from, to, document } => { - self.pointer_replies.push(control::PendingPointerReply { from, to, document, reply }); - } - } + // PLAN: `job_finished` for a `ui.pointer` reply that waits on the tool's edit (`Reply::AfterJob`) is called where that edit is applied (hub-w2, chunk plan w9) + let document = self.document_identity(); + self.channel.settle(req, reply, document, settle); } - if handled == control::MAX_CONTROL_REQUESTS_PER_FRAME { - // Leave later requests on the channel and schedule another frame to serve them. - ctx.request_repaint(); - } - self.control_rx = Some(rx); + self.channel.poll_input(&host); } - /// Sends the `ui.pointer` replies that wait for the tool's edit once their events have been - /// made and the edit is applied. The canvas checks on the tool each frame it is drawn; this - /// checks too, for frames without it. - pub(crate) fn answer_pointer_replies(&mut self, ctx: &egui::Context) { - // Those whose events the canvas's check made go first, before this check makes the input - // held after them. - self.send_pointer_replies(); - if self.pointer_replies.is_empty() { + /// The UI phase of a pass: counts the pass toward the captures' settling and issues the due + /// ones; a capture that expired or lost its window is answered here. + pub(crate) fn issue_captures(&mut self, ctx: &egui::Context) { + let document = self.document_identity(); + self.channel.captures.note_pass(); + let finished = self.channel.captures.issue(&WindowHost::of(ctx), motion::now(), document); + self.finish_captures(finished); + } + + /// Replies to finished captures; a capture with a path is written by [`write_automation_file`]. + fn finish_captures(&mut self, finished: Vec) { + if finished.is_empty() { return; } - if self.session.tool_editing() { - let r = self.session.tool_poll(self.view_info(), false); - canvas::apply_requests(self, r); - } - self.send_pointer_replies(); - if !self.pointer_replies.is_empty() { - ctx.request_repaint_after(std::time::Duration::from_millis(16)); - } - } - - /// Sends the waiting `ui.pointer` replies whose events have been made. - fn send_pointer_replies(&mut self) { - for pending in std::mem::take(&mut self.pointer_replies) { - let control::PendingPointerReply { from, to, document, reply } = pending; - if self.session.input_applied(from, to) { - let _ = reply.send(control::pointer_reply_for(self, document)); - } else { - self.pointer_replies.push(control::PendingPointerReply { from, to, document, reply }); - } - } + let hiding = control::deferred_hiding(self); + let roots = self.automation_roots.clone(); + let write = &mut self.services.write; + self.channel.finish_captures(finished, &mut |path, png| write_automation_file(roots.as_ref(), write, &hiding, path, png)); } /// The active document's identity: its process-unique uid and revision. A capture records it /// at admission and issuance and refuses to answer with a different document or undo state. - pub(super) fn document_identity(&self) -> Option<(u64, u64)> { - self.session.active().map(|document| (document.uid, document.revision)) + pub(super) fn document_identity(&self) -> Option { + self.session.active().map(|document| DocumentId::new(document.uid, document.revision)) } } diff --git a/crates/ui-egui/src/app/screenshot.rs b/crates/ui-egui/src/app/screenshot.rs deleted file mode 100644 index c34d022e50..0000000000 --- a/crates/ui-egui/src/app/screenshot.rs +++ /dev/null @@ -1,181 +0,0 @@ -use super::{ - Arc, CaptureEpoch, MAX_SCREENSHOT_BYTES, MAX_SCREENSHOT_TOTAL_BYTES, QueuedScreenshot, SCREENSHOT_SETTLE_FRAMES, SCREENSHOT_TIMEOUT_ERROR, - VectorcraftApp, file_access, json, now_ms, -}; -use crate::control; - -impl VectorcraftApp { - /// The image size (pixels) and checked byte count a capture of the current viewport would - /// have: the window's content rect times the current DPI/zoom. The viewport's own `inner_rect` - /// is the fresh source; `content_rect` is only a fallback for hosts that do not report one - /// (Wayland, headless), and a logic-only pass leaves it from the last shown frame. Issuance in - /// a real UI pass recomputes this and re-checks the budget, so a stale admission size cannot - /// let an oversized image through. - pub(super) fn screenshot_pixels(&self, ctx: &egui::Context) -> Result<(usize, usize, usize), String> { - let rect = ctx.input(|i| i.viewport().inner_rect).unwrap_or_else(|| ctx.content_rect()); - let scale = f64::from(ctx.pixels_per_point()); - let pixels = |points: f32, what: &str| -> Result { - let value = f64::from(points) * scale; - if !value.is_finite() || !(1.0..=100_000.0).contains(&value) { - return Err(format!("the window's {what} ({points} points × {scale} DPI) cannot size a screenshot")); - } - Ok(value.round() as usize) - }; - let width = pixels(rect.width(), "width")?; - let height = pixels(rect.height(), "height")?; - let bytes = width - .checked_mul(height) - .and_then(|n| n.checked_mul(4)) - .ok_or_else(|| format!("a {width}×{height} screenshot's byte count overflows"))?; - Ok((width, height, bytes)) - } - - /// Issue the first due capture of a settled UI pass, at most one in flight: the one-shot - /// callback makes correlation trivial, and serializing bounds readback memory. - pub(super) fn issue_screenshots(&mut self, ctx: &egui::Context) { - if self.pending_screenshots.iter().any(|p| p.slot.is_some()) { - ctx.request_repaint_after(std::time::Duration::from_millis(16)); - return; - } - for q in &mut self.queued_screenshots { - q.frames = q.frames.saturating_add(1); - } - let now = now_ms(); - let Some(pos) = self.queued_screenshots.iter().position(|q| now >= q.due_ms && q.frames >= SCREENSHOT_SETTLE_FRAMES) else { - if !self.queued_screenshots.is_empty() { - ctx.request_repaint_after(std::time::Duration::from_millis(16)); - } - return; - }; - let queued = self.queued_screenshots.remove(pos); - let Some(index) = self.pending_screenshots.iter().position(|p| p.id == queued.id) else { return }; - let document = self.document_identity(); - if self.pending_screenshots[index].document != document { - self.fail_screenshot(index, "the document changed while the screenshot was pending"); - return; - } - let (width, height, bytes) = match self.screenshot_pixels(ctx) { - Ok(v) => v, - Err(e) => { - self.fail_screenshot(index, &e); - return; - } - }; - let (data, path, previous) = - (self.pending_screenshots[index].data, self.pending_screenshots[index].path.is_some(), self.pending_screenshots[index].reserved_bytes); - if data && !path && bytes > control::MAX_SCREENSHOT_PNG_REPLY_BYTES { - let e = format!( - "a PNG reply of this {width}×{height} screenshot ({bytes} bytes of pixels) no longer fits the {}-byte reply-encoding limit; write it to a path instead", - control::MAX_SCREENSHOT_PNG_REPLY_BYTES - ); - self.fail_screenshot(index, &e); - return; - } - if bytes > MAX_SCREENSHOT_BYTES || self.screenshot_reserved.saturating_sub(previous).saturating_add(bytes) > MAX_SCREENSHOT_TOTAL_BYTES { - let e = format!("the window grew since the screenshot was admitted: {width}×{height} no longer fits the capture budget"); - self.fail_screenshot(index, &e); - return; - } - self.screenshot_reserved = self.screenshot_reserved.saturating_sub(previous).saturating_add(bytes); - let viewport = ctx.viewport_id(); - let (slot, callback) = craft_ui::capture::CaptureSlot::new(ctx, viewport, MAX_SCREENSHOT_BYTES); - { - let pending = &mut self.pending_screenshots[index]; - pending.reserved_bytes = bytes; - pending.issued = Some(CaptureEpoch { geometry: self.geometry_epoch, viewport, document, width, height }); - pending.slot = Some(slot); - } - // A pending `Screenshot` asks for the paint it needs, even while hidden. - ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(callback)); - ctx.request_repaint(); - } - - /// Answer a pending request with an error and release its reservation. - fn fail_screenshot(&mut self, index: usize, error: &str) { - if index >= self.pending_screenshots.len() { - return; - } - let pending = self.pending_screenshots.remove(index); - self.queued_screenshots.retain(|q| q.id != pending.id); - self.screenshot_reserved = self.screenshot_reserved.saturating_sub(pending.reserved_bytes); - if let Some(slot) = pending.slot { - slot.cancel(); - } - let _ = pending.reply.send(json!({"ok": false, "error": error})); - } - - /// Take completed captures on the UI thread only, verify they still match the document and - /// geometry they were issued for, and write them under the automation roots. A late completion - /// (after a timeout or close) has already been canceled with its slot, so it writes nothing. - /// - /// This runs in `tick`, as both hosts call logic and the UI on the same thread. `save_screenshot` - /// and `file_access::confine` here, and the `&mut self` write, must move with it if logic ever - /// runs off the UI thread. - pub(super) fn collect_screenshots(&mut self, ctx: &egui::Context) { - if self.pending_screenshots.is_empty() { - return; - } - let mut completed: Vec<(usize, Result, craft_ui::capture::CaptureError>)> = vec![]; - for (index, pending) in self.pending_screenshots.iter().enumerate() { - if let Some(slot) = &pending.slot - && let Some(result) = slot.take() - { - completed.push((index, result)); - } - } - let now = now_ms(); - let document = self.document_identity(); - for (index, result) in completed.into_iter().rev() { - let Some((id, issued, deadline)) = self.pending_screenshots.get(index).map(|p| (p.id, p.issued, p.deadline_ms)) else { continue }; - match result { - // The frame came only after the request's deadline: it is late even though the - // callback had stored it before this pass took it. Do not encode or write it. - _ if now >= deadline => { - self.fail_screenshot(index, SCREENSHOT_TIMEOUT_ERROR); - } - Ok(_) if issued.is_some_and(|e| e.document != document) => { - self.fail_screenshot(index, "the document changed while the screenshot was pending"); - } - Ok(image) => { - let size = (image.size[0], image.size[1]); - let stale = - issued.is_none_or(|e| e.geometry != self.geometry_epoch || e.viewport != ctx.viewport_id() || (e.width, e.height) != size); - if stale { - // Resize, DPI or zoom changed while the capture was in flight: a fresh slot - // and a fresh frame, not the old pixels. Attempts are bounded. - let retry = self.pending_screenshots[index].attempts == 0; - self.pending_screenshots[index].attempts = self.pending_screenshots[index].attempts.saturating_add(1); - self.pending_screenshots[index].slot = None; - self.pending_screenshots[index].issued = None; - if retry { - self.queued_screenshots.insert(0, QueuedScreenshot { id, due_ms: now_ms(), frames: 0 }); - } else { - self.fail_screenshot(index, "the window changed while the screenshot was in flight"); - } - continue; - } - let pending = self.pending_screenshots.remove(index); - self.screenshot_reserved = self.screenshot_reserved.saturating_sub(pending.reserved_bytes); - let roots = self.automation_roots.clone(); - let reply = file_access::confine(roots.as_ref(), || { - let mut reply = control::save_screenshot(self, &image, pending.path.as_deref(), pending.data); - control::hide_in_deferred_reply(self, &mut reply, &json!({"path": pending.path})); - reply - }); - let _ = pending.reply.send(reply); - } - Err(e) => { - let error = format!("the screenshot could not be used: {e}"); - self.fail_screenshot(index, &error); - } - } - } - let timed_out: Vec = self.pending_screenshots.iter().enumerate().filter(|(_, p)| now >= p.deadline_ms).map(|(i, _)| i).collect(); - for index in timed_out.into_iter().rev() { - self.fail_screenshot(index, SCREENSHOT_TIMEOUT_ERROR); - } - if !self.pending_screenshots.is_empty() { - ctx.request_repaint_after(std::time::Duration::from_millis(16)); - } - } -} diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 96c4880d39..d25f005f96 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -2,13 +2,14 @@ use serde_json::{Value, json}; use vectorcraft_engine::Session; use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; -use super::{ControlRequest, MAX_DIALOG_FIELDS, Outcome, handle}; -use crate::state::Dialog; +use craft_automation::{ControlRequest, Reply}; + +use super::handle; use crate::{Services, VectorcraftApp}; fn input_request(app: &mut VectorcraftApp, method: &str, params: Value) -> Value { let (req, _) = ControlRequest::new(method, params); - let Outcome::Done(r) = handle(app, &egui::Context::default(), &req) else { panic!("expected immediate reply") }; + let Reply::Done(r) = handle(app, &egui::Context::default(), &req) else { panic!("expected immediate reply") }; r } @@ -592,242 +593,18 @@ fn deferred_pointer_reply_uses_the_gesture_document_after_file_new() { app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); app.run("select.set", json!({"ids": [id]})).unwrap(); - let (reply, received) = std::sync::mpsc::channel(); - let at = app.session.input_count(); - app.pointer_replies.push(super::PendingPointerReply { from: at, to: at, document: app.session.active().map(|d| d.uid), reply }); + let gesture = app.session.active().map(|d| d.uid); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); app.run("tool.select", json!({"tool": "rectangle"})).unwrap(); - app.answer_pointer_replies(&egui::Context::default()); - let result = received.try_recv().unwrap(); + let result = super::pointer_reply_for(&app, gesture); assert_eq!(result["ok"], true, "{result}"); assert_eq!(result["result"]["selection"], json!([id])); assert_eq!(result["result"]["key"], Value::Null); assert_eq!(result["result"]["tool"], "rectangle"); } -#[test] -fn control_lists_and_selects_optional_addon_tools() { - let mut app = VectorcraftApp::new(Session::new(), Services::default()); - let listed = input_request(&mut app, "ui.tool.list", json!({})); - assert_eq!(listed["ok"], true); - let groups = listed["result"].as_array().unwrap(); - for tool in vectorcraft_tools::addons::GROUPS.iter().flat_map(|group| group.iter()) { - let matching: Vec<_> = groups.iter().flat_map(|group| group.as_array().unwrap()).filter(|entry| entry["id"] == tool.id).collect(); - assert_eq!(matching.len(), 1, "{}", tool.id); - assert_eq!(matching[0]["label"], tool.label); - assert!(matching[0]["shortcut"].is_null()); - let selected = input_request(&mut app, "ui.tool.select", json!({"tool": tool.id})); - assert_eq!(selected["ok"], true, "{selected}"); - assert_eq!(selected["result"]["tool"], tool.id); - } -} - -#[test] -fn ui_set_turns_the_image_trace_preview_off_and_on() { - let mut app = VectorcraftApp::new(Session::new(), Services::default()); - assert!(app.ui.image_trace_preview); - for on in [false, true] { - let r = input_request(&mut app, "ui.set", json!({"imageTracePreview": on})); - assert_eq!(r["ok"], true, "{r}"); - assert_eq!(app.ui.image_trace_preview, on); - } -} - -/// #3797: `ui.set` `outline` sets the active document's view; without a document it is an error -/// and sets nothing else either. -#[test] -fn ui_set_outline_sets_the_active_documents_view() { - let mut app = VectorcraftApp::new(Session::new(), Services::default()); - for params in [json!({"outline": false}), json!({"outline": true, "grid": true})] { - let r = input_request(&mut app, "ui.set", params); - assert_eq!(r["ok"], false, "{r}"); - } - assert!(!app.ui.view.grid, "nothing is set"); - app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); - app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); - let r = input_request(&mut app, "ui.set", json!({"outline": true})); - assert_eq!(r["ok"], true, "{r}"); - assert!(app.outline_view()); - assert_eq!(app.views.iter().map(|v| v.outline).collect::>(), [false, true], "the other document stays in Preview"); -} - -#[test] -fn the_image_trace_preview_is_a_command() { - let mut app = VectorcraftApp::new(Session::new(), Services::default()); - assert!(crate::menus::UI_COMMANDS.iter().any(|c| c.0 == "imageTrace.preview")); - assert_eq!(app.run("imageTrace.preview", json!({})), Ok(json!(false)), "toggles"); - assert!(!app.ui.image_trace_preview); - assert_eq!(app.run("imageTrace.preview", json!({"on": false})), Ok(json!(false)), "stays off"); - assert_eq!(app.run("imageTrace.preview", json!({"on": true})), Ok(json!(true))); - assert!(app.ui.image_trace_preview); - assert!(app.run("imageTrace.preview", json!({"on": "yes"})).is_err()); - assert!(app.ui.image_trace_preview, "a bad value leaves it"); - let r = input_request(&mut app, "engine.execute", json!({"command": "imageTrace.preview", "params": {"on": false}})); - assert_eq!(r["ok"], true, "{r}"); - assert!(!app.ui.image_trace_preview, "the control channel reaches it"); -} - -#[test] -fn control_input_rejects_excessive_counts_before_mutation() { - // Only modest over-limit values on the baseline: never exercise an unbounded loop. - for (method, params) in [("ui.click", json!({"count": 17})), ("ui.drag", json!({"steps": 257})), ("ui.drag", json!({"steps": 2, "count": 17}))] { - let mut app = VectorcraftApp::new(Session::new(), Services::default()); - app.synthetic.push(egui::Event::Text("already queued".into())); - let before = format!("{:?}", app.synthetic); - let r = input_request(&mut app, method, params); - assert_eq!(r["ok"], false, "oversized input must be rejected: {r}"); - assert_eq!(format!("{:?}", app.synthetic), before, "rejection must preserve the entire queue"); - } -} - -#[test] -fn control_input_respects_existing_queue_budget() { - let mut app = VectorcraftApp::new(Session::new(), Services::default()); - app.synthetic = vec![egui::Event::PointerMoved(egui::pos2(1.0, 2.0)); 1023]; - let before = format!("{:?}", app.synthetic); - let r = input_request(&mut app, "ui.click", json!({})); - assert_eq!(r["ok"], false, "a whole click must fit before any part is appended"); - assert_eq!(format!("{:?}", app.synthetic), before); -} - -#[test] -fn control_input_yields_control_channel_after_frame_budget() { - let (tx, rx) = std::sync::mpsc::channel(); - let mut app = VectorcraftApp::new(Session::new(), Services::default()).with_control(rx); - let mut replies = vec![]; - for _ in 0..65 { - let (req, reply) = ControlRequest::new("ui.move", json!({"x": 1, "y": 2})); - tx.send(req).unwrap(); - replies.push(reply); - } - app.drain_control(&egui::Context::default()); - assert_eq!(replies.iter().filter(|r| r.try_recv().is_ok()).count(), 64); - assert_eq!(app.synthetic.len(), 64); - app.drain_control(&egui::Context::default()); - assert_eq!(replies.last().unwrap().try_recv().unwrap()["ok"], true); - assert_eq!(app.synthetic.len(), 65); -} - -#[test] -fn control_input_rejects_invalid_and_extreme_counts() { - for value in [json!(u64::MAX), json!(-1), json!(1.5), json!("2"), Value::Null] { - for (method, key) in [("ui.click", "count"), ("ui.drag", "count"), ("ui.drag", "steps")] { - let mut app = VectorcraftApp::new(Session::new(), Services::default()); - app.synthetic.push(egui::Event::Text("pending".into())); - let before = format!("{:?}", app.synthetic); - let mut params = json!({}); - params[key] = value.clone(); - let r = input_request(&mut app, method, params); - assert_eq!(r["ok"], false, "{method}/{key}: {r}"); - assert!(r["error"].as_str().unwrap().contains(key)); - assert_eq!(format!("{:?}", app.synthetic), before); - } - } -} - -#[test] -fn control_input_accepts_boundary_gestures_and_preserves_event_order() { - let mut app = VectorcraftApp::new(Session::new(), Services::default()); - let r = input_request( - &mut app, - "ui.drag", - json!({"x": 2, "y": 3, "toX": 20, "toY": 30, - "steps": 256, "count": 16, "button": "right", "shift": true}), - ); - assert_eq!(r["ok"], true); - assert_eq!(app.synthetic.len(), 289); - assert!(matches!(app.synthetic.first(), Some(egui::Event::PointerMoved(p)) if *p == egui::pos2(2.0, 3.0))); - assert!( - matches!(app.synthetic.get(1), Some(egui::Event::PointerButton { pressed: true, button: egui::PointerButton::Secondary, modifiers, .. }) if modifiers.shift) - ); - assert!(matches!(app.synthetic.get(257), Some(egui::Event::PointerMoved(p)) if *p == egui::pos2(20.0, 30.0))); - assert!(matches!(app.synthetic.get(258), Some(egui::Event::PointerButton { pressed: false, .. }))); - assert!(matches!(app.synthetic.last(), Some(egui::Event::PointerButton { pressed: false, pos, .. }) if *pos == egui::pos2(20.0, 30.0))); - for (method, params, events) in [ - ("ui.click", json!({}), 3), - ("ui.click", json!({"count": 2}), 5), - ("ui.drag", json!({}), 11), - ("ui.drag", json!({"steps": 0, "count": 0}), 4), - ] { - app.synthetic.clear(); - assert_eq!(input_request(&mut app, method, params)["ok"], true); - assert_eq!(app.synthetic.len(), events); - } - app.synthetic = vec![egui::Event::PointerMoved(egui::pos2(0.0, 0.0)); 1021]; - assert_eq!(input_request(&mut app, "ui.click", json!({}))["ok"], true); - assert_eq!(app.synthetic.len(), 1024, "the exact queue boundary is permitted"); -} - -#[test] -fn control_input_budget_covers_every_synthetic_method() { - for (method, params) in [ - ("ui.key", json!({"key": "Enter", "text": "x"})), - ("ui.move", json!({})), - ("ui.wheel", json!({"dy": 1})), - ("ui.text", json!({"text": "hello"})), - ("ui.click", json!({})), - ("ui.drag", json!({"steps": 1})), - ] { - let mut app = VectorcraftApp::new(Session::new(), Services::default()); - app.synthetic = vec![egui::Event::PointerMoved(egui::pos2(1.0, 2.0)); 1024]; - let before = format!("{:?}", app.synthetic); - let r = input_request(&mut app, method, params); - assert_eq!(r["ok"], false, "{method}: {r}"); - assert_eq!(format!("{:?}", app.synthetic), before); - app.synthetic.clear(); - assert_eq!(input_request(&mut app, method, json!({"key": "Enter", "steps": 1}))["ok"], true, "queue space becomes usable after draining"); - } -} - -/// `ui.dialog.set {fields}` stores the whole list in order, or nothing when an item is refused. -#[test] -fn dialog_set_stores_a_field_list_whole_or_not_at_all() { - let mut app = VectorcraftApp::new(Session::new(), Services::default()); - app.ui.dialog = Some(crate::state::Dialog::new("move", json!({"dx": "0 pt", "dy": "0 pt"}))); - let fields = |app: &VectorcraftApp| app.ui.dialog.as_ref().map(|d| serde_json::to_value(&d.fields).unwrap()); - let before = fields(&app); - for params in [ - json!({"fields": [{"field": "copy", "value": true}, {"value": 1}]}), - json!({"fields": [{"field": "copy", "value": true}, 7]}), - json!({"fields": {"field": "copy"}}), - json!({"field": "dx", "fields": [{"field": "copy", "value": true}]}), - json!({"fields": [{"field": "copy", "value": true}, {"field": "note"}]}), - ] { - let r = input_request(&mut app, "ui.dialog.set", params.clone()); - assert_eq!(r["ok"], false, "{params}: {r}"); - assert_eq!(fields(&app), before, "{params}: a refused list stores no field"); - } - let list = json!([{"field": "copy", "value": true}, {"field": "dx", "value": "3 pt"}, {"field": "dx", "value": "5 pt"}, {"field": "dy"}]); - let r = input_request(&mut app, "ui.dialog.set", json!({"fields": list})); - assert_eq!(r["ok"], true, "{r}"); - let after = fields(&app).unwrap(); - assert_eq!(after, json!({"copy": true, "dx": "5 pt", "dy": null})); - assert_eq!(r["result"]["fields"], after); - let r = input_request(&mut app, "ui.dialog.set", json!({"field": "dy", "value": "2 pt"})); - assert_eq!(r["ok"], true, "{r}"); - assert_eq!(fields(&app).unwrap()["dy"], "2 pt"); - app.ui.dialog = None; - assert_eq!(input_request(&mut app, "ui.dialog.set", json!({"fields": []}))["error"], "no dialog open"); -} - -/// `ui.dialog.set {fields}` stores at most `MAX_DIALOG_FIELDS` items; a longer list stores none. -#[test] -fn dialog_set_refuses_a_field_list_over_the_limit() { - let mut app = VectorcraftApp::new(Session::new(), Services::default()); - app.ui.dialog = Some(crate::state::Dialog::new("move", json!({"dx": "0 pt"}))); - let list = |n: usize| Value::Array((0..n).map(|i| json!({"field": "dx", "value": format!("{i} pt")})).collect()); - let r = input_request(&mut app, "ui.dialog.set", json!({"fields": list(MAX_DIALOG_FIELDS + 1)})); - assert_eq!(r["ok"], false, "{r}"); - assert_eq!(r["error"], format!("`fields` holds {} items; at most {MAX_DIALOG_FIELDS}", MAX_DIALOG_FIELDS + 1)); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields["dx"].clone()), Some(json!("0 pt")), "a refused list stores no field"); - let r = input_request(&mut app, "ui.dialog.set", json!({"fields": list(MAX_DIALOG_FIELDS)})); - assert_eq!(r["ok"], true, "{r}"); - let last = format!("{} pt", MAX_DIALOG_FIELDS - 1); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields["dx"].clone()), Some(json!(last)), "the whole list is stored, in order"); -} - /// `ui.dialog.set {fields, action}` confirms or cancels the dialog it set the fields in, within the /// same request, and replies `{dialog, result}`. A bad `action` or a refused field sets nothing and /// leaves the dialog open. @@ -869,7 +646,7 @@ fn render_takes_the_artboard_asked_for() { let mut request = |method: &str, params: Value| { let (req, reply) = ControlRequest::new(method, params); tx.send(req).unwrap(); - app.drain_control(&egui::Context::default()); + app.run_control(&egui::Context::default()); reply.try_recv().unwrap() }; let new = json!({"width": 64, "height": 64, "units": "Points", "artboards": 2}); @@ -902,48 +679,61 @@ fn render_takes_the_artboard_asked_for() { assert_eq!([&r["result"]["width"], &r["result"]["height"]].map(Value::as_u64), [Some(64), Some(64)], "null keeps the default: {r}"); } -/// The control channel's input methods refuse a number or switch of the wrong type before they -/// queue any event; omitting it keeps its default. +/// Each method of the control table reaches its handler and refuses a param of the wrong type before +/// it changes anything; the app's own commands refuse one too, and omitting it or giving null keeps +/// its default. #[test] -fn control_input_refuses_params_of_the_wrong_type() { - let move_to = |mods: Value| json!({"events": [{"kind": "move", "x": 5, "y": 5}, {"kind": "move", "x": 6, "y": 6, "mods": mods}]}); +fn the_method_table_routes_each_method_and_checks_its_params() { + { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + let listed = input_request(&mut app, "ui.tool.list", json!({})); + assert_eq!(listed["ok"], true); + let groups = listed["result"].as_array().unwrap(); + for tool in vectorcraft_tools::addons::GROUPS.iter().flat_map(|group| group.iter()) { + let matching: Vec<_> = groups.iter().flat_map(|group| group.as_array().unwrap()).filter(|entry| entry["id"] == tool.id).collect(); + assert_eq!(matching.len(), 1, "{}", tool.id); + assert_eq!(matching[0]["label"], tool.label); + assert!(matching[0]["shortcut"].is_null()); + let selected = input_request(&mut app, "ui.tool.select", json!({"tool": tool.id})); + assert_eq!(selected["ok"], true, "{selected}"); + assert_eq!(selected["result"]["tool"], tool.id); + } + assert!(app.ui.image_trace_preview); + for on in [false, true] { + let r = input_request(&mut app, "ui.set", json!({"imageTracePreview": on})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(app.ui.image_trace_preview, on); + } + let r = input_request(&mut app, "engine.execute", json!({"command": "imageTrace.preview", "params": {"on": false}})); + assert_eq!(r["ok"], true, "{r}"); + assert!(!app.ui.image_trace_preview, "the control channel reaches the command"); + // #3797: `ui.set` `outline` sets the active document's view; without a document it is an + // error and sets nothing else either. + for params in [json!({"outline": false}), json!({"outline": true, "grid": true})] { + let r = input_request(&mut app, "ui.set", params); + assert_eq!(r["ok"], false, "{r}"); + } + assert!(!app.ui.view.grid, "nothing is set"); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = input_request(&mut app, "ui.set", json!({"outline": true})); + assert_eq!(r["ok"], true, "{r}"); + assert!(app.outline_view()); + assert_eq!(app.views.iter().map(|v| v.outline).collect::>(), [false, true], "the other document stays in Preview"); + } for (method, params, key) in [ - ("ui.move", json!({"x": "10"}), "x"), - ("ui.move", json!({"y": true}), "y"), - ("ui.wheel", json!({"dy": "1"}), "dy"), - ("ui.wheel", json!({"dy": 1, "shift": "yes"}), "shift"), - ("ui.click", json!({"x": [1]}), "x"), - ("ui.click", json!({"cmd": 1}), "cmd"), - ("ui.drag", json!({"toX": "5"}), "toX"), - ("ui.key", json!({"key": "Enter", "alt": "true"}), "alt"), ("ui.resize", json!({"width": "800"}), "width"), ("ui.screenshot", json!({"focus": "no"}), "focus"), - ("ui.screenshot", json!({"data": 1}), "data"), ("ui.set", json!({"rulers": "true"}), "rulers"), ("ui.set", json!({"grid": true, "controlBar": 0}), "controlBar"), - ("ui.pointer", json!({"events": [{"kind": "move", "x": "5", "y": 0}]}), "x"), - ("ui.pointer", move_to(json!({"shift": "yes"})), "mods"), - ("ui.pointer", move_to(json!([true])), "mods"), - ("ui.pointer", json!({"mods": "shift", "events": [{"kind": "move", "x": 1, "y": 1}]}), "mods"), ] { let mut app = VectorcraftApp::new(Session::new(), Services::default()); - app.synthetic.push(egui::Event::Text("pending".into())); - let before = (format!("{:?}", app.synthetic), app.ui.view.rulers, app.ui.view.grid, app.ui.control_bar); + let before = (app.ui.view.rulers, app.ui.view.grid, app.ui.control_bar); let r = input_request(&mut app, method, params.clone()); assert_eq!(r["ok"], false, "{method} {params}: {r}"); assert!(r["error"].as_str().is_some_and(|e| e.contains(&format!("`{key}`"))), "{method} {params}: {r}"); - let after = (format!("{:?}", app.synthetic), app.ui.view.rulers, app.ui.view.grid, app.ui.control_bar); - assert_eq!(after, before, "{method} {params}: nothing is queued or set"); + assert_eq!((app.ui.view.rulers, app.ui.view.grid, app.ui.control_bar), before, "{method} {params}: nothing is set"); } - let mut app = VectorcraftApp::new(Session::new(), Services::default()); - assert_eq!(input_request(&mut app, "ui.move", json!({"x": null, "y": 4}))["ok"], true); - assert!(matches!(app.synthetic.first(), Some(egui::Event::PointerMoved(p)) if *p == egui::pos2(0.0, 4.0))); -} - -/// The app's own commands refuse a param of the wrong type and change nothing; omitting it or -/// giving null keeps its default. -#[test] -fn ui_commands_refuse_params_of_the_wrong_type() { let mut app = VectorcraftApp::new(Session::new(), Services::default()); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); @@ -1074,7 +864,7 @@ fn pointer_replies_name_the_key_object() { let click = |app: &mut VectorcraftApp| { let events = json!([{"kind": "down", "x": 110, "y": 20}, {"kind": "up", "x": 110, "y": 20}]); let (req, _) = ControlRequest::new("ui.pointer", json!({"events": events})); - let Outcome::Done(r) = handle(app, &ctx, &req) else { panic!("not done") }; + let Reply::Done(r) = handle(app, &ctx, &req) else { panic!("not done") }; assert_eq!(r["ok"], true, "{r}"); r["result"].get("key").cloned() }; @@ -1098,7 +888,7 @@ fn pointer_reply_waits_for_a_merge_on_another_thread() { let send = |app: &mut VectorcraftApp, events: Value| { let (req, reply) = ControlRequest::new("ui.pointer", json!({"events": events})); tx.send(req).unwrap(); - app.drain_control(&ctx); + app.run_control(&ctx); reply }; let hover = send(&mut app, json!([{"kind": "move", "x": 15, "y": 10}])); @@ -1128,7 +918,7 @@ fn pointer_reply_waits_for_a_merge_on_another_thread() { // A frame: the canvas checks on the tool, then the replies are answered. let r = app.session.tool_poll(app.view_info(), false); crate::canvas::apply_requests(&mut app, r); - app.answer_pointer_replies(&ctx); + app.run_control(&ctx); }; assert_eq!(reply["ok"], true, "{reply}"); assert_eq!(reply["result"]["selection"].as_array().map(Vec::len), Some(41), "{reply}: the selection after the merge"); @@ -1140,7 +930,7 @@ fn pointer_reply_waits_for_a_merge_on_another_thread() { assert!(start.elapsed() < std::time::Duration::from_secs(60), "no reply to the Cmd-click"); let r = app.session.tool_poll(app.view_info(), false); crate::canvas::apply_requests(&mut app, r); - app.answer_pointer_replies(&ctx); + app.run_control(&ctx); }; assert_eq!(press["result"]["selection"].as_array().map(Vec::len), Some(0), "{press}: the lent selection tool deselected after the merge"); assert_eq!(press["result"]["tool"], "shapeBuilder", "{press}"); @@ -1339,94 +1129,6 @@ fn save_and_close_apply_a_merge_on_another_thread_first() { } } -/// `ui.dialog.set` of a field the open dialog does not have is an error that lists its fields, -/// and the dialog stays as it was. Fields a dialog may not hold yet are still set: `discard` -/// with a discard button, `preview` with a live preview and the spec's `inputs`. A `__` field that -/// is not one of the controls of the dialog's kind is refused. -#[test] -fn dialog_set_refuses_a_field_the_dialog_does_not_have() { - let mut app = VectorcraftApp::new(Session::new(), Services::default()); - let fields = json!({"index": 0, "uid": 1, "name": "Untitled-1", "then": "close"}); - app.ui.dialog = Some(Dialog::new(crate::unsaved::KIND, fields.clone())); - let r = input_request(&mut app, "ui.dialog.set", json!({"field": "discrad", "value": true})); - assert_eq!(r["ok"], false, "{r}"); - assert_eq!(r["error"], "the `saveChanges` dialog has no field `discrad`; its fields: discard, index, name, then, uid"); - assert_eq!(app.ui.dialog.as_ref().map(|d| Value::Object(d.fields.clone())), Some(fields.clone())); - let r = input_request(&mut app, "ui.dialog.set", json!({"field": "__note", "value": true})); - assert_eq!(r["error"], "the `saveChanges` dialog cannot set protected field `__note`", "{r}"); - assert_eq!(app.ui.dialog.as_ref().map(|d| Value::Object(d.fields.clone())), Some(fields)); - for field in ["name", "discard"] { - let r = input_request(&mut app, "ui.dialog.set", json!({"field": field, "value": true})); - assert_eq!(r["ok"], true, "{field}: {r}"); - } - // Move opens without Copy, which its checkbox adds once clicked; Scale's options and the - // reference point belong to the other transform dialogs. - let set = |app: &mut VectorcraftApp, kind: &str, fields: Value, cases: &[(&str, bool)]| { - app.ui.dialog = Some(Dialog::new(kind, fields)); - for (field, ok) in cases { - let r = input_request(app, "ui.dialog.set", json!({"field": field, "value": true})); - assert_eq!(r["ok"], *ok, "{kind} {field}: {r}"); - } - }; - let moved = [("copy", true), ("preview", true), ("distance", true), ("discard", false), ("copies", false), ("corners", false), ("origin", false)]; - set(&mut app, "move", json!({"dx": "0 pt", "dy": "0 pt"}), &moved); - set( - &mut app, - "scale", - json!({"sx": 100, "sy": 100, "uniform": true}), - &[("corners", true), ("strokes", true), ("origin", true), ("distance", false)], - ); - set(&mut app, "rotate", json!({"angle": 0}), &[("origin", true), ("objects", true), ("corners", false)]); - set(&mut app, "rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}), &[("radius", true), ("sides", false)]); - set(&mut app, "ellipse", json!({"x": 0, "y": 0, "width": 10, "height": 10}), &[("radius", false)]); - // Corners that differ in kind and radius open without either. - let mixed = json!({"id": 1, "corners": [0, 1, 2, 3], "relativeRadii": false}); - set(&mut app, vectorcraft_tools::corners::DIALOG, mixed, &[("kind", true), ("radius", true), ("radii", false)]); - set(&mut app, "saveForOffice", json!({"ppi": 150, "transparent": false, "artboard": 0}), &[("path", true)]); - set(&mut app, "brushOptions", json!({"name": "Dots"}), &[("tips", true), ("tip", false)]); - set(&mut app, "justification", json!({"wordDesired": 100}), &[("wordMin", true), ("singleWord", true), ("wordMid", false)]); - set(&mut app, "hyphenation", json!({"hyphenate": true}), &[("afterFirst", true), ("hyphenationZone", true), ("afterfirst", false)]); - set(&mut app, "effectGallery", json!({"stack": []}), &[("browseEffect", true), ("browseParams", true), ("browse", false)]); - // A new artboard's dialog opens without a background color or display marks. - let new_board = json!({"new": true, "name": "Artboard 2", "x": 0, "y": 0, "width": 10, "height": 10}); - let marks = [ - ("color", true), - ("showCenterMark", true), - ("showCrossHairs", true), - ("showVideoSafeAreas", true), - ("videoRulerPixelAspectRatio", true), - ("showCenterMarks", false), - ]; - set(&mut app, "artboardOptions", new_board, &marks); - // Glass and Texturizer take the texture Load Texture… reads; other effects don't. - set(&mut app, "effect", json!({"__effect": "distort.glass"}), &[("textureImage", true)]); - set(&mut app, "effect", json!({"__effect": "blur.gaussian"}), &[("textureImage", false)]); - // The generic dialog takes every parameter of its command. - set(&mut app, "command", json!({"__command": "shape.rectangle", "x": 0, "y": 0}), &[("width", true), ("widht", false)]); - // Transparency Flattener Presets holds the selected preset's options before its first frame. - crate::dialogs::flattener_presets::open(&mut app, None); - let r = input_request(&mut app, "ui.dialog.set", json!({"field": "textToOutlines", "value": true})); - assert_eq!(r["ok"], true, "{r}"); - // Edit Selection takes `deleted` for each of its rows only. - app.run("file.new", json!({})).unwrap(); - app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - for name in ["A", "B"] { - app.run("select.save", json!({ "name": name })).unwrap(); - } - crate::dialogs::edit_selection::open(&mut app).unwrap(); - for (field, ok) in [("deleted1", true), ("deleted", false), ("deletedx", false), ("deleted01", false), ("deleted2", false)] { - let r = input_request(&mut app, "ui.dialog.set", json!({"field": field, "value": true})); - assert_eq!(r["ok"], ok, "{field}: {r}"); - } - let r = input_request(&mut app, "ui.dialog.set", json!({"field": "name", "value": "A"})); - assert_eq!( - r["error"], - "the `editSelection` dialog has no field `name`; its fields: count, deleted0, deleted1, name0, name1, orig0, orig1, selected" - ); - app.ui.dialog = None; - assert_eq!(input_request(&mut app, "ui.dialog.set", json!({"field": "name", "value": "A"}))["error"], "no dialog open"); -} - /// `engine.commands` lists each UI command's default shortcut on this platform: Select Last /// Selection Tool shows Ctrl+` (`Cmd+~`) on Windows and Linux and none on macOS. #[test] diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index 3affa544ec..8ffb41b381 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -9,7 +9,8 @@ use vectorcraft_engine::Session; use vectorcraft_engine::file_access::AutomationRoots; use crate::background::SharedWriteFn; -use crate::control::ControlRequest; +use craft_automation::{ControlRequest, Reply}; + use crate::state::Dialog; use crate::{Services, VectorcraftApp}; @@ -46,11 +47,19 @@ fn s(p: PathBuf) -> String { p.to_string_lossy().into_owned() } -/// One request through the control channel, as the app's frame drains it. +/// One request through the control channel, as the app's frame runs it, on a context of its own. A +/// reply that waits for injected input comes once passes of that context have taken it. fn request(app: &mut VectorcraftApp, tx: &std::sync::mpsc::Sender, method: &str, params: Value) -> Value { + let ctx = egui::Context::default(); let (req, reply) = ControlRequest::new(method, params); tx.send(req).unwrap(); - app.drain_control(&egui::Context::default()); + for _ in 0..8 { + app.run_control(&ctx); + if let Ok(r) = reply.try_recv() { + return r; + } + ctx.run_ui(egui::RawInput::default(), |_| {}); + } reply.try_recv().unwrap() } @@ -533,21 +542,43 @@ fn control_render_draws_the_trace_view_with_trace_views() { let _ = std::fs::remove_dir_all(base); } +/// A pass that carries injected input runs inside the automation roots, whatever else it holds: a +/// file the person drops outside them is refused in it, and opened in the passes after. #[test] -fn frames_with_injected_input_are_confined() { +fn a_pass_with_injected_input_runs_inside_the_roots() { + #[derive(Debug)] + struct Dropped(PathBuf); + impl egui::DroppedFile for Dropped { + fn path(&self) -> &Path { + &self.0 + } + fn bytes(&self) -> Result, String> { + std::fs::read(&self.0).map_err(|e| e.to_string()) + } + } let (mut app, tx, base) = confined("synthetic"); - let r = request(&mut app, &tx, "ui.key", json!({"key": "Escape"})); - assert_eq!(r["ok"], true, "{r}"); let ctx = egui::Context::default(); - let mut raw = egui::RawInput::default(); - app.raw_input_hook(&ctx, &mut raw); - assert!(app.synthetic_frame, "the frame carrying the key"); - // The batch is acknowledged only after a settled UI pass took it (one step per pass). - let mut out = ctx.run_ui(raw, |_| {}); - out.textures_delta.clear(); - let mut raw = egui::RawInput::default(); - app.raw_input_hook(&ctx, &mut raw); - assert!(!app.synthetic_frame, "the frames after it are the person's"); + let (req, _reply) = ControlRequest::new("ui.key", json!({"key": "Escape"})); + tx.send(req).unwrap(); + app.run_control(&ctx); + let outside = base.join("outside/b.svg"); + let pass = |app: &mut VectorcraftApp, dropped: bool| { + let mut raw = egui::RawInput::default(); + if dropped { + raw.dropped_files.push(std::sync::Arc::new(Dropped(outside.clone()))); + } + app.begin_host_iteration(); + ctx.run_ui(raw, |ui| { + app.tick(ui.ctx()); + app.ui(ui); + }); + app.session.documents().len() + }; + assert_eq!(pass(&mut app, true), 0, "the pass carrying the key is confined"); + for _ in 0..4 { + pass(&mut app, false); + } + assert_eq!(pass(&mut app, true), 1, "the person's pass is not"); let _ = std::fs::remove_dir_all(base); } @@ -631,7 +662,11 @@ fn ui_inspect_leaves_out_paths_outside_the_read_root() { "fontsFolder": inside, "templatesFolder": outside, "recoveryFolder": outside, "scratchPrimary": "Startup", "scratchSecondary": "../private", "pluginsFolder": "", }); - app.ui.dialog = Some(crate::state::Dialog::new("preferences", json!({"fontsFolder": inside, "templatesFolder": outside}))); + crate::prefs_dialog::open(&mut app, None); + // The person types the folders: their request is not confined. + let (fill, _) = ControlRequest::new("ui.dialog.set", json!({"fields": [{"field": "fontsFolder", "value": inside}, {"field": "templatesFolder", "value": outside}]})); + let Reply::Done(filled) = crate::control::handle(&mut app, &egui::Context::default(), &fill) else { panic!("deferred") }; + assert_eq!(filled["ok"], true, "{filled}"); // The person sees every path. let ctx = egui::Context::default(); @@ -1457,74 +1492,6 @@ fn ui_inspect_shows_full_library_ids_without_a_read_root() { assert!(ui["docking_hidden"].as_object().unwrap().contains_key(&format!("library:swatches:{theirs}")), "{r}"); } -/// Hidden logic-only ticks between the injection and its UI pass must not drain another step: -/// one step per settled pass, not per hidden tick. -#[test] -fn hidden_ticks_without_a_ui_pass_do_not_drain_more_injected_steps() { - let (mut app, tx, base) = confined("gate"); - let r = request(&mut app, &tx, "ui.key", json!({"key": "A", "text": "x"})); - assert_eq!(r["ok"], true, "{r}"); - let ctx = egui::Context::default(); - let mut raw = egui::RawInput::default(); - app.raw_input_hook(&ctx, &mut raw); - assert!(!raw.events.is_empty(), "the first step is in the host's input"); - let queued = app.synthetic.len(); - for _ in 0..3 { - let mut raw = egui::RawInput::default(); - app.raw_input_hook(&ctx, &mut raw); - assert!(raw.events.is_empty(), "no new step while the previous batch is unapplied"); - } - assert_eq!(app.synthetic.len(), queued, "the hidden ticks drained nothing"); - let _ = std::fs::remove_dir_all(base); -} - -/// A UI pass that changes the document before taking an injected batch drops exactly that batch, -/// including the synthetic modifier latch it set: a later real event keeps the host's modifiers. -#[test] -fn a_stale_injected_batch_is_dropped_with_its_modifier_latch() { - let (mut app, tx, base) = confined("discard"); - let r = request(&mut app, &tx, "ui.key", json!({"key": "A", "text": "x", "cmd": true})); - assert_eq!(r["ok"], true, "{r}"); - let ctx = egui::Context::default(); - let mut raw = egui::RawInput::default(); - app.raw_input_hook(&ctx, &mut raw); - assert!(app.synthetic_modifiers, "the batch carries Cmd"); - assert!(!raw.events.is_empty()); - // The document changed after injection (a control request or a click switching documents): - // the batch no longer belongs to what the UI pass would act on. - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.raw_input_hook(&ctx, &mut raw); - assert!(raw.events.is_empty(), "the stale events are removed from the host's input"); - assert!(!app.synthetic_frame && !app.synthetic_injected, "the batch is not applied"); - assert!(!app.synthetic_modifiers, "its modifier latch is cleared too"); - assert!(app.synthetic.is_empty(), "nothing further was queued"); - let _ = std::fs::remove_dir_all(base); -} - -/// If the host's raw input no longer contains the synthetic batch exactly (another handler -/// rewrote or interleaved events), the app cannot separate stale synthetic clicks/text from the -/// person's input. It delivers nothing that pass and cancels the rest of the sequence. -#[test] -fn an_unidentifiable_stale_injected_batch_fails_closed() { - let (mut app, tx, base) = confined("discard-unknown"); - let r = request(&mut app, &tx, "ui.key", json!({"key": "A", "text": "x", "cmd": true})); - assert_eq!(r["ok"], true, "{r}"); - let ctx = egui::Context::default(); - let mut raw = egui::RawInput::default(); - app.raw_input_hook(&ctx, &mut raw); - assert!(raw.events.len() > 1, "the batch has a modifier companion and the key"); - // Rewrite one event so the exact subsequence can no longer be found. - let last = raw.events.len() - 1; - raw.events[last] = egui::Event::Text("host".into()); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - app.raw_input_hook(&ctx, &mut raw); - assert!(raw.events.is_empty(), "unidentifiable stale input is never delivered"); - assert!(!app.synthetic_frame && !app.synthetic_injected, "the stale batch is not applied"); - assert!(!app.synthetic_modifiers, "its modifier latch is cleared too"); - assert!(app.synthetic.is_empty(), "the rest of the stale synthetic sequence is cancelled"); - let _ = std::fs::remove_dir_all(base); -} - /// A plug-in's permissions are approved only by a person who asked for the install. A control /// request (or MCP, which comes through it) can't pass `grant`, can't answer the approval dialog or /// rewrite what it installs, and a frame of synthetic input can't press its OK. The person can't @@ -1566,10 +1533,6 @@ fn automation_cannot_approve_a_plugin_install() { super::plugins::show_approval(&mut app); let r = request(&mut app, &tx, "ui.dialog.confirm", json!({})); refused(&r, ASKED); - app.synthetic_frame = true; - assert!(crate::dialogs::confirm(&mut app).unwrap_err().contains(ASKED)); - assert!(vectorcraft_plugins::registry::get(id).is_none()); - app.synthetic_frame = false; assert!(crate::dialogs::confirm(&mut app).unwrap_err().contains(ASKED), "a person's OK on automation's question"); assert!(app.ui.dialog.is_some() && vectorcraft_plugins::registry::get(id).is_none() && vectorcraft_plugins::registry::granted(id).is_none()); @@ -1777,7 +1740,7 @@ fn dialog_set_allows_hidden_controls() { crate::prefs_dialog::open(&mut app, None); let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "__search", "value": "grid"})); assert_eq!(r["ok"], true, "{r}"); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("__search")), Some("grid".to_string())); + assert_eq!(r["result"]["fields"]["__search"], "grid", "{r}"); } /// Save PDF's and Print's OK save a preset while Save Preset… asks for its name: `ui.dialog.set` @@ -2075,19 +2038,20 @@ fn automation_cannot_approve_replacing_a_plugin() { type DialogHarness = egui_kittest::Harness<'static, VectorcraftApp>; -/// Runs one UI pass of `h` for each batch of synthetic input the control path queued, each taken -/// through the host's raw-input hook, until none is left and the last batch is acknowledged. -fn take_injected(h: &mut DialogHarness) { +/// [`request`] for an app the harness draws: its passes take the injected input, and the reply +/// comes once they have. +fn request_drawn(h: &mut DialogHarness, tx: &std::sync::mpsc::Sender, method: &str, params: Value) -> Value { let ctx = h.ctx.clone(); - loop { - let mut raw = egui::RawInput::default(); - h.state_mut().raw_input_hook(&ctx, &mut raw); - if raw.events.is_empty() && h.state().synthetic.is_empty() { - break; + let (req, reply) = ControlRequest::new(method, params); + tx.send(req).unwrap(); + for _ in 0..64 { + h.state_mut().run_control(&ctx); + if let Ok(r) = reply.try_recv() { + return r; } - h.input_mut().events.extend(raw.events); h.step(); } + reply.try_recv().unwrap() } /// The open install approval, with nothing installed or granted for `id`. @@ -2130,9 +2094,8 @@ fn injected_keys_and_pointer_input_cannot_approve_a_plugin_install() { for key in ["Enter", "Space"] { assert!(!h.get_by_label("OK").accesskit_node().is_focused(), "no button has the focus yet"); h.state_mut().ui.status.clear(); - let r = request(h.state_mut(), &tx, "ui.key", json!({"key": key})); + let r = request_drawn(&mut h, &tx, "ui.key", json!({"key": key})); assert_eq!(r["ok"], true, "{r}"); - take_injected(&mut h); assert!(still_waiting(&h, id), "{key}"); assert_eq!(h.state().ui.status, "", "{key} presses nothing"); } @@ -2142,25 +2105,22 @@ fn injected_keys_and_pointer_input_cannot_approve_a_plugin_install() { h.run_steps(2); assert!(h.get_by_label("OK").accesskit_node().is_focused()); h.state_mut().ui.status.clear(); - let r = request(h.state_mut(), &tx, "ui.key", json!({"key": key})); + let r = request_drawn(&mut h, &tx, "ui.key", json!({"key": key})); assert_eq!(r["ok"], true, "{r}"); - take_injected(&mut h); assert!(still_waiting(&h, id), "{key} on a focused OK"); assert!(h.state().ui.status.contains(refusal), "{key} pressed OK and was refused: {:?}", h.state().ui.status); } let at = h.get_by_label("OK").rect().center(); h.state_mut().ui.status.clear(); - let r = request(h.state_mut(), &tx, "ui.click", json!({"x": at.x, "y": at.y})); + let r = request_drawn(&mut h, &tx, "ui.click", json!({"x": at.x, "y": at.y})); assert_eq!(r["ok"], true, "{r}"); - take_injected(&mut h); assert!(still_waiting(&h, id), "ui.click"); assert!(h.state().ui.status.contains(refusal), "ui.click pressed OK and was refused: {:?}", h.state().ui.status); let events = json!([{"kind": "down", "x": at.x, "y": at.y}, {"kind": "up", "x": at.x, "y": at.y}]); - let r = request(h.state_mut(), &tx, "ui.pointer", json!({"events": events})); + let r = request_drawn(&mut h, &tx, "ui.pointer", json!({"events": events})); assert_eq!(r["ok"], true, "{r}"); - take_injected(&mut h); assert!(still_waiting(&h, id), "ui.pointer"); h.get_by_label("OK").click(); diff --git a/crates/ui-egui/src/tests/screenshots.rs b/crates/ui-egui/src/tests/screenshots.rs index b2b15af98d..6a86fd005f 100644 --- a/crates/ui-egui/src/tests/screenshots.rs +++ b/crates/ui-egui/src/tests/screenshots.rs @@ -1,372 +1,26 @@ -//! `ui.screenshot` after egui 0.37 replaced `Event::Screenshot`/`UserData` with a one-shot -//! `ScreenshotCallback`: exactly one file and reply per request, a late completion writes -//! nothing, admission is bounded before issue, a changed document or window geometry never saves -//! stale pixels, and a hidden window asks for the paint that reaches issuance. +//! `ui.screenshot`'s queue, admission, settling, staleness and deadline are `craft_automation`'s +//! `Captures`, tried in that crate's `tests/it/screenshot.rs`; what stays here is the app's PNG +//! writer and its reply limit (`control::save_screenshot`). -use std::sync::Arc; - -use egui::{Event, Pos2, Rect, ViewportCommand, ViewportId, ViewportInfo, vec2}; use serde_json::json; use vectorcraft_engine::Session; -use crate::control::ControlRequest; use crate::{Services, VectorcraftApp}; -const SCREEN: egui::Vec2 = vec2(320.0, 200.0); - -/// Build a screenshot test app with a write service, control channel and temporary directory on a -/// 100 by 100 document. -fn app(tag: &str) -> (VectorcraftApp, std::sync::mpsc::Sender, std::path::PathBuf) { +/// An app with a write service and a 100 by 100 document, and a temporary directory. +fn app(tag: &str) -> (VectorcraftApp, std::path::PathBuf) { let dir = vectorcraft_testkit::temp_dir(tag); let services = Services { write: Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string()))), ..Default::default() }; - let (tx, rx) = std::sync::mpsc::channel(); - let mut app = VectorcraftApp::new(Session::new(), services).with_control(rx); + let mut app = VectorcraftApp::new(Session::new(), services); app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - (app, tx, dir) -} - -/// Submit a `ui.screenshot` control request and return its reply receiver. -fn request(tx: &std::sync::mpsc::Sender, params: serde_json::Value) -> std::sync::mpsc::Receiver { - let (req, reply) = ControlRequest::new("ui.screenshot", params); - tx.send(req).unwrap(); - reply -} - -/// Run one tick-then-UI host frame at the requested screen size and discard texture deltas. -fn frame_at(app: &mut VectorcraftApp, ctx: &egui::Context, size: egui::Vec2, events: Vec) -> egui::FullOutput { - let raw = egui::RawInput { events, screen_rect: Some(Rect::from_min_size(Pos2::ZERO, size)), ..Default::default() }; - app.begin_host_iteration(); - let mut out = ctx.run_ui(raw, |ui| { - app.tick(ui.ctx()); - app.ui(ui); - }); - out.textures_delta.clear(); - out -} - -/// Run one host frame at the standard 320 by 200 screenshot size. -fn frame(app: &mut VectorcraftApp, ctx: &egui::Context) -> egui::FullOutput { - frame_at(app, ctx, SCREEN, vec![]) -} - -/// The callback of the screenshot command this frame issued, if any. -fn issued(out: &egui::FullOutput) -> Option { - let viewport = out.viewport_output.get(&ViewportId::ROOT)?; - viewport.commands.iter().rev().find_map(|command| match command { - ViewportCommand::Screenshot(callback) => Some(callback.clone()), - _ => None, - }) -} - -/// Make an admitted capture due now, with no deadline: the settle policy and the deadline both -/// measure wall-clock time, which a test must not race. The frame count in `issue_screenshots` -/// still proves the settle passes, and the timeout tests set the deadline in the past themselves. -fn allow_due(app: &mut VectorcraftApp) { - for queued in &mut app.queued_screenshots { - queued.due_ms = f64::MIN; - } - for pending in &mut app.pending_screenshots { - pending.deadline_ms = f64::MAX; - } -} - -/// Run full frames until the capture is issued (bounded: a failure is an error, not a hang). -fn drive_until_issued(app: &mut VectorcraftApp, ctx: &egui::Context) -> egui::ScreenshotCallback { - for _ in 0..64 { - let out = frame(app, ctx); - if let Some(callback) = issued(&out) { - return callback; - } - } - panic!("the settled frame issues the capture"); -} - -/// Two full frames install and settle the interface fonts before the first request. -fn ready(app: &mut VectorcraftApp, ctx: &egui::Context) { - frame(app, ctx); - frame(app, ctx); -} - -/// Drain an admitted request and make it due: a frame takes it from the control channel. -fn admit(app: &mut VectorcraftApp, ctx: &egui::Context) { - frame(app, ctx); - allow_due(app); -} - -/// One admitted capture completes once, writes the named file, replies with its size and releases -/// the reservation. -#[test] -fn a_request_saves_one_file_and_replies_once() { - let (mut app, tx, dir) = app("screenshot-one"); - let ctx = egui::Context::default(); - ready(&mut app, &ctx); - let path = dir.join("shot.png"); - let reply = request(&tx, json!({"path": path.to_string_lossy(), "data": true})); - assert!(reply.try_recv().is_err(), "no reply before a frame is presented"); - admit(&mut app, &ctx); - let callback = drive_until_issued(&mut app, &ctx); - assert!(!path.exists(), "the callback writes nothing itself"); - callback.complete(Arc::new(egui::ColorImage::filled([320, 200], egui::Color32::BLACK))); - app.begin_host_iteration(); - app.tick(&ctx); - let answer = reply.try_recv().expect("one reply"); - assert_eq!(answer["ok"], true, "{answer}"); - assert_eq!((answer["result"]["width"].as_u64(), answer["result"]["height"].as_u64()), (Some(320), Some(200))); - assert!(path.is_file()); - assert!(reply.try_recv().is_err(), "exactly one reply"); - assert_eq!(app.screenshot_reserved, 0, "the reservation is released"); - let _ = std::fs::remove_dir_all(dir); -} - -/// A timed-out request replies once and writes nothing; a later completion is inert. -#[test] -fn a_timed_out_request_writes_nothing_and_a_late_completion_is_inert() { - let (mut app, tx, dir) = app("screenshot-timeout"); - let ctx = egui::Context::default(); - ready(&mut app, &ctx); - let path = dir.join("late.png"); - let reply = request(&tx, json!({"path": path.to_string_lossy()})); - admit(&mut app, &ctx); - let callback = drive_until_issued(&mut app, &ctx); - // The frame never came: the deadline passes and the request answers once. - for pending in &mut app.pending_screenshots { - pending.deadline_ms = -1.0; - } - app.begin_host_iteration(); - app.tick(&ctx); - let answer = reply.try_recv().expect("the timeout reply"); - assert_eq!(answer["ok"], false, "{answer}"); - callback.complete(Arc::new(egui::ColorImage::filled([320, 200], egui::Color32::WHITE))); - app.begin_host_iteration(); - app.tick(&ctx); - assert!(!path.exists(), "a late completion writes nothing"); - assert!(reply.try_recv().is_err(), "no second reply"); - let _ = std::fs::remove_dir_all(dir); -} - -/// A completion collected after the deadline is neither encoded nor written and replies once with -/// the no-frame error. -#[test] -fn a_completion_that_arrives_after_the_deadline_is_not_saved() { - let (mut app, tx, dir) = app("screenshot-deadline"); - let ctx = egui::Context::default(); - ready(&mut app, &ctx); - let path = dir.join("too-late.png"); - let reply = request(&tx, json!({"path": path.to_string_lossy()})); - admit(&mut app, &ctx); - let callback = drive_until_issued(&mut app, &ctx); - // The callback stored the image, but the UI thread collects it after the deadline. - for pending in &mut app.pending_screenshots { - pending.deadline_ms = -1.0; - } - callback.complete(Arc::new(egui::ColorImage::filled([320, 200], egui::Color32::WHITE))); - app.begin_host_iteration(); - app.tick(&ctx); - let answer = reply.try_recv().expect("the timeout reply"); - assert_eq!(answer["ok"], false, "{answer}"); - assert!(answer["error"].as_str().unwrap_or_default().contains("no frame was presented"), "{answer}"); - assert!(!path.exists(), "an image collected after the deadline is not encoded or written"); - assert!(reply.try_recv().is_err(), "no second reply"); - let _ = std::fs::remove_dir_all(dir); -} - -/// Admission refuses a fifth request without evicting the four pending ones and releases capacity -/// when one completes. -#[test] -fn admission_rejects_more_than_four_requests_without_evicting_one_and_releases_a_finished_one() { - let (mut app, tx, dir) = app("screenshot-admission"); - let ctx = egui::Context::default(); - ready(&mut app, &ctx); - let mut replies = vec![]; - for i in 0..5 { - replies.push(request(&tx, json!({"path": dir.join(format!("{i}.png")).to_string_lossy()}))); - } - frame(&mut app, &ctx); - let last = replies.pop().unwrap().try_recv().expect("the fifth is refused at once"); - assert_eq!(last["ok"], false, "{last}"); - assert!(last["error"].as_str().unwrap_or_default().contains("already 4"), "{last}"); - for reply in &replies { - assert!(reply.try_recv().is_err(), "the four admitted requests stay pending"); - } - assert_eq!(app.pending_screenshots.len(), 4); - // Complete the first: its reservation must come back, so a new request is admitted. - allow_due(&mut app); - let callback = drive_until_issued(&mut app, &ctx); - callback.complete(Arc::new(egui::ColorImage::filled([320, 200], egui::Color32::BLACK))); - app.begin_host_iteration(); - app.tick(&ctx); - assert_eq!(replies[0].try_recv().expect("the completed reply")["ok"], true); - let more = request(&tx, json!({"path": dir.join("more.png").to_string_lossy()})); - frame(&mut app, &ctx); - assert!(more.try_recv().is_err(), "a released reservation admits the next request"); - assert_eq!(app.pending_screenshots.len(), 4); - let _ = std::fs::remove_dir_all(dir); -} - -/// Pixels with a different size are stale, produce no reply or file, and a retry with the matching -/// image completes the request. -#[test] -fn an_image_of_another_size_is_stale_and_retried() { - let (mut app, tx, dir) = app("screenshot-size"); - let ctx = egui::Context::default(); - ready(&mut app, &ctx); - let path = dir.join("retry.png"); - let reply = request(&tx, json!({"path": path.to_string_lossy()})); - admit(&mut app, &ctx); - // An image of another size means the window changed under the capture: it is not saved. - drive_until_issued(&mut app, &ctx).complete(Arc::new(egui::ColorImage::filled([300, 200], egui::Color32::BLACK))); - app.begin_host_iteration(); - app.tick(&ctx); - assert!(reply.try_recv().is_err(), "no reply for the stale image"); - assert!(!path.exists()); - // The retry issues a fresh slot after the settle frames, and the matching image completes it. - let second = drive_until_issued(&mut app, &ctx); - second.complete(Arc::new(egui::ColorImage::filled([320, 200], egui::Color32::BLACK))); - app.begin_host_iteration(); - app.tick(&ctx); - let answer = reply.try_recv().expect("the retry's reply"); - assert_eq!(answer["ok"], true, "{answer}"); - assert!(path.is_file()); - let _ = std::fs::remove_dir_all(dir); -} - -/// Changing and restoring the DPI still invalidates in-flight pixels by epoch; the retry for the -/// current geometry succeeds. -#[test] -fn a_geometry_change_and_change_back_still_rejects_the_old_pixels() { - let (mut app, tx, dir) = app("screenshot-epoch"); - let ctx = egui::Context::default(); - ready(&mut app, &ctx); - let path = dir.join("epoch.png"); - let reply = request(&tx, json!({"path": path.to_string_lossy()})); - admit(&mut app, &ctx); - let callback = drive_until_issued(&mut app, &ctx); - // DPI changes and changes back before the callback arrives: the epoch, not value equality, - // decides that the pixels are stale. - ctx.set_pixels_per_point(2.0); - frame(&mut app, &ctx); - ctx.set_pixels_per_point(1.0); - frame(&mut app, &ctx); - callback.complete(Arc::new(egui::ColorImage::filled([320, 200], egui::Color32::BLACK))); - app.begin_host_iteration(); - app.tick(&ctx); - assert!(reply.try_recv().is_err(), "no reply for pixels taken before the change back"); - assert!(!path.exists()); - // The retry issues for the current geometry and completes once. - drive_until_issued(&mut app, &ctx).complete(Arc::new(egui::ColorImage::filled([320, 200], egui::Color32::BLACK))); - app.begin_host_iteration(); - app.tick(&ctx); - let answer = reply.try_recv().expect("the retry's reply"); - assert_eq!(answer["ok"], true, "{answer}"); - assert!(path.is_file()); - let _ = std::fs::remove_dir_all(dir); -} - -/// Switching documents while a capture is in flight fails the request instead of saving new- -/// document pixels. -#[test] -fn a_document_change_while_a_capture_is_in_flight_fails_instead_of_saving_it() { - let (mut app, tx, dir) = app("screenshot-document"); - let ctx = egui::Context::default(); - ready(&mut app, &ctx); - let path = dir.join("other-document.png"); - let reply = request(&tx, json!({"path": path.to_string_lossy()})); - admit(&mut app, &ctx); - let callback = drive_until_issued(&mut app, &ctx); - // The user switches documents during the 240 ms settle/in-flight window: pixels of the new - // document must not be answered for the old request. - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - callback.complete(Arc::new(egui::ColorImage::filled([320, 200], egui::Color32::BLACK))); - app.begin_host_iteration(); - app.tick(&ctx); - let answer = reply.try_recv().expect("the identity reply"); - assert_eq!(answer["ok"], false, "{answer}"); - assert!(answer["error"].as_str().unwrap_or_default().contains("document changed"), "{answer}"); - assert!(!path.exists()); - assert!(reply.try_recv().is_err(), "no second reply"); - let _ = std::fs::remove_dir_all(dir); -} - -/// Switching documents during settle fails at issuance without ever issuing a capture or keeping a -/// reservation. -#[test] -fn a_document_change_during_the_settle_fails_at_issuance_without_issuing_a_capture() { - let (mut app, tx, dir) = app("screenshot-document-settle"); - let ctx = egui::Context::default(); - ready(&mut app, &ctx); - let path = dir.join("settled-away.png"); - let reply = request(&tx, json!({"path": path.to_string_lossy()})); - admit(&mut app, &ctx); - app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); - let mut answer = None; - for _ in 0..8 { - let out = frame(&mut app, &ctx); - assert!(issued(&out).is_none(), "a changed document is never captured"); - if let Ok(value) = reply.try_recv() { - answer = Some(value); - break; - } - } - let answer = answer.expect("the identity failure comes at issuance"); - assert_eq!(answer["ok"], false, "{answer}"); - assert!(answer["error"].as_str().unwrap_or_default().contains("document changed"), "{answer}"); - assert!(!path.exists()); - assert!(app.pending_screenshots.is_empty(), "the admitted reservation is released"); - let _ = std::fs::remove_dir_all(dir); -} - -/// A second stale-sized completion answers the request once with an error and writes nothing. -#[test] -fn a_second_stale_completion_replies_once_with_an_error_and_writes_nothing() { - let (mut app, tx, dir) = app("screenshot-stale-twice"); - let ctx = egui::Context::default(); - ready(&mut app, &ctx); - let path = dir.join("stale.png"); - let reply = request(&tx, json!({"path": path.to_string_lossy()})); - admit(&mut app, &ctx); - drive_until_issued(&mut app, &ctx).complete(Arc::new(egui::ColorImage::filled([300, 200], egui::Color32::BLACK))); - app.begin_host_iteration(); - app.tick(&ctx); - assert!(reply.try_recv().is_err(), "the first stale image is retried, not answered"); - drive_until_issued(&mut app, &ctx).complete(Arc::new(egui::ColorImage::filled([300, 200], egui::Color32::BLACK))); - app.begin_host_iteration(); - app.tick(&ctx); - let answer = reply.try_recv().expect("the second stale image fails the request"); - assert_eq!(answer["ok"], false, "{answer}"); - assert!(answer["error"].as_str().unwrap_or_default().contains("changed while the screenshot was in flight"), "{answer}"); - assert!(!path.exists()); - assert!(reply.try_recv().is_err(), "exactly one error reply"); - let _ = std::fs::remove_dir_all(dir); -} - -/// A hidden window's logic pass requests a hidden paint instead of issuing the queued capture; the -/// capture remains pending. -#[test] -fn a_hidden_window_is_asked_to_paint_the_queued_capture() { - let (mut app, tx, dir) = app("screenshot-hidden"); - let ctx = egui::Context::default(); - ready(&mut app, &ctx); - let reply = request(&tx, json!({})); - let mut raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, SCREEN)), ..Default::default() }; - raw.viewports.insert(ViewportId::ROOT, ViewportInfo { minimized: Some(true), inner_rect: None, focused: Some(false), ..Default::default() }); - app.begin_host_iteration(); - let out = ctx.run_logic(&raw, |ctx| app.tick(ctx)); - let commands = out.viewport_commands.get(&ViewportId::ROOT).cloned().unwrap_or_default(); - assert!( - commands.iter().any(|c| matches!(c, ViewportCommand::RequestPaintWhileHidden)), - "a queued capture reaches issuance only through RequestPaintWhileHidden: {commands:?}" - ); - assert_eq!(app.pending_screenshots.len(), 1); - assert!(app.pending_screenshots.iter().all(|p| p.slot.is_none()), "logic alone never issues a capture"); - assert!(reply.try_recv().is_err(), "no reply before the paint pass"); - let _ = std::fs::remove_dir_all(dir); + (app, dir) } /// An oversized claimed image is refused from the reply-encoding budget before any copy or encode. #[test] fn a_data_reply_over_the_encoding_budget_is_refused_before_encoding() { - let (mut app, _tx, _dir) = app("screenshot-encoding"); + let (mut app, _dir) = app("screenshot-encoding"); // A huge claimed image with no pixels: the guard must look at the checked size before copying // or encoding anything. (A real 100 000 × 100 000 ColorImage would already be impossible.) let image = egui::ColorImage { size: [100_000, 100_000], source_size: egui::Vec2::ZERO, pixels: vec![] }; @@ -379,7 +33,7 @@ fn a_data_reply_over_the_encoding_budget_is_refused_before_encoding() { /// same request fails. #[test] fn a_path_plus_data_capture_writes_the_file_and_omits_an_oversized_inline_png() { - let (mut app, _tx, dir) = app("screenshot-path-data"); + let (mut app, dir) = app("screenshot-path-data"); let image = egui::ColorImage::filled([2, 2], egui::Color32::RED); let path = dir.join("shot.png"); let path_text = path.to_string_lossy().into_owned();