From e51e929e48194a2b9cc50f6d4e8175c103c7fb76 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 12 Nov 2026 22:15:50 +0000 Subject: [PATCH] Dialogs: automation surface for every StackDialog StackDialog gains json_fields and set_json_field; DialogHost lists its open dialogs with their fields, sets one by id, and confirms or cancels by id whatever the type. HostedParamDialog (values by parameter row, with a programmatic OK), StandardPrompt and UnsavedChangesDialog (their choice) implement them. craft_automation::dialogs runs ui.dialog.set/confirm/cancel on a host and lists its dialogs for ui.inspect. --- Cargo.lock | 2 + crates/automation/src/dialogs.rs | 69 +++++++++++++++++ crates/automation/src/lib.rs | 2 + crates/automation/tests/it/dialogs.rs | 54 +++++++++++++ crates/automation/tests/it/main.rs | 1 + crates/dialogs/src/service.rs | 2 +- crates/ui-panels/Cargo.toml | 1 + crates/ui-panels/src/dialog/host.rs | 76 ++++++++++++++++--- crates/ui-panels/src/dialog/mod.rs | 2 +- crates/ui-panels/src/dialog/prompts.rs | 25 +++++- crates/ui-panels/src/dialog/stack.rs | 5 ++ crates/ui-panels/src/dialog/unsaved.rs | 51 ++++++++++++- crates/ui-patterns/Cargo.toml | 1 + .../src/patterns/form_dialogs/dialog.rs | 37 ++++++++- docs/ui-dialogs.md | 1 + 15 files changed, 311 insertions(+), 18 deletions(-) create mode 100644 crates/automation/src/dialogs.rs create mode 100644 crates/automation/tests/it/dialogs.rs diff --git a/Cargo.lock b/Cargo.lock index ddc71e013..3f4e9ae95 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2654,6 +2654,7 @@ dependencies = [ "craft-ui-widgets", "egui", "serde", + "serde_json", "toml", ] @@ -2673,6 +2674,7 @@ dependencies = [ "craft-ui-test-kit", "egui", "serde", + "serde_json", "toml", "toml_edit", "zeroize", diff --git a/crates/automation/src/dialogs.rs b/crates/automation/src/dialogs.rs new file mode 100644 index 000000000..3fac06efe --- /dev/null +++ b/crates/automation/src/dialogs.rs @@ -0,0 +1,69 @@ +//! `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` number `inspect` lists; 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. + +use craft_ui::dialog::{DialogHost, DialogId}; +use egui::Context; +use serde_json::{Value, json}; + +use crate::protocol::Params; + +/// The open dialogs, the top one last: `{id, parent, key, fields}`, `null` for a missing parent, key or fields. +pub fn inspect(host: &DialogHost) -> Value { + host.open_dialogs() + .into_iter() + .map(|dialog| json!({"id": dialog.id.value(), "parent": dialog.parent.map(|id| id.value()), "key": dialog.key, "fields": dialog.fields})) + .collect() +} + +/// Runs a `ui.dialog.*` method on `host`; `None` when `method` is not one of them. +/// +/// - `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). +/// - `ui.dialog.cancel {dialog}` closes the dialog and its children with Cancel. +pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option> { + let fields: &[&str] = match method { + "ui.dialog.set" => &["dialog", "field", "value"], + "ui.dialog.confirm" => &["dialog", "choice"], + "ui.dialog.cancel" => &["dialog"], + _ => return None, + }; + Some(run(host, ctx, method, params, fields)) +} + +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); + let id = dialog(host, read)?; + match method { + "ui.dialog.set" => { + let field = read.str_field("field")?.ok_or("missing `field`")?; + host.set_json_field(id, field, params.get("value").cloned().unwrap_or(Value::Null))?; + } + "ui.dialog.confirm" => { + if let Some(choice) = params.get("choice") { + host.set_json_field(id, "choice", choice.clone())?; + } + if !host.confirm_by_id(ctx, id) { + return Err("the dialog refuses OK: it is disabled, or the dialog has no programmatic OK".to_owned()); + } + } + _ => { + if !host.cancel_by_id(ctx, id) { + return Err(format!("no dialog {}", id.value())); + } + } + } + Ok(Value::Null) +} + +/// The dialog `params.dialog` names, from the stack; one the app shows beside the host is refused by the host. +fn dialog(host: &DialogHost, params: Params<'_>) -> Result { + let value = params.uint_field("dialog")?.ok_or("missing `dialog`")?; + host.stack().ids().find(|id| id.value() == value).ok_or_else(|| format!("no dialog {value}")) +} diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 2f8728170..e89f9833e 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -23,6 +23,8 @@ pub mod ui; pub mod args; #[cfg(all(feature = "ui", not(target_arch = "wasm32")))] pub mod control; +#[cfg(all(feature = "ui", not(target_arch = "wasm32")))] +pub mod dialogs; #[cfg(not(target_arch = "wasm32"))] pub mod profiler; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/automation/tests/it/dialogs.rs b/crates/automation/tests/it/dialogs.rs new file mode 100644 index 000000000..6756e68dd --- /dev/null +++ b/crates/automation/tests/it/dialogs.rs @@ -0,0 +1,54 @@ +//! `ui.dialog.*` on typed dialogs through one generic path. + +use craft_automation::dialogs::{dialog_method, inspect}; +use craft_ui::contract::Bind; +use craft_ui::dialog::{DialogHost, DialogResult, PromptChoice, PromptKind, StandardPrompt}; +use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog}; +use craft_ui::testing::trial; +use egui::Context; +use serde_json::{Value, json}; + +fn call(host: &mut DialogHost, ctx: &Context, method: &str, params: Value) -> Result { + dialog_method(host, ctx, method, ¶ms).expect("a ui.dialog method") +} + +/// A parameter dialog and a prompt are listed with their fields, set by key and answered by id, with no code that +/// knows their types; a value the row can't hold and an unknown choice are refused. +#[trial] +fn dialog_methods_read_set_and_answer_typed_dialogs() { + let ctx = Context::default(); + let mut host = DialogHost::new(); + host.open(HostedParamDialog::new("gaussianBlur", DialogFields::from_pairs([("radius", 1.0)]), |fields| { + ParamDialog::new("gaussianBlur", "Gaussian Blur", Param::parse_list(r#"{"radius":0.1..1000=1,"method":"spin|zoom"}"#)) + .values(Bind::bound(fields)) + })); + let listed = inspect(&host); + assert_eq!(listed[0]["key"], "gaussianBlur"); + assert_eq!(listed[0]["fields"], json!({"radius": 1.0})); + let blur = listed[0]["id"].clone(); + + assert_eq!(call(&mut host, &ctx, "ui.dialog.set", json!({"dialog": blur, "field": "radius", "value": 4.5})), Ok(Value::Null)); + assert!(call(&mut host, &ctx, "ui.dialog.set", json!({"dialog": blur, "field": "radius", "value": 5000})).is_err_and(|e| e.contains("radius"))); + assert!( + call(&mut host, &ctx, "ui.dialog.set", json!({"dialog": blur, "field": "angle", "value": 1})).is_err_and(|e| e.contains("unknown field")) + ); + assert_eq!(inspect(&host)[0]["fields"]["radius"], 4.5); + assert_eq!(call(&mut host, &ctx, "ui.dialog.confirm", json!({"dialog": blur})), Ok(Value::Null)); + let Some(DialogResult::Ok(result)) = host.take::() else { panic!("the blur dialog answers OK") }; + assert_eq!((result.fields.number("radius"), result.fields.text("method")), (Some(4.5), Some("spin"))); + assert_eq!(inspect(&host), json!([])); + + host.open(StandardPrompt::new(PromptKind::TrashMask)); + let prompt = inspect(&host)[0]["id"].clone(); + assert_eq!(inspect(&host)[0]["fields"]["choice"], "proceed"); + assert!(call(&mut host, &ctx, "ui.dialog.confirm", json!({"dialog": prompt, "choice": "maybe"})).is_err()); + assert_eq!(call(&mut host, &ctx, "ui.dialog.confirm", json!({"dialog": prompt, "choice": "alternate"})), Ok(Value::Null)); + let Some(DialogResult::Ok(answer)) = host.take::() else { panic!("the prompt answers") }; + assert_eq!(answer.choice, PromptChoice::Alternate); + + host.open(StandardPrompt::new(PromptKind::TrashMask)); + let prompt = inspect(&host)[0]["id"].clone(); + assert_eq!(call(&mut host, &ctx, "ui.dialog.cancel", json!({"dialog": prompt})), Ok(Value::Null)); + assert!(matches!(host.take::(), Some(DialogResult::Cancel))); + assert!(call(&mut host, &ctx, "ui.dialog.cancel", json!({"dialog": prompt})).is_err()); +} diff --git a/crates/automation/tests/it/main.rs b/crates/automation/tests/it/main.rs index cdb69c178..2bacd6f0f 100644 --- a/crates/automation/tests/it/main.rs +++ b/crates/automation/tests/it/main.rs @@ -2,4 +2,5 @@ mod actions; mod control; +mod dialogs; mod screenshot; diff --git a/crates/dialogs/src/service.rs b/crates/dialogs/src/service.rs index 7f10fe469..b38e584eb 100644 --- a/crates/dialogs/src/service.rs +++ b/crates/dialogs/src/service.rs @@ -341,7 +341,7 @@ impl FilePanels { /// The dialog ids of the Replace questions open on the app's dialog host, for an app that lists /// its open prompts to automation (`ui.inspect`) and answers them by id - /// (`DialogHost::confirm_by_id::`). + /// (`DialogHost::confirm_by_id`). #[cfg(feature = "ui")] pub fn open_questions(&self) -> impl Iterator + '_ { self.prompts.iter().filter_map(|asked| asked.dialog) diff --git a/crates/ui-panels/Cargo.toml b/crates/ui-panels/Cargo.toml index db84842df..2e2703415 100644 --- a/crates/ui-panels/Cargo.toml +++ b/crates/ui-panels/Cargo.toml @@ -31,6 +31,7 @@ craft-host = { workspace = true } craft-quit = { workspace = true } craft-i18n = { workspace = true, features = ["collate"] } serde = { workspace = true } +serde_json = { workspace = true } [dev-dependencies] craft-ui-panels = { path = ".", features = ["testing"] } diff --git a/crates/ui-panels/src/dialog/host.rs b/crates/ui-panels/src/dialog/host.rs index 743c0a520..3d2135570 100644 --- a/crates/ui-panels/src/dialog/host.rs +++ b/crates/ui-panels/src/dialog/host.rs @@ -8,6 +8,7 @@ use std::any::{Any, TypeId}; use std::fmt; use egui::{Context, Ui}; +use serde_json::Value; use super::stack::{DialogId, DialogStack}; use crate::contract::{Pattern, PatternKind, PatternProbe}; @@ -72,6 +73,19 @@ pub trait StackDialog: Any + Send { None } + /// The dialog's values as a JSON object, keyed as [`set_json_field`](StackDialog::set_json_field) takes them: + /// what automation lists for the open dialog (`ui.inspect`). `None` (the default) for a dialog without values. + fn json_fields(&self) -> Option { + None + } + + /// Sets the value `field` names, as the user editing that control would (`ui.dialog.set`); a prompt's answer + /// is its `choice` field. `Err` says why the dialog refused: no such field, or a value the control can't hold. + /// Refuses everything by default. + fn set_json_field(&mut self, field: &str, _value: Value) -> Result<(), String> { + Err(format!("unknown field `{field}`: this dialog has no fields")) + } + /// Called when the host closes the dialog from outside with [`DialogResult::Cancel`] /// ([`DialogHost::cancel`], a dialog of the same type opened over it, or its parent closing), /// so it can release what it holds: a pick ticket (`Files::forget`), an armed dropper. The @@ -114,6 +128,8 @@ trait AnyStackDialog: Send { fn key(&self) -> Option; fn instance(&self) -> Option; fn confirm_erased(&mut self, ctx: &Context) -> Option>; + fn json_fields(&self) -> Option; + fn set_json_field(&mut self, field: &str, value: Value) -> Result<(), String>; fn show_erased(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option>; /// `DialogResult::::Cancel`, boxed, for a dialog closed from outside. fn cancelled(&self) -> Box; @@ -144,6 +160,14 @@ impl AnyStackDialog for D { self.confirm(ctx).map(|result| Box::new(DialogResult::Ok(result)) as Box) } + fn json_fields(&self) -> Option { + StackDialog::json_fields(self) + } + + fn set_json_field(&mut self, field: &str, value: Value) -> Result<(), String> { + StackDialog::set_json_field(self, field, value) + } + fn show_erased(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option> { self.show(ui, stack).map(|result| Box::new(result) as Box) } @@ -195,7 +219,11 @@ impl AnyStackDialog for D { /// [`open_unless_open`](DialogHost::open_unless_open) refuses while any `D` is open and leaves /// it alone (PhotoCraft's `confirmationPending`). /// - Automation: [`get`](DialogHost::get) and [`get_mut`](DialogHost::get_mut) reach the open -/// dialog's value, so a script sets fields and a test reads them like a user would. +/// dialog's value for code that knows its type. A script that doesn't goes by id: +/// [`open_dialogs`](DialogHost::open_dialogs) lists every open dialog with its +/// [`json_fields`](StackDialog::json_fields), [`set_json_field`](DialogHost::set_json_field) sets one, +/// and [`confirm_by_id`](DialogHost::confirm_by_id) and [`cancel_by_id`](DialogHost::cancel_by_id) close it, +/// whatever its type. #[derive(Default)] pub struct DialogHost { stack: DialogStack, @@ -207,6 +235,20 @@ pub struct DialogHost { replaced: Vec>, } +/// One open dialog as automation sees it ([`DialogHost::open_dialogs`]). +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct OpenDialog { + /// The id the `_by_id` calls take. + pub id: DialogId, + /// The dialog it was opened from, for a child. + pub parent: Option, + /// [`StackDialog::key`]. + pub key: Option, + /// [`StackDialog::json_fields`]. + pub fields: Option, +} + /// A finished dialog's answer, with the key the dialog had. struct StoredResult { type_id: TypeId, @@ -329,9 +371,9 @@ impl DialogHost { } } - /// [`confirm`](DialogHost::confirm) for the open `D` that `id` names. - pub fn confirm_by_id(&mut self, ctx: &Context, id: DialogId) -> bool { - match self.position_by_id::(id) { + /// [`confirm`](DialogHost::confirm) for the open dialog `id` names, whatever its type. + pub fn confirm_by_id(&mut self, ctx: &Context, id: DialogId) -> bool { + match self.position_by_id(id) { Some(at) => self.confirm_at(ctx, at), None => false, } @@ -356,9 +398,9 @@ impl DialogHost { } } - /// [`cancel`](DialogHost::cancel) for the open `D` that `id` names. - pub fn cancel_by_id(&mut self, ctx: &Context, id: DialogId) -> bool { - match self.position_by_id::(id) { + /// [`cancel`](DialogHost::cancel) for the open dialog `id` names, whatever its type. + pub fn cancel_by_id(&mut self, ctx: &Context, id: DialogId) -> bool { + match self.position_by_id(id) { Some(at) => self.cancel_at(ctx, at), None => false, } @@ -374,6 +416,22 @@ impl DialogHost { true } + /// The open dialogs in opening order (the top one last), with their fields. + pub fn open_dialogs(&self) -> Vec { + self.open + .iter() + .map(|dialog| OpenDialog { id: dialog.id(), parent: self.stack.parent(dialog.id()), key: dialog.key(), fields: dialog.json_fields() }) + .collect() + } + + /// Sets `field` of the open dialog `id` names ([`StackDialog::set_json_field`]), whatever its type. + pub fn set_json_field(&mut self, id: DialogId, field: &str, value: Value) -> Result<(), String> { + match self.open.iter_mut().find(|dialog| dialog.id() == id) { + Some(dialog) => dialog.set_json_field(field, value), + None => Err("no such dialog".to_owned()), + } + } + /// The open dialog `id` ([`dialog_id`](super::dialog_id) of its key) as `Any`, for an app with /// many dialog types that looks the top one up by id and downcasts. pub fn get_dyn(&self, id: DialogId) -> Option<&dyn Any> { @@ -411,8 +469,8 @@ impl DialogHost { self.open.iter().rposition(|dialog| dialog.result_type() == TypeId::of::()) } - fn position_by_id(&self, id: DialogId) -> Option { - self.open.iter().position(|dialog| dialog.id() == id && dialog.result_type() == TypeId::of::()) + fn position_by_id(&self, id: DialogId) -> Option { + self.open.iter().position(|dialog| dialog.id() == id) } fn store_result(&mut self, dialog: &dyn AnyStackDialog, result: Box) { diff --git a/crates/ui-panels/src/dialog/mod.rs b/crates/ui-panels/src/dialog/mod.rs index a563bfb70..6c2b473a1 100644 --- a/crates/ui-panels/src/dialog/mod.rs +++ b/crates/ui-panels/src/dialog/mod.rs @@ -25,7 +25,7 @@ pub use blocking::{BlockingOverlay, BlockingOverlayStyle}; pub use frame::{DialogFrame, DialogFrameStyle, DialogOutput, FooterCx, FooterHooks}; #[doc(hidden)] pub use host::dialog_probe; -pub use host::{DialogHost, DialogResult, StackDialog, StartupStage}; +pub use host::{DialogHost, DialogResult, OpenDialog, StackDialog, StartupStage}; pub use modal::{Dialog, DialogStyle}; pub use prompt::{Prompt, PromptOutput}; pub use prompts::{PromptAnswer, PromptChoice, PromptKind, StandardPrompt, StandardPromptOutput}; diff --git a/crates/ui-panels/src/dialog/prompts.rs b/crates/ui-panels/src/dialog/prompts.rs index 36a597f86..acc3b534a 100644 --- a/crates/ui-panels/src/dialog/prompts.rs +++ b/crates/ui-panels/src/dialog/prompts.rs @@ -15,6 +15,7 @@ use craft_behavior::Mixed; use craft_i18n::{Count, Format}; use craft_theme::variant::Tone; use egui::{Context, Response, Ui}; +use serde_json::{Value, json}; use std::any::Any; use std::fmt; @@ -61,8 +62,9 @@ pub enum PromptKind { Custom, } -/// The answer to a `StandardPrompt`. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +/// The answer to a `StandardPrompt`. Automation names it in camel case (`"proceed"`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum PromptChoice { /// The default button: Delete, Open Anyway, Replace, Apply. @@ -449,4 +451,23 @@ impl StackDialog for StandardPrompt { fn confirm(&mut self, _: &Context) -> Option { Some(self.answer(self.chosen, self.skip)) } + + /// `choice`, the answer a programmatic OK gives, and `skip`, the "Don't show again" box where the prompt has + /// one. + fn json_fields(&self) -> Option { + let mut fields = json!({ "choice": self.chosen }); + if self.skip_box { + fields["skip"] = Value::Bool(self.skip); + } + Some(fields) + } + + fn set_json_field(&mut self, field: &str, value: Value) -> Result<(), String> { + match field { + "choice" => self.set_choice(serde_json::from_value(value).map_err(|error| format!("`choice`: {error}"))?), + "skip" if self.skip_box => self.skip = value.as_bool().ok_or("`skip` takes true or false")?, + _ => return Err(format!("unknown field `{field}`")), + } + Ok(()) + } } diff --git a/crates/ui-panels/src/dialog/stack.rs b/crates/ui-panels/src/dialog/stack.rs index 7ab004b6a..08d694717 100644 --- a/crates/ui-panels/src/dialog/stack.rs +++ b/crates/ui-panels/src/dialog/stack.rs @@ -83,6 +83,11 @@ impl DialogStack { self.entries.iter().any(|(_, parent)| *parent == Some(id)) } + /// The dialog `id` was opened from, when it is a child. + pub fn parent(&self, id: DialogId) -> Option { + self.entries.iter().find(|(entry, _)| *entry == id)?.1 + } + /// The dialogs opened from `id`, in opening order. pub fn children(&self, id: DialogId) -> impl Iterator + '_ { self.entries.iter().filter(move |(_, parent)| *parent == Some(id)).map(|(entry, _)| *entry) diff --git a/crates/ui-panels/src/dialog/unsaved.rs b/crates/ui-panels/src/dialog/unsaved.rs index af49a26b3..d7a3f90ce 100644 --- a/crates/ui-panels/src/dialog/unsaved.rs +++ b/crates/ui-panels/src/dialog/unsaved.rs @@ -15,6 +15,7 @@ use craft_behavior::Mixed; use craft_host::target::Os; use craft_quit::{CloseAnswer, CloseScope}; use egui::{Context, Response, Ui}; +use serde_json::{Value, json}; /// The answer for one document, with whether it applies to the rest. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -76,6 +77,17 @@ impl UnsavedChangesDialog { self.chosen = Some(answer); } + /// What a programmatic OK answers. + fn chosen(&self) -> CloseAnswer { + let accepting = if self.scope == CloseScope::Revert { CloseAnswer::DontSave } else { CloseAnswer::Save }; + self.chosen.unwrap_or(accepting) + } + + /// Whether the "Apply to All" box shows: the guard has more documents, and the question is not a revert. + fn offers_apply_to_all(&self) -> bool { + self.remaining > 1 && self.scope != CloseScope::Revert + } + /// How many documents the guard still asks about, this one included; above one the "Apply to All" box shows. #[must_use] pub fn remaining(mut self, remaining: usize) -> Self { @@ -124,7 +136,7 @@ impl UnsavedChangesDialog { let replies: Vec = replies.into_iter().map(|(_, reply)| reply).collect(); let mut prompt = Prompt::new(words.unsaved_title.clone(), message).answers(buttons(&env, replies)); let mut ticked = hosted && self.apply_to_all; - if self.remaining > 1 && self.scope != CloseScope::Revert { + if self.offers_apply_to_all() { let label = words.unsaved_apply_to_all.clone(); let tick = &mut ticked; let mut value = hosted.then_some(&mut self.apply_to_all); @@ -163,7 +175,40 @@ impl StackDialog for UnsavedChangesDialog { /// The answer set with `set_answer`; the accepting answer's (Save, or Don't Save when reverting) unless set. fn confirm(&mut self, _: &Context) -> Option { - let accepting = if self.scope == CloseScope::Revert { CloseAnswer::DontSave } else { CloseAnswer::Save }; - Some(self.answer(self.chosen.unwrap_or(accepting))) + Some(self.answer(self.chosen())) + } + + /// `choice` (`save`, `dontSave` or `cancel`), the answer a programmatic OK gives, and `applyToAll` while the + /// guard has more documents. + fn json_fields(&self) -> Option { + let choice = match self.chosen() { + CloseAnswer::Save => "save", + CloseAnswer::DontSave => "dontSave", + CloseAnswer::Cancel => "cancel", + }; + let mut fields = json!({ "choice": choice }); + if self.offers_apply_to_all() { + fields["applyToAll"] = Value::Bool(self.apply_to_all); + } + Some(fields) + } + + fn set_json_field(&mut self, field: &str, value: Value) -> Result<(), String> { + match field { + "choice" => self.set_answer(match value.as_str() { + Some("save") if self.scope != CloseScope::Revert => CloseAnswer::Save, + Some("dontSave") => CloseAnswer::DontSave, + Some("cancel") => CloseAnswer::Cancel, + _ => { + return Err(format!( + "`choice` takes {}", + if self.scope == CloseScope::Revert { "dontSave or cancel" } else { "save, dontSave or cancel" } + )); + } + }), + "applyToAll" if self.offers_apply_to_all() => self.apply_to_all = value.as_bool().ok_or("`applyToAll` takes true or false")?, + _ => return Err(format!("unknown field `{field}`")), + } + Ok(()) } } diff --git a/crates/ui-patterns/Cargo.toml b/crates/ui-patterns/Cargo.toml index 23deea113..24a1fcbf5 100644 --- a/crates/ui-patterns/Cargo.toml +++ b/crates/ui-patterns/Cargo.toml @@ -29,6 +29,7 @@ egui = { workspace = true } craft-host = { workspace = true } craft-i18n = { workspace = true, features = ["collate"] } serde = { workspace = true } +serde_json = { workspace = true } # `patterns::preferences::SettingsDocument` turns an app's settings struct into a draft table and back; `toml_edit` gives # the struct's field order, which a `toml::Table` sorts away. toml = { version = "1.1", default-features = false, features = ["std", "parse", "serde"] } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs index 06353c005..0cd3d23db 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs @@ -6,7 +6,7 @@ use crate::runtime::requests::{ColorRequest, HostAnswer, PathRequest}; use super::form::FormDialog; use super::host_requests::HostRequests; -use super::param::{Param, ParamKind, open_fields, set_color_field}; +use super::param::{Param, ParamKind, fill_defaults, open_fields, set_color_field}; use super::preview::{PreviewPane, PreviewView, PreviewZoom}; use super::rows::{ParamRows, ParamRowsOutput}; @@ -27,7 +27,8 @@ use crate::runtime::words::CommonWords; use crate::sections::{DialogRole, FooterButton}; use egui::load::SizedTexture; -use egui::{Response, Ui}; +use egui::{Context, Response, Ui}; +use serde_json::Value; use std::borrow::Cow; use std::cell::Cell; @@ -686,4 +687,36 @@ impl StackDialog for HostedParamDialog { fn instance(&self) -> Option { self.instance } + + /// Answers OK as the button does: none while OK is disabled. The result keeps what a remembering dialog saves. + fn confirm(&mut self, _: &Context) -> Option { + let ParamDialog { key, params, remember, ok_enabled, .. } = (self.build)(&mut self.fields); + if !ok_enabled { + return None; + } + let params = params.into_owned(); + fill_defaults(¶ms, &mut self.fields); + let fields = self.fields.clone(); + let remember = remember.map(|save| (save, ParamDialog::remembered(¶ms, &fields))); + Some(ParamResult { key, fields, remember }) + } + + /// The values by parameter key, as [`DialogFields`] serializes them. + fn json_fields(&self) -> Option { + serde_json::to_value(&self.fields).ok() + } + + /// Keeps `value` when a parameter row (or its unit choice) takes it, as [`Param::accepts`] says. + fn set_json_field(&mut self, field: &str, value: Value) -> Result<(), String> { + let params = (self.build)(&mut self.fields).params.into_owned(); + let parsed: FieldValue = serde_json::from_value(value.clone()).map_err(|error| format!("`{field}`: {error}"))?; + if params.iter().any(|param| param.accepts(field, &parsed)) { + self.fields.set(field, parsed); + Ok(()) + } else if params.iter().any(|param| param.key == field || param.unit_key() == Some(field)) { + Err(format!("`{field}` can't take {value}")) + } else { + Err(format!("unknown field `{field}`")) + } + } } diff --git a/docs/ui-dialogs.md b/docs/ui-dialogs.md index 7627a5f1c..fbfc6f1e4 100644 --- a/docs/ui-dialogs.md +++ b/docs/ui-dialogs.md @@ -82,6 +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(id, field, value)` sets one as the user would (a prompt's answer is its `choice` field); `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. - `take_keyed` returns the result with `StackDialog::key`, so a Cancel still names the command it answers. - 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.