Merge pull request #2964 from dotCooCoo/feat/dialog-confirm-held-refusal

craft-automation: ui.dialog.confirm of a held OK replies with the app's answer, a refusal in English
This commit is contained in:
BFlat
2026-11-26 10:25:33 +07:00
committed by GitHub
4 changed files with 184 additions and 10 deletions
+62 -4
View File
@@ -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
@@ -15,6 +16,7 @@
use std::sync::mpsc::{Receiver, Sender};
use craft_ui::dialog::{DialogHost, DialogId, HeldOk};
use craft_ui::runtime::motion;
use craft_ui::runtime::windows::WindowHost;
use serde_json::{Value, json};
@@ -133,6 +135,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<String>,
},
}
impl Reply {
@@ -174,6 +189,7 @@ pub struct ControlChannel {
input_waiters: Vec<Sender<ControlResponse>>,
job_waiters: Vec<(JobId, Sender<ControlResponse>)>,
tree_waiters: Vec<Sender<ControlResponse>>,
held_waiters: Vec<(DialogId, u64, Sender<ControlResponse>)>,
/// The screenshot queue; the app calls its `issue` and `drain` from its UI and logic phases.
pub captures: Captures,
}
@@ -181,7 +197,14 @@ pub struct ControlChannel {
impl ControlChannel {
/// Attach a transport's receiver (TCP, stdin, tests).
pub fn new(rx: Receiver<ControlRequest>) -> 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
@@ -218,6 +241,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, region, viewport } => {
let request = ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms };
if let Err((reply, e)) = self.captures.admit(request, now) {
@@ -299,6 +334,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.
@@ -339,6 +397,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()
}
}
+30 -3
View File
@@ -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 most `fields` one `ui.dialog.set` call takes.
@@ -36,7 +38,8 @@ pub fn inspect(host: &DialogHost) -> Value {
/// - `ui.dialog.set {dialog, field, value}` sets one field ([`DialogHost::set_json_field`]); `{dialog, fields: [{field,
/// value?}]}` sets a list of at most [`MAX_DIALOG_FIELDS`], all or none ([`DialogHost::set_json_fields`]).
/// - `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<Result<Value, String>> {
@@ -49,6 +52,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<Reply> {
// 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<Value, String> {
let params = Params(params).only(None, fields)?;
let read = Params(&params);
@@ -67,6 +90,10 @@ fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, field
}
},
"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())?;
}
+91 -2
View File
@@ -1,9 +1,13 @@
//! `ui.dialog.*` on typed dialogs through one generic path.
use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, inspect};
use std::sync::mpsc::{Receiver, channel};
use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse};
use craft_automation::dialogs::{MAX_DIALOG_FIELDS, 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::<HostedParamDialog>()).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<ControlResponse> {
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::<HostedParamDialog>(), 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::<HostedParamDialog>();
// 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::<HostedParamDialog>();
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);
}
/// A `fields` list sets every field or none: a refused field in the middle leaves the dialog as it was and gives that
/// refusal; a list over the limit, an item without a string `field` and `field` beside `fields` are refused unread.
#[trial]
+1 -1
View File
@@ -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::<D>()` closes a dialog from outside as Escape would, and `StackDialog::cancelled` lets it release what it holds.
- `get`, `get_mut` and `confirm::<D>()` 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` (ui-patterns), `HostedAlert` (ui-panels), `HostedLayerStyle` and `HostedAdjustDialog<V, E>` around any adjustment editor (craft-imaging). A properties dialog is hosted as a `HostedParamDialog` over `PropertiesDialog::into_param_dialog()`. A footer button or a custom row's button that keeps a hosted form open comes back once, by its id, from `take_action`. Footer and row ids share that one channel.
- A `ParamDialog` with `tabs` shows a tab strip and the rows of the shown tab. Its own `params` are the shared rows, above the strip or under the tab's rows (`SharedRows`). Every tab's values open, are checked and answer together, whichever tab shows. A `ParamTab::read_only` tab shows its values without controls, under its note. A `read_only` dialog has only OK, no Alt reset, and answers with no values.