diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 571a355846..095eab171a 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -209,6 +209,8 @@ impl VectorcraftApp { run_count: 0, channel: None, deferred_control: None, + held_set: None, + held_confirms: Vec::new(), control_rotate_press: None, pointer_waits: Vec::new(), context: 0, @@ -802,6 +804,9 @@ impl VectorcraftApp { panel_docking::close_overlays_for_modal(self, &ctx); let drawn_document = self.session.active().map(|st| (st.uid, st.revision)); dialogs::host::pump(self, &ctx); + // The pump answered the held OKs it could: the confirms waiting on them reply before the next pass's shell + // closes an accepted dialog. + self.poll_held(); // The canvas has already painted. A dialog can apply or roll back its preview // on the final input frame, with no further mouse movement to wake the window. if self.session.active().map(|st| (st.uid, st.revision)) != drawn_document { diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 2389373b4c..db564b4c34 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -80,14 +80,15 @@ impl VectorcraftApp { }; let document = self.document_identity(); let now = self.instant(); - if let Some(channel) = self.channel.as_mut() { - channel.settle_at(req, reply, document, settle, now); - } + self.settle_control(req, reply, document, settle, now); } + // A request above may have closed a dialog whose held OK a confirm waits on. + self.poll_held(); // A capture is issued only after passes settle it, and an idle window runs none; a hidden // one runs only this logic unless asked to paint. Its readback finishes only in a later frame, - // so frames keep coming until it is answered, as production's did. - if self.channel.as_ref().is_some_and(|channel| channel.captures.any_pending()) { + // so frames keep coming until it is answered, as production's did. The app answers a held OK + // only in a pass that pumps the dialogs, so frames also keep coming while a confirm waits on one. + if self.channel.as_ref().is_some_and(|channel| channel.captures.any_pending()) || !self.held_confirms.is_empty() { if self.viewport_hidden(ctx) { host.paint_while_hidden(); } @@ -118,6 +119,44 @@ impl VectorcraftApp { } } + /// Hands the reply to `req` to the control channel ([`ControlChannel::settle_at`]). The app holds the reply of a + /// confirm that waits for its answer to a dialog's held OK ([`craft::automation::Reply::AfterHeldOk`], + /// [`control::HeldConfirm`]), and [`Self::poll_held`] sends it. + pub(crate) fn settle_control( + &mut self, + mut req: craft::automation::ControlRequest, + reply: craft::automation::Reply, + document: Option, + settle: f64, + now: craft::ui::runtime::motion::Instant, + ) { + let held_set = self.held_set.take(); + let Some(channel) = self.channel.as_mut() else { return }; + if matches!(reply, craft::automation::Reply::AfterHeldOk { .. }) { + self.held_confirms.push(control::HeldConfirm::hold(&mut req, held_set)); + } + channel.settle_at(req, reply, document, settle, now); + } + + /// Answers the `ui.dialog.confirm` replies held on a dialog's OK ([`craft::automation::Reply::AfterHeldOk`]) once + /// the app accepted or refused it, or the dialog closed, each as its request's reply shows it + /// ([`control::HeldConfirm::forward`]). Called after the dialog pump of a pass, before the next pass's shell + /// closes a dialog the app accepted, and after the control requests. + pub(crate) fn poll_held(&mut self) { + if let Some(dialogs) = self.dialogs() + && let Some(channel) = self.channel.as_mut() + { + dialogs.with(|host| channel.poll_held(host)); + } + if self.held_confirms.is_empty() { + return; + } + let hiding = control::deferred_hiding(self); + let roots = self.automation_roots.clone(); + let held = &mut self.held_confirms; + file_access::confine(roots.as_ref(), || held.retain(|confirm| confirm.forward(&hiding))); + } + /// Answers the `ui.pointer` replies held on the tool's edit ([`control::PointerWait`]). The canvas /// checks on the tool each pass it is drawn; this checks too, for passes without it. fn answer_pointer_waits(&mut self, ctx: &egui::Context) { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index bfe9f1991c..5e46bdeeda 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -18,8 +18,11 @@ //! - `ui.find`: the controls of the window's access tree that match a name or role //! - `ui.set {brightness?, panel?, dockTab?, rulers?, outline?, …}` //! - `ui.dialog.set` / `ui.dialog.confirm` / `ui.dialog.cancel`: answered by -//! `craft::automation::dialogs::dialog_method` for the dialog asked for (`dialog`, default `"top"`), and by -//! `dialogs::simplify_slider::dialog_method` for the Simplify and Smooth sliders +//! `craft::automation::dialogs::dialog_reply` for the dialog asked for (`dialog`, default `"top"`), and by +//! `dialogs::simplify_slider::dialog_method` for the Simplify and Smooth sliders. A set with an `action` replies +//! `{dialog, result}`: the dialog as the set left it, and the reply to its confirm or cancel. A confirm, or a set with +//! `action: "confirm"`, of a dialog that holds its OK replies once the app accepts it, or with the app's +//! refusal as its error //! - `ui.resize {width, height}`, `ui.focus`, `ui.screenshot {path?, focus?}` (without a path the //! PNG comes back in the reply) //! - `ui.render {path?, scale?, artboard?, data?, traceViews?}`: render an artboard headlessly @@ -129,6 +132,25 @@ fn wrap(r: Result) -> Reply { Reply::from_result(r) } +/// The hosted dialog that `params` names (`dialog`, `"top"` for the top one) as `ui.inspect` lists it, +/// `{id, parent, key, fields}`, or null when none is open. +fn set_dialog(host: &craft::ui::dialog::DialogHost, params: &Value) -> Value { + let open = craft::automation::dialogs::inspect(host); + let list = open.as_array().map_or(&[][..], Vec::as_slice); + let set = if params["dialog"] == "top" { list.last() } else { list.iter().find(|d| d["id"] == params["dialog"]) }; + set.cloned().unwrap_or(Value::Null) +} + +/// The reply to a `ui.dialog.set` with an `action`, from `reply`, the reply to its confirm or cancel: on success +/// `{dialog, result}`, with `dialog` as the set left it and `result` the answer's result, and otherwise `reply`. +pub(crate) fn answered_set(dialog: Value, reply: Value) -> Value { + if reply["ok"] != true { + return reply; + } + let result = reply.get("result").cloned().unwrap_or(Value::Null); + json!({"ok": true, "result": {"dialog": dialog, "result": result}}) +} + pub fn all_commands(app: &VectorcraftApp) -> Value { let mut v: Vec = app.session.commands().into_iter().map(|c| serde_json::to_value(c).unwrap_or_default()).collect(); for (id, label, sc, params) in crate::menus::UI_COMMANDS { @@ -1175,9 +1197,10 @@ const DOCKING_ACTION: &str = "action"; /// succeeded or failed ([`sent_paths`]), except where a `path` or `files` entry of its result names the /// file the request wrote inside the write roots, as the request gave it. A reply with no `/`, `\` or `%` in it is not searched, since every hidden path /// holds a separator, written or escaped. A screenshot's reply is hidden when it is sent -/// ([`Hiding::hide_error`]); a `ui.pointer` reply sent after the tool's edit holds no library id +/// ([`Hiding::hide_error`]), and so is a confirm's reply held on a dialog's OK ([`HeldConfirm::forward`]); a `ui.pointer` reply sent after the tool's edit holds no library id /// or path. pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) -> Reply { + app.held_set = None; let method = req.method.as_str(); if vectorcraft_engine::file_access::current().is_none() { return dispatch(app, ctx, method, &req.params); @@ -1201,6 +1224,50 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques Reply::Done(reply) } +/// A `ui.dialog.confirm`, or a `ui.dialog.set` with `action: "confirm"`, whose reply waits for the app's answer to +/// the dialog's held OK ([`Reply::AfterHeldOk`]). The control channel sends that answer to `answer`, and +/// [`Self::forward`] sends it on as the request's reply. +pub(crate) struct HeldConfirm { + /// Where the control channel sends the answer. + answer: std::sync::mpsc::Receiver, + /// Where the request's reply goes. + reply: std::sync::mpsc::Sender, + /// The request's params: the reply hides the paths outside the read root that they hold. + params: Value, + /// The dialog that a set with an `action` set, which the reply shows as `dialog`. + dialog: Option, +} + +impl HeldConfirm { + /// Holds the reply of `req`: the control channel answers the returned confirm in its place. `dialog` is the + /// dialog `req` set, for a set with an `action`. + pub(crate) fn hold(req: &mut ControlRequest, dialog: Option) -> Self { + let (to_confirm, answer) = std::sync::mpsc::channel(); + let reply = std::mem::replace(&mut req.reply, to_confirm); + Self { answer, reply, params: req.params.clone(), dialog } + } + + /// Sends the control channel's answer on as the request's reply: inside `{dialog, result}` for a set with an + /// `action`, and under a read root with what `hiding` hides, as [`handle`] hides a reply it sends at once. True + /// while the answer has not come. + pub(crate) fn forward(&self, hiding: &Hiding) -> bool { + let answer = match self.answer.try_recv() { + Ok(answer) => answer, + Err(std::sync::mpsc::TryRecvError::Empty) => return true, + Err(std::sync::mpsc::TryRecvError::Disconnected) => return false, + }; + let mut reply = match &self.dialog { + Some(dialog) => answered_set(dialog.clone(), answer), + None => answer, + }; + if vectorcraft_engine::file_access::current().is_some() { + hiding.hide(&mut reply, &self.params); + } + let _ = self.reply.send(reply); + false + } +} + /// Hides in `reply` the libraries hidden now and in `before`, and the paths outside the read root that /// `sent`, the request's params, holds ([`handle`]), and the recovery folders outside the read root /// that are in use or that a failure message named, with each folder on the way to one that the reply @@ -1473,6 +1540,7 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val Some(_) => return err("`action` must be confirm or cancel"), }; let pdf = app.save_pdf.as_ref().map(|open| open.id).filter(|_| method == "ui.dialog.set"); + let mut held_set = None; let reply = dialogs.with(|host| { // The answer goes to the dialog the fields went to, even when setting them opens another over it. if answer.is_some() @@ -1491,34 +1559,39 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val // A Save PDF settings object keeps the options it leaves out. match pdf.and_then(|id| crate::dialogs::save_pdf::set_settings_objects(host, ctx, id, ¶ms)) { Some(set) => Some(set.map(|()| Value::Null)), + // A confirm that files a dialog's held OK replies once the app accepts or refuses it. + None if method != "ui.dialog.set" => return craft::automation::dialogs::dialog_reply(host, ctx, method, ¶ms), None => craft::automation::dialogs::dialog_method(host, ctx, method, ¶ms), } } else { Some(Ok(Value::Null)) }; match (set, answer) { + // A set with an `action` replies `{dialog, result}`: the dialog as the set left it, and the answer's + // result. A confirm that files the dialog's held OK replies once the app answers it. (Some(Ok(_)), Some(answer)) => { + let dialog = set_dialog(host, ¶ms); if answer == "ui.dialog.confirm" && let Ok(id) = craft::automation::dialogs::dialog_id(host, ¶ms) { crate::dialogs::print::prepare_confirm(app, host, id); } - craft::automation::dialogs::dialog_method(host, ctx, answer, &json!({ "dialog": params["dialog"] })) + match craft::automation::dialogs::dialog_reply(host, ctx, answer, &json!({ "dialog": params["dialog"] })) { + Some(Reply::Done(reply)) => Some(Reply::Done(answered_set(dialog, reply))), + Some(held) => { + held_set = Some(dialog); + Some(held) + } + None => None, + } } // A set answers with the dialog it set, `{id, parent, key, fields}`, as production did. - (Some(Ok(_)), None) if method == "ui.dialog.set" => { - let open = craft::automation::dialogs::inspect(host); - let list = open.as_array().map_or(&[][..], Vec::as_slice); - let set = if params["dialog"] == "top" { list.last() } else { list.iter().find(|d| d["id"] == params["dialog"]) }; - Some(Ok(set.cloned().unwrap_or(Value::Null))) - } - (set, _) => set, + (Some(Ok(_)), None) if method == "ui.dialog.set" => Some(ok(set_dialog(host, ¶ms))), + (set, _) => set.map(wrap), } }); - match reply { - Some(r) => wrap(r), - None => err(format!("unknown method `{method}`")), - } + app.held_set = held_set; + reply.unwrap_or_else(|| err(format!("unknown method `{method}`"))) } "ui.resize" => { let (w, h) = match coord(p, "width", 1440.0).and_then(|w| Ok((w, coord(p, "height", 900.0)?))) { @@ -1678,14 +1751,21 @@ fn preferences_method(app: &mut VectorcraftApp, method: &str, p: &Value) -> Resu for (field, value) in fields { crate::prefs_dialog::set_field(app, &field, value)?; } - match action { - Some("confirm") => crate::prefs_dialog::confirm(app), + // A set with an `action` replies `{dialog, result}`: the window as the set left it, as `ui.inspect` shows it, and + // the answer's result. + let dialog = (method == "ui.dialog.set" && action.is_some()).then(|| json!({"kind": "preferences", "fields": crate::prefs_dialog::fields(app)})); + let result = match action { + Some("confirm") => crate::prefs_dialog::confirm(app)?, Some(_) => { crate::prefs_dialog::cancel(app); - Ok(Value::Null) + Value::Null } - None => Ok(Value::Null), - } + None => Value::Null, + }; + Ok(match dialog { + Some(dialog) => json!({"dialog": dialog, "result": result}), + None => result, + }) } /// `app.save` (`method`) or `app.export` with params `p`. diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index d267ab460e..96824a2057 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -648,16 +648,112 @@ fn dialog_set_with_an_action_answers_the_same_dialog() { } let r = request(&mut app, json!({"fields": [{"field": "text", "value": "b"}], "action": "confirm"})); assert_eq!(r["ok"], true, "{r}"); + // The reply is `{dialog, result}`: the dialog as the set left it, and the reply to confirm. + assert_eq!(r["result"]["dialog"]["id"], id.value().to_string(), "{r}"); + assert_eq!(r["result"]["dialog"]["fields"]["text"], "b", "{r}"); + assert_eq!(r["result"].get("result"), Some(&Value::Null), "{r}"); let Some(DialogResult::Ok(answer)) = taken(&app, id) else { panic!("confirmed in the same request") }; assert_eq!(answer.fields.text("text"), Some("b"), "the answer holds the field set with it"); let id = open(&mut app); let r = request(&mut app, json!({"fields": [{"field": "text", "value": "c"}], "action": "cancel"})); assert_eq!(r["ok"], true, "{r}"); + assert_eq!(r["result"]["dialog"]["fields"]["text"], "c", "{r}"); + assert_eq!(r["result"].get("result"), Some(&Value::Null), "{r}"); assert!(matches!(taken(&app, id), Some(DialogResult::Cancel)), "canceled in the same request"); let r = request(&mut app, json!({"fields": [], "action": "confirm"})); assert_eq!(r["ok"], false, "no dialog open: {r}"); } +/// A confirm of a dialog that holds its OK replies with the app's answer, through both ways of confirming: +/// `ui.dialog.confirm` gets the refusal of a color adjustment confirmed in another document than the one it +/// opened in, and `ui.dialog.set {action: "confirm"}` in its own document gets the acceptance. While the +/// window is hidden, the request asks for the pass that pumps the dialogs, and the reply waits for it. +#[test] +fn a_held_confirm_replies_with_the_apps_answer() { + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default()).with_control(rx)); + let ctx = app.ui_ctx.clone().unwrap(); + let mut ids = Vec::new(); + for _ in 0..2 { + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + ids.push(app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + app.run("paint.setFill", json!({"color": "#808080"})).unwrap(); + } + let fill = |app: &VectorcraftApp, id: u64| { + let node = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + node.appearance.fill_paint().color().unwrap().to_hex() + }; + app.run("document.activate", json!({"index": 0})).unwrap(); + crate::dialogs::color_balance::open(&mut app); + app.dialogs() + .unwrap() + .with(|h| h.set_json_field(&ctx, craft::ui::dialog::dialog_id(crate::dialogs::color_balance::KIND), "r", json!(20))) + .unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + + let (req, reply) = ControlRequest::new("ui.dialog.confirm", json!({})); + tx.send(req).unwrap(); + crate::testing::app_frame(&mut app, &ctx, egui::RawInput::default()); + let refused = json!({"ok": false, "error": "This adjustment can only apply to the document where it was opened."}); + assert_eq!(reply.try_recv().ok(), Some(refused), "the confirm replies with the app's refusal"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "the other document is not adjusted"); + assert_eq!(fill(&app, ids[1]), "#808080"); + + app.run("document.activate", json!({"index": 0})).unwrap(); + let hidden = || { + let mut raw = egui::RawInput::default(); + raw.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo { minimized: Some(true), ..Default::default() }); + raw + }; + let (req, reply) = ControlRequest::new("ui.dialog.set", json!({"fields": [], "action": "confirm"})); + tx.send(req).unwrap(); + // A hidden window runs only the app's logic until it is asked to paint. + let out = crate::testing::part_frame(&mut app, &ctx, hidden(), |app, ui| app.tick(ui.ctx())); + assert!(reply.try_recv().is_err(), "the reply waits for the app's answer"); + let commands = out.viewport_output.get(&egui::ViewportId::ROOT).map_or(&[][..], |v| v.commands.as_slice()); + assert!(commands.contains(&egui::ViewportCommand::RequestPaintWhileHidden), "the held OK asks for a pass: {commands:?}"); + crate::testing::app_frame(&mut app, &ctx, hidden()); + let r = reply.try_recv().expect("the confirm replies once the app accepts it"); + assert_eq!(r["ok"], true, "{r}"); + // A set with an `action` replies `{dialog, result}` once the app has answered too. + assert_eq!(r["result"]["dialog"]["key"], crate::dialogs::color_balance::KIND, "{r}"); + assert_eq!(r["result"]["dialog"]["fields"]["r"].as_f64(), Some(20.0), "{r}"); + assert_eq!(r["result"].get("result"), Some(&Value::Null), "{r}"); + assert_eq!(fill(&app, ids[0]), "#b38080", "the adjustment applies in its own document"); + assert!(app.held_confirms.is_empty(), "no confirm waits"); +} + +/// A held confirm whose dialog closes before the app answers its OK replies with an error, and a second confirm +/// sent while the first waits is refused without answering the first. +#[test] +fn a_held_confirm_answers_when_its_dialog_closes_first() { + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default()).with_control(rx)); + let ctx = app.ui_ctx.clone().unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); + crate::dialogs::color_balance::open(&mut app); + // A pass that runs only the app's logic answers the control requests, but not the held OK. + let logic = |app: &mut VectorcraftApp, method: &str| { + let (req, reply) = ControlRequest::new(method, json!({})); + tx.send(req).unwrap(); + crate::testing::part_frame(app, &ctx, egui::RawInput::default(), |app, ui| app.tick(ui.ctx())); + reply + }; + let first = logic(&mut app, "ui.dialog.confirm"); + assert!(first.try_recv().is_err(), "the reply waits for the app's answer"); + let second = logic(&mut app, "ui.dialog.confirm"); + let r = second.try_recv().expect("a second confirm replies at once"); + assert_eq!(r["ok"], false, "a second confirm while the first waits is refused: {r}"); + assert!(first.try_recv().is_err(), "the first confirm still waits"); + let cancel = logic(&mut app, "ui.dialog.cancel"); + assert_eq!(cancel.try_recv().ok().map(|r| r["ok"].clone()), Some(json!(true))); + let closed = json!({"ok": false, "error": "the dialog closed while its OK waited for the app's answer"}); + assert_eq!(first.try_recv().ok(), Some(closed), "the first confirm replies that the dialog closed"); + assert!(app.held_confirms.is_empty(), "no confirm waits"); +} + /// #1004: `ui.render` (the MCP `screenshot` of a connected app) renders the artboard asked /// for, at the scale asked for; the first without one. #[test] diff --git a/crates/ui-egui/src/dialogs/hyphenation.rs b/crates/ui-egui/src/dialogs/hyphenation.rs index 4e9fae0914..e660977d02 100644 --- a/crates/ui-egui/src/dialogs/hyphenation.rs +++ b/crates/ui-egui/src/dialogs/hyphenation.rs @@ -245,11 +245,11 @@ mod tests { } assert_eq!(paras(&app, id), original, "{lang}: only the draft changes while open"); if answer == "ui.dialog.confirm" { - let (request, _) = ControlRequest::new(answer, json!({})); - match crate::control::handle(&mut app, &ctx, &request) { - Reply::Done(reply) => assert_eq!(reply["ok"], true, "{reply}"), - _ => panic!("confirmation should reply immediately"), - } + let (request, sent) = ControlRequest::new(answer, json!({})); + let reply = crate::control::handle(&mut app, &ctx, &request); + assert!(matches!(reply, Reply::AfterHeldOk { .. }), "the confirm waits for the app's answer to the held OK"); + let reply = crate::testing::settled_reply(&mut app, &ctx, request, &sent, reply); + assert_eq!(reply["ok"], true, "{reply}"); } else { click(&mut app, &mut frame, footer.center()); } diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index c7a85c3e0c..51c59b32b9 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -846,15 +846,23 @@ pub(crate) fn dialog_method(app: &mut VectorcraftApp, method: &str, params: &Val return Some(Err(e)); } } - Some(match answer { - Some(true) => confirm(app), - Some(false) => cancel(app).map(|()| Value::Null), - // A set answers with the dialog it set, `{id, parent, key, fields}`, as the other dialogs' sets do. - None => Ok(with_host(app, |host, _| { + // A set answers with the dialog it set, `{id, parent, key, fields}`, as the other dialogs' sets do. + let set = (method == "ui.dialog.set").then(|| { + with_host(app, |host, _| { let id = dialog_id(KIND).value().to_string(); craft::automation::dialogs::inspect(host).as_array().and_then(|open| open.iter().find(|d| d["id"] == id.as_str()).cloned()) }) .flatten() - .unwrap_or(Value::Null)), + .unwrap_or(Value::Null) + }); + let result = match answer { + Some(true) => confirm(app), + Some(false) => cancel(app).map(|()| Value::Null), + None => return Some(Ok(set.unwrap_or(Value::Null))), + }; + // A set with an `action` replies `{dialog, result}`: the dialog as the set left it, and the answer's result. + Some(match (set, result) { + (Some(dialog), Ok(result)) => Ok(json!({ "dialog": dialog, "result": result })), + (_, result) => result, }) } diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 35675bda64..4684955ec9 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -90,10 +90,11 @@ pub(super) fn confirm(app: &mut VectorcraftApp) { } /// One control request, answered as the control channel answers it: at once, or, for synthetic input (`ui.text`, -/// `ui.key`), once the frames after it have processed the input. +/// `ui.key`), once the frames after it have processed the input, or, for a confirm of Print's held OK, once the app +/// answered it. pub(super) fn call_raw(app: &mut VectorcraftApp, method: &str, params: Value) -> Value { let ctx = ctx(app); - let (req, _reply) = craft::automation::ControlRequest::new(method, params); + let (req, answer) = craft::automation::ControlRequest::new(method, params); let reply = match crate::control::handle(app, &ctx, &req) { craft::automation::Reply::Done(reply) => reply, craft::automation::Reply::AfterInput => { @@ -102,7 +103,8 @@ pub(super) fn call_raw(app: &mut VectorcraftApp, method: &str, params: Value) -> } json!({"ok": true, "result": null}) } - _ => panic!("{method} is answered at once or after its input"), + held @ craft::automation::Reply::AfterHeldOk { .. } => crate::testing::settled_reply(app, &ctx, req, &answer, held), + _ => panic!("{method} is answered at once, after its input or after the app's answer"), }; pump(app); reply diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 60e133e9f3..c066f803e1 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -179,6 +179,11 @@ pub struct VectorcraftApp { pub(crate) channel: Option, /// A `ui.pointer` or `ui.tool.select` held until the synthetic input sent before it reached the tool. deferred_control: Option, + /// The dialog that the request [`control::handle`] answered last set with `action: "confirm"`, when that confirm + /// filed the dialog's held OK: its reply shows it as `dialog` ([`control::HeldConfirm`]). + pub(crate) held_set: Option, + /// The confirms whose replies wait for the app's answer to a dialog's held OK. + pub(crate) held_confirms: Vec, /// Where a control-channel Rotate View drag began, kept between its requests. pub(crate) control_rotate_press: Option, /// The `ui.pointer` replies that wait for the edit their gesture started on another thread. diff --git a/crates/ui-egui/src/testing.rs b/crates/ui-egui/src/testing.rs index 89a74801bc..59667e5f7a 100644 --- a/crates/ui-egui/src/testing.rs +++ b/crates/ui-egui/src/testing.rs @@ -113,6 +113,30 @@ pub(crate) fn run_fired(app: &mut crate::VectorcraftApp, ctx: &egui::Context) { let _ = app.frame_input(take_output(ctx)); } +/// The reply to `req`, which [`crate::control::handle`] answered with `reply` just before, as the app sends it on +/// `answer` ([`crate::VectorcraftApp::settle_control`]): at once, or for a confirm that filed a dialog's held OK, after +/// the frame whose dialog pump accepted or refused that OK. For that frame the app answers a control channel that +/// holds the reply. +pub(crate) fn settled_reply( + app: &mut crate::VectorcraftApp, + ctx: &egui::Context, + req: craft::automation::ControlRequest, + answer: &std::sync::mpsc::Receiver, + reply: craft::automation::Reply, +) -> serde_json::Value { + let (_requests, rx) = std::sync::mpsc::channel(); + let previous = app.channel.replace(craft::automation::ControlChannel::new(rx)); + let now = app.instant(); + app.settle_control(req, reply, None, 0.0, now); + let sent = answer.try_recv().or_else(|_| { + app_frame(app, ctx, egui::RawInput::default()); + answer.try_recv() + }); + app.channel = previous; + app.held_confirms.clear(); + sent.unwrap_or_else(|_| serde_json::json!({"ok": false, "error": "no reply after the frame that pumps the dialogs"})) +} + /// Held by a test that changes the custom dictionary, which the whole process shares, or that needs it to hold still: /// every change moves the dictionary's generation, and a Check Spelling walk that sees it move checks its scope again /// from the start. diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index ac619939fe..65605a9e1f 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -161,6 +161,26 @@ fn control_saves_leave_out_the_documents_file_outside_the_read_root() { let _ = std::fs::remove_dir_all(base); } +/// A confirm's reply held on a dialog's OK, sent once the app answers it, shows a path outside the read root that the +/// request sent by its file name only, as a reply sent at once does. +#[test] +fn a_held_confirm_hides_the_paths_outside_the_read_root() { + let (mut app, _tx, base) = confined("held-confirm"); + let outside = s(base.join("outside/b.svg")); + let params = json!({"fields": [{"field": "file", "value": outside}], "action": "confirm"}); + let (mut req, reply) = ControlRequest::new("ui.dialog.set", params); + app.held_confirms.push(crate::control::HeldConfirm::hold(&mut req, None)); + // The control channel answers the held confirm with the app's refusal. + req.reply.send(json!({"ok": false, "error": format!("cannot read {outside}")})).unwrap(); + app.poll_held(); + let r = reply.try_recv().expect("the reply is sent once the answer has come"); + assert_eq!(r["ok"], false, "{r}"); + assert!(!r.to_string().contains(&s(base.join("outside"))), "{r}"); + assert!(r["error"].as_str().is_some_and(|e| e.contains("b.svg")), "{r}"); + assert!(app.held_confirms.is_empty(), "no confirm waits"); + let _ = std::fs::remove_dir_all(base); +} + /// In one session with a library loaded from outside the read root: the library keeps its file-name /// id, a reply that names its path shows the file name, a save without a path leaves out the /// document's file, and a save or export to a path the client gave in the write root keeps that path @@ -1782,6 +1802,13 @@ fn dialog_set_allows_hidden_controls() { let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "__search", "value": "grid"})); assert_eq!(r["ok"], true, "{r}"); assert_eq!(crate::prefs_dialog::fields(&app).unwrap()["__search"], "grid"); + // With an `action`, Preferences replies `{dialog, result}` as the hosted dialogs do. + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "__search", "value": "rulers", "action": "cancel"})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(r["result"]["dialog"]["kind"], "preferences", "{r}"); + assert_eq!(r["result"]["dialog"]["fields"]["__search"], "rulers", "{r}"); + assert_eq!(r["result"].get("result"), Some(&Value::Null), "{r}"); + assert!(!crate::prefs_dialog::is_open(&app), "canceled in the same request"); } /// Save PDF's and Print's OK export and print: `ui.dialog.set` can't add a preset name to turn OK diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 403e20faea..0f819ee981 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -734,6 +734,9 @@ fn ui_dialog_set_with_an_action_gives_the_event() { let fields = json!({"fields": [{"field": "event", "value": "change"}, {"field": "control", "value": "name"}, {"field": "value", "value": "Ann"}], "action": "confirm"}); let r = run(&mut app, "ui.dialog.set", fields); assert_eq!(r["ok"], true, "{r}"); + // A set with an `action` replies `{dialog, result}`: the dialog as the set left it, and the answer's result. + assert!(r["result"]["dialog"]["fields"].is_object(), "{r}"); + assert!(r["result"].get("result").is_some(), "{r}"); assert!(until_window(&mut app)); let r = run(&mut app, "ui.dialog.set", json!({"field": "title", "value": "x"})); assert_eq!(r["ok"], false, "the title is read only: {r}"); diff --git a/crates/ui-egui/src/tests/synthetic.rs b/crates/ui-egui/src/tests/synthetic.rs index 5b516374d8..e5fdfffa3f 100644 --- a/crates/ui-egui/src/tests/synthetic.rs +++ b/crates/ui-egui/src/tests/synthetic.rs @@ -8,11 +8,15 @@ use vectorcraft_engine::Session; use crate::VectorcraftApp; -/// Send one control request (it must succeed). +/// Send one control request (it must succeed). A confirm that files a dialog's held OK is answered in the frames the +/// test runs after it, which check what the OK did. pub(crate) fn control(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, params: Value) { let (req, _rx) = ControlRequest::new(method, params); - let Reply::Done(r) = crate::control::handle(app, ctx, &req) else { panic!("not done") }; - assert_eq!(r["ok"], true, "{r}"); + match crate::control::handle(app, ctx, &req) { + Reply::Done(r) => assert_eq!(r["ok"], true, "{r}"), + Reply::AfterHeldOk { .. } => {} + _ => panic!("not done"), + } } /// One whole app frame (`tick` and `ui`, as production runs them) in an 800 × 600 window with diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 21c81bda1e..870dcfcb82 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -102,7 +102,7 @@ the two can still win that race. | `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above | | `ui.wheel` | `{x, y, dy?, dx?, unit?: "line"\|"point", shift?, alt?, cmd?}` | a mouse wheel turn over screen point (x, y): `dy` notches up (+) or down, `dx` sideways. Over the canvas the wheel scrolls, Cmd-wheel (Ctrl on Windows and Linux) scrolls sideways and Alt-wheel (Option on the Mac) zooms about the pointer (with the `ctrlWheelScrollsSideways` preference off, Cmd-wheel zooms too); with the `zoomWithMouseWheel` preference the wheel and Alt-wheel zoom about the pointer, Shift-wheel scrolls up and down and Cmd-wheel (Ctrl on Windows and Linux) sideways. Over a focused numeric field (click it first) each notch steps its value as Up/Down do (Shift: ten, Cmd/Ctrl: a tenth) and the panel stays put; over anything else in a panel the wheel scrolls it. Over the canvas, the wheel preferences in `docs/mcp.md` change what these keys do | | `ui.set` | `{brightness?, panel?, rulers?, outline?, grid?, smartGuides?, boundingBox?, controlBar?, imageTracePreview?}` | `outline`: View › Outline for the active document only (each document has its own, a document opens in Preview, and `ui.inspect` shows it as `view.outline`; an error without a document). `imageTracePreview`: the Image Trace panel's Preview (`ui.inspect` shows it as `ui.image_trace_preview`) | -| `ui.dialog.set` / `.confirm` / `.cancel` | `{field, value, action?}` or `{fields: [{field, value}…], action?}` | fill and submit the open dialog. `ui.dialog.set` takes the fields the dialog has (`ui.inspect`) other than its `__` fields, the `__` fields that are controls of the dialog (such as `__section`, `__allArtboards` and `__bleedLinked` in Save PDF, `__constrain` in Transform Each and the shape dialogs, and `__search` and `__category` in Preferences; Save PDF's and Print's `__savePresetAs`, the preset name, only while Save Preset… asks for it, since OK then saves a preset), `discard` on a dialog with a discard button, `preview` on one with a live preview, the fields that the dialog reads but adds only when a control changes (such as `searchFolder`, or `copy` in the Transform dialogs), and the fields it passes to the command it runs: every parameter of the `command` dialog's command (`ui.paramDialog`), and the `textureImage` that Load Texture… sets in the Glass, Texturizer and Rough Pastels effects; any other field is an error that lists the dialog's fields, and the dialog stays as it was. Any other `__` field, held or not, holds what the dialog's OK acts on (such as the `__command` and `__params` of a `confirm` or `command` dialog) or the dialog's own state: setting it is the error "the `` dialog cannot set protected field ``", and the dialog stays as it was. `fields` sets the list (at most 256 items) in order (a missing `value` is `null`) and checks every item first: when one is refused, the call is an error and no field changes. `action: "confirm"` or `"cancel"` on `ui.dialog.set` then confirms or cancels the same dialog in the same request, as `ui.dialog.confirm` and `ui.dialog.cancel` do, and the reply is `{dialog, result}`: the dialog after the fields were set and the reply to confirm (`null` for cancel); any other `action` is an error and no field changes | +| `ui.dialog.set` / `.confirm` / `.cancel` | `{field, value, action?}` or `{fields: [{field, value}…], action?}` | fill and submit the open dialog. `ui.dialog.set` takes the fields the dialog has (`ui.inspect`) other than its `__` fields, the `__` fields that are controls of the dialog (such as `__section`, `__allArtboards` and `__bleedLinked` in Save PDF, `__constrain` in Transform Each and the shape dialogs, and `__search` and `__category` in Preferences; Save PDF's and Print's `__savePresetAs`, the preset name, only while Save Preset… asks for it, since OK then saves a preset), `discard` on a dialog with a discard button, `preview` on one with a live preview, the fields that the dialog reads but adds only when a control changes (such as `searchFolder`, or `copy` in the Transform dialogs), and the fields it passes to the command it runs: every parameter of the `command` dialog's command (`ui.paramDialog`), and the `textureImage` that Load Texture… sets in the Glass, Texturizer and Rough Pastels effects; any other field is an error that lists the dialog's fields, and the dialog stays as it was. Any other `__` field, held or not, holds what the dialog's OK acts on (such as the `__command` and `__params` of a `confirm` or `command` dialog) or the dialog's own state: setting it is the error "the `` dialog cannot set protected field ``", and the dialog stays as it was. `fields` sets the list (at most 256 items) in order (a missing `value` is `null`) and checks every item first: when one is refused, the call is an error and no field changes. `action: "confirm"` or `"cancel"` on `ui.dialog.set` then confirms or cancels the same dialog in the same request, as `ui.dialog.confirm` and `ui.dialog.cancel` do, and the reply is `{dialog, result}`: the dialog after the fields were set and the reply to confirm (`null` for cancel); any other `action` is an error and no field changes. When the dialog waits for the app to accept or refuse its OK (a color adjustment refuses OK while another document is the active one), `ui.dialog.confirm` and `action: "confirm"` reply once the app has answered: `null` (`result: null` for `action`) when it accepts the OK, and the app's refusal as the error when it refuses it, with the dialog left open. A confirm whose dialog closes first is the error "the dialog closed while its OK waited for the app's answer" | | `ui.screenshot` | `{path?, data?}` | capture the window (PNG), written to `path`; `data: true` sends it back as `pngBase64` too. The inline PNG is capped at 64 MiB: with a `path` the file is still written and `pngBase64` is omitted when the image is larger, while a path-less `data: true` request fails if either the raw RGBA image or the encoded PNG exceeds the cap. Needs a presented frame: with the screen locked or the window minimized/covered it fails after ~8 s with an explanatory error | | `ui.render` | `{path?, scale?, artboard?, data?, traceViews?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first; `traceViews: true`: Image Trace objects draw in their View, as on the canvas, instead of their tracing result): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | | `ui.resize` | `{width?, height?}` | request the window's inner size; omitted or null `width` and `height` default to 1440 and 900. Returns `null` |