From a1cc33883315872f27ba84bafb0a16b87b708926 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:09:57 -0800 Subject: [PATCH] craft-automation: ui.dialog.confirm of a held OK replies with the app's answer, a refusal in English A dialog that holds its OK files the answer for the app, which accepts or refuses it later. ui.dialog.confirm replied success as soon as OK was filed, so a caller never learned that the app refused it, or why. - dialogs::dialog_reply runs a ui.dialog.* method like dialog_method and returns the Reply to settle. A confirm that files a held OK becomes Reply::AfterHeldOk, which waits for the app's answer. - ControlChannel::poll_held answers the waiting confirms from the host: success once the app accepts, an error with the refusal's reason (English for a Word) once it refuses, and an error when the dialog closes or opens again before the answer. - A second confirm while an answer waits is refused, as the disabled OK button is. A confirm after a refusal that no poll has read yet answers the earlier confirm with that refusal. --- crates/automation/src/control.rs | 66 +++++++++++++++++-- crates/automation/src/dialogs.rs | 33 +++++++++- crates/automation/tests/it/dialogs.rs | 93 ++++++++++++++++++++++++++- docs/ui-dialogs.md | 2 +- 4 files changed, 184 insertions(+), 10 deletions(-) diff --git a/crates/automation/src/control.rs b/crates/automation/src/control.rs index cc1e37c812..fbde905002 100644 --- a/crates/automation/src/control.rs +++ b/crates/automation/src/control.rs @@ -5,8 +5,9 @@ //! (`engine.execute`, `ui.inspect`, `ui.set`, `ui.dialog.*`, `ui.screenshot`, …) and hands the //! [`Reply`] to [`ControlChannel::settle`]. The channel replies at once, after the queued //! injected input has been processed ([`Reply::AfterInput`], so a following `ui.inspect` sees -//! the effect), when a background job ends ([`Reply::AfterJob`]), or when a screenshot completes -//! ([`Reply::Screenshot`], through [`crate::screenshot::Captures`]). +//! the effect), when a background job ends ([`Reply::AfterJob`]), when the app answers a dialog's +//! held OK ([`Reply::AfterHeldOk`]), or when a screenshot completes ([`Reply::Screenshot`], through +//! [`crate::screenshot::Captures`]). //! //! Deadlines: a request still queued when its [`REPLY_DEADLINE`] passes is dropped before dispatch //! and the transport replies [`expired_error`] (safe to re-send); one that was dispatched and gave @@ -16,6 +17,7 @@ use std::sync::mpsc::{Receiver, Sender}; use web_time::Instant; +use craft_ui::dialog::{DialogHost, DialogId, HeldOk}; use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; use serde_json::{Value, json}; @@ -130,6 +132,19 @@ pub enum Reply { /// A `ui.accessTree`: hold the reply until the window's settled access tree can be read /// ([`ControlChannel::poll_access_trees`]). AccessTree, + /// A `ui.dialog.confirm` that filed the held OK of a dialog for the app: hold the reply until the + /// app answers it ([`ControlChannel::poll_held`]). + #[non_exhaustive] + AfterHeldOk { + /// The dialog whose OK is held. + dialog: DialogId, + /// Which open of the dialog ([`DialogHost::open_serial`]): a later open of the same dialog + /// is not the one the request confirmed. + open: u64, + /// The app's refusal of the dialog's previous OK, when this confirm filed OK again after it: + /// the earlier confirms still held for this open are answered with it. + refused: Option, + }, } impl Reply { @@ -171,6 +186,7 @@ pub struct ControlChannel { input_waiters: Vec>, job_waiters: Vec<(JobId, Sender)>, tree_waiters: Vec>, + held_waiters: Vec<(DialogId, u64, Sender)>, /// The screenshot queue; the app calls its `issue` and `drain` from its UI and logic phases. pub captures: Captures, } @@ -178,7 +194,14 @@ pub struct ControlChannel { impl ControlChannel { /// Attach a transport's receiver (TCP, stdin, tests). pub fn new(rx: Receiver) -> Self { - Self { rx, input_waiters: Vec::new(), job_waiters: Vec::new(), tree_waiters: Vec::new(), captures: Captures::default() } + Self { + rx, + input_waiters: Vec::new(), + job_waiters: Vec::new(), + tree_waiters: Vec::new(), + held_waiters: Vec::new(), + captures: Captures::default(), + } } /// The next request to run, claimed through [`Dispatch::start`]. Expired or abandoned @@ -207,6 +230,18 @@ impl ControlChannel { Reply::AfterInput => self.input_waiters.push(reply), Reply::AfterJob(job) => self.job_waiters.push((job, reply)), Reply::AccessTree => self.tree_waiters.push(reply), + Reply::AfterHeldOk { dialog, open, refused } => { + if let Some(reason) = refused { + self.held_waiters.retain(|(earlier, earlier_open, tx)| { + let answered = (*earlier, *earlier_open) == (dialog, open); + if answered { + let _ = tx.send(json!({"ok": false, "error": reason})); + } + !answered + }); + } + self.held_waiters.push((dialog, open, reply)); + } Reply::Screenshot { token, path, viewport } => { if let Err((reply, e)) = self.captures.admit(ScreenshotRequest { token, path, viewport, reply, document, settle_ms }, motion::now()) { let _ = reply.send(json!({"ok": false, "error": e})); @@ -284,6 +319,29 @@ impl ControlChannel { } } + /// Answers the held `ui.dialog.confirm` requests ([`Reply::AfterHeldOk`]) from `host`: success + /// once the app accepted the dialog's held OK; once it refused it, an error whose text is the + /// refusal's reason, English for a reason given as a `Word`; an error once the dialog closed + /// while it waited, also when the same dialog opened again since. A request stays held while + /// the app has not answered. Call it in every pass after the app answered the held OKs it + /// answers in that pass and before the pass runs the host ([`DialogHost::run`]), which closes a + /// dialog the app accepted; calling it more than once in a pass is harmless. + pub fn poll_held(&mut self, host: &DialogHost) { + self.held_waiters.retain(|(dialog, open, reply)| { + let answer = match host.held_state(*dialog) { + _ if host.open_serial(*dialog) != Some(*open) => { + json!({"ok": false, "error": "the dialog closed while its OK waited for the app's answer"}) + } + Some(HeldOk::Waiting) => return true, + Some(HeldOk::Accepted) => json!({"ok": true, "result": null}), + Some(HeldOk::Refused(reason)) => json!({"ok": false, "error": reason.as_str()}), + _ => json!({"ok": false, "error": "the app refused OK"}), + }; + let _ = reply.send(answer); + false + }); + } + /// Drops the host's queued input and the step in flight, and fails every /// [`Reply::AfterInput`] waiter with `input cancelled: {reason}`, also when only waiters /// remain (their input was already consumed). True when anything was pending or waiting. @@ -324,6 +382,6 @@ impl ControlChannel { /// Waiters of every kind, for `ui.inspect`'s `pending` count and tests. pub fn waiting(&self) -> usize { - self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.captures.pending() + self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.held_waiters.len() + self.captures.pending() } } diff --git a/crates/automation/src/dialogs.rs b/crates/automation/src/dialogs.rs index 62fc0b268b..6b8db5d943 100644 --- a/crates/automation/src/dialogs.rs +++ b/crates/automation/src/dialogs.rs @@ -1,7 +1,8 @@ //! `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` on an app's [`DialogHost`], for every dialog type. //! -//! The app's method table hands these methods to [`dialog_method`] and lists [`inspect`] under `ui.inspect`'s -//! `dialogs`. A dialog is named by the `id` `inspect` lists, or `"top"` for the top one; its fields are its +//! The app's method table hands these methods to [`dialog_method`], or to [`dialog_reply`] for a reply that waits +//! for the app's answer to a held OK, and lists [`inspect`] under `ui.inspect`'s `dialogs`. A dialog is named by the +//! `id` `inspect` lists, or `"top"` for the top one; its fields are its //! [`StackDialog::json_fields`](craft_ui::dialog::StackDialog::json_fields). Opening a dialog (`ui.dialog.open`) and //! running the command its answer is for stay the app's: an answer waits for the app's `DialogHost::take` as a //! click's would. @@ -10,6 +11,7 @@ use craft_ui::dialog::{DialogHost, DialogId, HeldOk, StandardPrompt}; use egui::Context; use serde_json::{Value, json}; +use crate::control::Reply; use crate::protocol::Params; /// The open dialogs, the top one last: `{id, parent, key, fields}`, `null` for a missing parent, key or fields. Ids @@ -32,7 +34,8 @@ pub fn inspect(host: &DialogHost) -> Value { /// /// - `ui.dialog.set {dialog, field, value}` sets one field ([`DialogHost::set_json_field`]). /// - `ui.dialog.confirm {dialog, choice?}` answers OK, as the default button would, after setting the `choice` field -/// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it. +/// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it; +/// a second confirm while that answer waits is refused. /// - `ui.dialog.cancel {dialog}` closes the dialog as Escape would: a standard prompt with a button for its Escape /// answer gives that answer, with its tag; any other dialog closes with its children with Cancel. pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option> { @@ -45,6 +48,26 @@ pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params: Some(run(host, ctx, method, params, fields)) } +/// [`dialog_method`] as the [`Reply`] the app hands to [`ControlChannel::settle`](crate::ControlChannel::settle): a +/// `ui.dialog.confirm` that files a dialog's held OK for the app replies once the app answers it +/// ([`Reply::AfterHeldOk`], answered by [`ControlChannel::poll_held`](crate::ControlChannel::poll_held)), so a refusal +/// reaches the caller as the reply's error, in its reason's English text. Every other call replies at once. +pub fn dialog_reply(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option { + // The dialog is named before the call: a confirm that closes it may leave another dialog on top. + let named = dialog_id(host, params).ok(); + // A refusal this confirm replaces still answers the confirms it refused. + let refused = match named.and_then(|id| host.held_state(id)) { + Some(HeldOk::Refused(reason)) => Some(reason.as_str().to_owned()), + _ => None, + }; + let result = dialog_method(host, ctx, method, params)?; + let held = named.filter(|&id| method == "ui.dialog.confirm" && result.is_ok() && host.held_state(id) == Some(HeldOk::Waiting)); + Some(match held.and_then(|id| Some((id, host.open_serial(id)?))) { + Some((dialog, open)) => Reply::AfterHeldOk { dialog, open, refused }, + None => Reply::from_result(result), + }) +} + fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, fields: &[&str]) -> Result { let params = Params(params).only(None, fields)?; let read = Params(¶ms); @@ -55,6 +78,10 @@ fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, field host.set_json_field(ctx, id, field, params.get("value").cloned().unwrap_or(Value::Null))?; } "ui.dialog.confirm" => { + // A second OK while the first waits files nothing, as the disabled button shows. + if host.held_state(id) == Some(HeldOk::Waiting) { + return Err("the dialog's OK waits for the app's answer to an earlier OK".to_owned()); + } if let Some(choice) = params.get("choice") { host.set_json_field(ctx, id, "choice", choice.clone())?; } diff --git a/crates/automation/tests/it/dialogs.rs b/crates/automation/tests/it/dialogs.rs index 1763a90f72..4cc8a7b68e 100644 --- a/crates/automation/tests/it/dialogs.rs +++ b/crates/automation/tests/it/dialogs.rs @@ -1,9 +1,13 @@ //! `ui.dialog.*` on typed dialogs through one generic path. -use craft_automation::dialogs::{dialog_method, inspect}; +use std::sync::mpsc::{Receiver, channel}; + +use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse}; +use craft_automation::dialogs::{dialog_method, dialog_reply, inspect}; use craft_ui::contract::{Bind, SaveKey}; -use craft_ui::dialog::{DialogHost, DialogResult, PromptChoice, PromptKind, StandardPrompt}; +use craft_ui::dialog::{DialogHost, DialogId, DialogResult, PromptChoice, PromptKind, StandardPrompt}; use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft_ui::runtime::env::{Label, Word}; use craft_ui::testing::trial; use egui::Context; use serde_json::{Value, json}; @@ -124,6 +128,91 @@ fn param_dialog_automation_follows_its_rows() { assert_eq!((reopened.fields.number("radius"), reopened.fields.text("method")), (Some(7.0), Some("zoom"))); } +const TAKEN: Word = Word::keyed("craft_automation.nameTaken", "A preset with that name exists"); + +/// The open parameter dialog `id` names. +fn held(host: &mut DialogHost, id: DialogId) -> &mut HostedParamDialog { + host.get_dyn_mut(id).and_then(|dialog| dialog.downcast_mut::()).expect("the held dialog is open") +} + +/// A `ui.dialog.confirm` that files a held OK replies with the app's answer: nothing while the app has not answered, +/// an error with the refusal's English text once it refuses, success once it accepts, and an error when the dialog +/// closes first, also when it opened again since. A second confirm while the answer waits is refused, and one after a +/// refusal no poll has read answers the earlier confirm with it. A dialog without a held OK replies at once. +#[trial] +fn a_confirm_of_a_held_ok_replies_with_the_apps_answer() { + let ctx = Context::default(); + let mut host = DialogHost::new(); + let (_requests, rx) = channel(); + let mut control = ControlChannel::new(rx); + let dialog = |ctx: &Context, held: bool| { + let dialog = HostedParamDialog::new(ctx, "blur", DialogFields::new(), |fields| { + ParamDialog::new("blur", "Blur", Param::parse_list(r#"{"radius":0.1..1000=1}"#)).values(Bind::bound(fields)) + }); + if held { dialog.held_ok() } else { dialog } + }; + let confirm = |host: &mut DialogHost, control: &mut ControlChannel, id: DialogId| -> Receiver { + let (request, reply) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": id.value()})); + let outcome = dialog_reply(host, &ctx, &request.method, &request.params).expect("a ui.dialog method"); + control.settle(request, outcome, None, 0.0); + reply + }; + + let id = host.open(dialog(&ctx, true)); + let reply = confirm(&mut host, &mut control, id); + control.poll_held(&host); + assert!(reply.try_recv().is_err(), "the reply waits for the app's answer"); + assert_eq!(control.waiting(), 1); + let again = confirm(&mut host, &mut control, id); + assert!(again.try_recv().is_ok_and(|reply| reply["ok"] == false), "a second OK while the first waits is refused"); + assert_eq!(control.waiting(), 1); + assert!(held(&mut host, id).take_ok().is_some(), "OK filed the answer for the app"); + held(&mut host, id).answer_ok(Err(Label::from(TAKEN))); + control.poll_held(&host); + assert_eq!(reply.try_recv(), Ok(json!({"ok": false, "error": "A preset with that name exists"}))); + assert_eq!(control.waiting(), 0); + + // A confirm after a refusal no poll has read yet answers the earlier confirm with that refusal. + let first = confirm(&mut host, &mut control, id); + assert!(held(&mut host, id).take_ok().is_some(), "OK files the answer again after a refusal"); + held(&mut host, id).answer_ok(Err(Label::from(TAKEN))); + let reply = confirm(&mut host, &mut control, id); + assert_eq!(first.try_recv(), Ok(json!({"ok": false, "error": "A preset with that name exists"}))); + assert_eq!(control.waiting(), 1); + assert!(held(&mut host, id).take_ok().is_some()); + held(&mut host, id).answer_ok(Ok(())); + control.poll_held(&host); + assert_eq!(reply.try_recv(), Ok(json!({"ok": true, "result": null}))); + assert!(host.confirm_by_id(&ctx, id), "the accepted dialog closes"); + assert!(matches!(host.take_keyed::(), Some((DialogResult::Ok(_), _)))); + + let id = host.open(dialog(&ctx, true)); + let reply = confirm(&mut host, &mut control, id); + assert!(host.cancel_by_id(&ctx, id)); + control.poll_held(&host); + let closed = reply.try_recv().expect("a closed dialog answers the held confirm"); + assert_eq!(closed["ok"], false); + assert!(closed["error"].as_str().is_some_and(|error| error.contains("closed")), "{closed}"); + host.take_keyed::(); + + // The same dialog opened again is a new open: its answer is not the closed one's. + let id = host.open(dialog(&ctx, true)); + let reply = confirm(&mut host, &mut control, id); + assert!(host.cancel_by_id(&ctx, id)); + assert_eq!(host.open(dialog(&ctx, true)), id, "a reopened dialog has the same id"); + assert_eq!(control.waiting(), 1); + control.poll_held(&host); + let closed = reply.try_recv().expect("the closed open's confirm is answered"); + assert!(closed["error"].as_str().is_some_and(|error| error.contains("closed")), "{closed}"); + assert!(host.cancel_by_id(&ctx, id)); + host.take_keyed::(); + + let id = host.open(dialog(&ctx, false)); + let reply = confirm(&mut host, &mut control, id); + assert_eq!(reply.try_recv(), Ok(json!({"ok": true, "result": null})), "a dialog without a held OK replies at once"); + assert_eq!(control.waiting(), 0); +} + /// `"top"` names the top dialog of the stack: a child over its parent takes the field, the parent keeps its own; with /// nothing open the request says so. #[trial] diff --git a/docs/ui-dialogs.md b/docs/ui-dialogs.md index 57ff766c89..6a048df8b4 100644 --- a/docs/ui-dialogs.md +++ b/docs/ui-dialogs.md @@ -82,7 +82,7 @@ Rules of the host: - `enqueue` queues a startup modal by `StartupStage` (recovery, first-launch offer, warning, update). Each opens when the stack is empty, one at a time. - `cancel::()` closes a dialog from outside as Escape would, and `StackDialog::cancelled` lets it release what it holds. - `get`, `get_mut` and `confirm::()` reach the open dialog's value, so a script or a test sets fields and answers OK as a user would. -- Automation that doesn't know the dialog's type goes by id. `open_dialogs` lists the open dialogs with their `StackDialog::json_fields`; `set_json_field(ctx, id, field, value)` sets one as the user would (a prompt's answer is its `choice` field, one it has an enabled button for); `confirm_by_id` and `cancel_by_id` close it. A dialog type opts in by implementing `json_fields` and `set_json_field`; `HostedParamDialog`, `StandardPrompt` and `UnsavedChangesDialog` do. `craft_automation::dialogs` runs `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` on a host and lists its dialogs for `ui.inspect`, so an app's control channel needs no code per dialog type. +- Automation that doesn't know the dialog's type goes by id. `open_dialogs` lists the open dialogs with their `StackDialog::json_fields`; `set_json_field(ctx, id, field, value)` sets one as the user would (a prompt's answer is its `choice` field, one it has an enabled button for); `confirm_by_id` and `cancel_by_id` close it. A dialog type opts in by implementing `json_fields` and `set_json_field`; `HostedParamDialog`, `StandardPrompt` and `UnsavedChangesDialog` do. `craft_automation::dialogs` runs `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` on a host and lists its dialogs for `ui.inspect`, so an app's control channel needs no code per dialog type. Its `dialog_reply` holds the reply to a `ui.dialog.confirm` that files a held OK until the app answers it (`ControlChannel::poll_held`): the caller gets success when the app accepts, and the refusal's reason, in English for a `Word`, as the error when it refuses. - `take_keyed` returns the result with `StackDialog::key`, so a Cancel still names the command it answers. - A hosted form owns what its dialog edits. What the dialog asks of the app while open (a preview, a path, a colour, a link) waits on the hosted value until the app takes it, and the app answers through the hosted value's methods. The hosted forms: `HostedParamDialog`, `HostedFormatOptions`, `HostedImageSize`, `HostedCanvasSize`, `HostedExportAs`, `HostedSaveForWeb`, `HostedAbout`, `HostedNewDocument`, `HostedGuideLayoutDialog`, `HostedNewGuideDialog`, `HostedPropertiesDialog` (ui-patterns), `HostedAlert` (ui-panels), `HostedLayerStyle` and `HostedAdjustDialog` around any adjustment editor (craft-imaging). - While the host runs its dialogs, or inside a `with` closure, `BodyCx::dialogs` returns `None`. A dialog that the host runs opens children through its own `DialogHost` value.