Dialogs: a control confirm of a held OK replies with the app's answer

A dialog that holds its OK files the answer for the app, which accepts or
refuses it in the next dialog pump. `ui.dialog.confirm` and `ui.dialog.set`
with `action: "confirm"` replied `{"ok": true}` as soon as the answer was
filed, so a client could not tell that the app refused it (a color
adjustment confirmed while another document is active) and the dialog
stayed open.

`ui.dialog.set` with an `action` also replied with the reply to the
confirm or cancel alone. The MCP `answer_dialog` tool reads a reply
without a `dialog` key as an app that did not answer the dialog, and
sends another `ui.dialog.confirm` or `ui.dialog.cancel`: after an
accepted OK that call failed with "no hosted dialog is open" or answered
the dialog under it.

- Both confirm paths answer with `dialog_reply`, and the app holds the
  reply of a confirm that waits on the dialog's held OK until the app
  answers that opening of the dialog.
- A set with an `action` replies `{dialog, result}`: the dialog as the
  set left it, and the reply to its confirm or cancel, also once a held
  OK is answered. This covers the hosted dialogs, Preferences and
  ScriptUI dialogs; the Simplify and Smooth sliders already replied this
  way.
- A held reply shows the paths outside the read root that the request
  sent by their file names, as a reply sent at once shows them.
- The app polls the held replies right after the dialog pump, before the
  next pass closes an accepted dialog, and after the control requests.
- While a confirm waits on a held OK, the control logic asks for a pass
  (a paint while the window is hidden), so a minimized window answers
  too. A dialog whose OK waits with no confirm on it, such as Print
  during its printer lookup, does not keep the window drawing.
- docs/control-protocol.md describes the held reply and its errors.
This commit is contained in:
dotCooCoo committed 2026-12-03 02:05:33 -08:00
1 parent 4002b2b66c
commit fe3305b9dc
13 files changed
+336 -43

No files matched your search

+5
View File
@@ -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 {
+44 -5
View File
@@ -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<DocumentId>,
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) {
+100 -20
View File
@@ -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<Value, String>) -> 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<Value> = 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<Value>,
/// Where the request's reply goes.
reply: std::sync::mpsc::Sender<Value>,
/// 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<Value>,
}
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<Value>) -> 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, &params)) {
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, &params),
None => craft::automation::dialogs::dialog_method(host, ctx, method, &params),
}
} 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, &params);
if answer == "ui.dialog.confirm"
&& let Ok(id) = craft::automation::dialogs::dialog_id(host, &params)
{
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, &params))),
(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`.
+96
View File
@@ -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]
+5 -5
View File
@@ -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());
}
+14 -6
View File
@@ -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,
})
}
+5 -3
View File
@@ -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
+5
View File
@@ -179,6 +179,11 @@ pub struct VectorcraftApp {
pub(crate) channel: Option<ControlChannel>,
/// A `ui.pointer` or `ui.tool.select` held until the synthetic input sent before it reached the tool.
deferred_control: Option<ControlRequest>,
/// 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<serde_json::Value>,
/// The confirms whose replies wait for the app's answer to a dialog's held OK.
pub(crate) held_confirms: Vec<control::HeldConfirm>,
/// Where a control-channel Rotate View drag began, kept between its requests.
pub(crate) control_rotate_press: Option<control::RotateViewPress>,
/// The `ui.pointer` replies that wait for the edit their gesture started on another thread.
+24
View File
@@ -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<serde_json::Value>,
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.
+27
View File
@@ -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
@@ -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}");
+7 -3
View File
@@ -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
+1 -1
View File
@@ -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 `<kind>` dialog cannot set protected field `<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 `<kind>` dialog cannot set protected field `<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` |