diff --git a/crates/automation/tests/it/dialogs.rs b/crates/automation/tests/it/dialogs.rs index fdf7b2530..d1ccd0e21 100644 --- a/crates/automation/tests/it/dialogs.rs +++ b/crates/automation/tests/it/dialogs.rs @@ -18,13 +18,13 @@ fn call(host: &mut DialogHost, ctx: &Context, method: &str, params: Value) -> Re 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| { + host.open(HostedParamDialog::new(&ctx, "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})); + assert_eq!(listed[0]["fields"], json!({"radius": 1.0, "method": "spin"}), "the dialog lists its defaults from its open"); 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)); @@ -72,14 +72,14 @@ fn dialog_methods_read_set_and_answer_typed_dialogs() { const REMEMBERED: SaveKey = SaveKey::new("craft_automation.blur"); /// A hosted parameter dialog's automation follows its rows as a user meets them: OK is refused while disabled, a -/// disabled row takes no value, a value is read as its row's kind (three integers for a three-cell grid), and OK -/// before the first pass answers with the remembered values the first pass would have loaded. +/// disabled row takes no value, a value is read as its row's kind (three integers for a three-cell grid), and from its +/// open, before any pass, the dialog lists and answers with the remembered values over the defaults. #[trial] fn param_dialog_automation_follows_its_rows() { let ctx = Context::default(); let mut host = DialogHost::new(); let blur = |ok: bool| { - HostedParamDialog::new("blur", DialogFields::new(), move |fields| { + HostedParamDialog::new(&ctx, "blur", DialogFields::new(), move |fields| { let mut params = Param::parse_list(r#"{"radius":0.1..1000=1,"method":"spin|zoom"}"#); params.push(Param::new("amount", "Amount", ParamKind::range(0.0, 100.0, 10.0, Default::default())).enabled_when("method", "zoom")); params.push(Param::new("cells", "Cells", ParamKind::grid(3, 0))); @@ -109,7 +109,10 @@ fn param_dialog_automation_follows_its_rows() { result.remember(&ctx); host.open(blur(true)); - let id = inspect(&host)[0]["id"].clone(); + let listed = inspect(&host); + let id = listed[0]["id"].clone(); + let fields = &listed[0]["fields"]; + assert_eq!((fields["radius"].as_f64(), &fields["method"], &fields["cells"]), (Some(7.0), &json!("zoom"), &json!([0, 1, 0])), "{fields}"); assert_eq!(call(&mut host, &ctx, "ui.dialog.confirm", json!({"dialog": id})), Ok(Value::Null)); let Some(DialogResult::Ok(reopened)) = host.take::() else { panic!("the reopened dialog answers OK") }; assert_eq!((reopened.fields.number("radius"), reopened.fields.text("method")), (Some(7.0), Some("zoom"))); diff --git a/crates/ui-gallery/src/mock/editor.rs b/crates/ui-gallery/src/mock/editor.rs index 9ae34a743..e8e7cb78c 100644 --- a/crates/ui-gallery/src/mock/editor.rs +++ b/crates/ui-gallery/src/mock/editor.rs @@ -148,7 +148,7 @@ fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, state: &mut MockState) { for command in dialogs { match command { AppCommand::GaussianBlur => { - host.open(HostedParamDialog::new(BLUR_KEY, DialogFields::new(), |fields| { + host.open(HostedParamDialog::new(ui.ctx(), BLUR_KEY, DialogFields::new(), |fields| { ParamDialog::new(BLUR_KEY, "Gaussian Blur", Param::parse_list(BLUR)).values(Bind::bound(fields)).remember(BLUR_MEMORY) })); } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs index 7720037ce..11848b282 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs @@ -741,7 +741,7 @@ type Build = dyn for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send; /// [`answer_ok`](HostedParamDialog::answer_ok). /// /// ```ignore -/// host.open(HostedParamDialog::new("radial-blur", DialogFields::new(), |fields| { +/// host.open(HostedParamDialog::new(ctx, "radial-blur", DialogFields::new(), |fields| { /// ParamDialog::new("radial-blur", "Radial Blur", params.clone()).values(Bind::bound(fields)) /// })); /// // each pass: if dialog.is_previewing() { dialog.set_preview(Some(render(dialog.fields()))) } @@ -751,8 +751,6 @@ pub struct HostedParamDialog { key: String, instance: Option, fields: DialogFields, - /// The values were opened (remembered values and defaults loaded) by the first show, OK or set. - opened: bool, build: Box, requests: HostRequests, /// Whether the dialog is open: bound to the dialog's `opened` prop, so the dialog's own open state, kept under @@ -799,20 +797,26 @@ struct Refused { } impl HostedParamDialog { - /// A hosted dialog for the command `key`, opening with `fields`; `build` makes the dialog over the values. + /// A hosted dialog for the command `key`, opening with `fields`; `build` makes the dialog over the values. The + /// values open now, as a `ParamDialog`'s first pass opens its own: the remembered values `ctx` keeps over + /// `fields`, then the defaults of the keys still missing. Automation reads and sets these values before any pass. pub fn new( + ctx: &Context, key: impl Into, - fields: DialogFields, + mut fields: DialogFields, build: impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static, ) -> Self { let key = key.into(); + let ParamDialog { params, remember, patterns, .. } = build(&mut fields); + let (params, patterns) = (params.into_owned(), patterns.into_owned()); + let saved = remember.and_then(|key| MemoryStage::peek_saved::>(ctx, &key)); + ParamDialog::open_values(¶ms, &patterns, saved.as_ref(), &mut fields); HostedParamDialog { id: dialog_id(key.as_str()), key, instance: None, + opening: fields.clone(), fields, - opened: false, - opening: DialogFields::default(), build: Box::new(build), requests: HostRequests::new(), open: true, @@ -828,11 +832,12 @@ impl HostedParamDialog { /// A hosted command form: the same as [`new`](HostedParamDialog::new), with `build` making a /// [`ParamDialog::command`]. pub fn command( + ctx: &Context, key: impl Into, fields: DialogFields, build: impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static, ) -> Self { - Self::new(key, fields, build) + Self::new(ctx, key, fields, build) } /// Names this dialog among others made with the same key (one per document, say), so they keep separate state. @@ -989,32 +994,23 @@ impl HostedParamDialog { pub fn cancel_requests(&mut self) { self.requests.cancel(); } - - /// Opens the values once, as a `ParamDialog`'s first pass does, before the first show, OK or set reads them. - fn open(&mut self, ctx: &Context) { - if std::mem::replace(&mut self.opened, true) { - return; - } - let ParamDialog { params, remember, patterns, .. } = (self.build)(&mut self.fields); - let (params, patterns) = (params.into_owned(), patterns.into_owned()); - let saved = remember.and_then(|key| MemoryStage::peek_saved::>(ctx, &key)); - ParamDialog::open_values(¶ms, &patterns, saved.as_ref(), &mut self.fields); - self.opening = self.fields.clone(); - } } /// Checks `value` against the row `field` of `params` and sets it in `fields`, as the user editing the row would; `Err` -/// says why the row refused (`FieldRefusal`). The field is a row's key or its unit key; a Files row takes a -/// `{files, folder, useFolder}` object and sets its two companion keys with it. Every dialog built on `Param`s sets -/// its fields through this one rule. +/// says why the row refused (`FieldRefusal`). The field is a row's key, its unit key or a custom row's companion key +/// ([`Param::companions`]); a Files row takes a `{files, folder, useFolder}` object and sets its two companion keys with +/// it. Every dialog built on `Param`s sets its fields through this one rule. pub fn set_param_field(params: &[Param], fields: &mut DialogFields, field: &str, value: Value) -> Result<(), String> { - let Some(param) = params.iter().find(|param| param.key == field || param.unit_key() == Some(field)) else { + let companion = |param: &Param| matches!(¶m.kind, ParamKind::Custom(row) if row.has_companion(field)); + let Some(param) = params.iter().find(|param| param.key == field || param.unit_key() == Some(field) || companion(param)) else { return Err(FieldRefusal::Unknown.message(field)); }; if !param.visible(fields) || !param.enabled(fields) { return Err(FieldRefusal::Inactive.message(field)); } - let writes = if param.key != field { + let writes = if companion(param) { + Some(vec![(field.to_owned(), Some(FieldValue::Json(value.clone())).filter(|_| !value.is_null()))]) + } else if param.key != field { value.as_str().map(|unit| vec![(field.to_owned(), Some(FieldValue::Text(unit.to_owned())))]) } else if matches!(param.kind, ParamKind::Files { .. }) { read_files(param, &value) @@ -1081,7 +1077,6 @@ impl StackDialog for HostedParamDialog { fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let measuring = crate::runtime::measure::active(ui.ctx()); let answers = if measuring { Vec::new() } else { self.requests.take_answers() }; - self.open(ui.ctx()); let finish = self.held.as_ref().is_some_and(|held| held.accepted); // A measuring run keeps the centre: the real run of the pass takes it. let centre = if measuring { self.centre } else { self.centre.take() }; @@ -1152,8 +1147,7 @@ impl StackDialog for HostedParamDialog { /// Answers OK as the button does: none while OK is disabled. The result keeps what a remembering dialog saves. A /// held dialog files the answer for the host, as its button does, and answers none; once the host accepted the /// held answer, it answers that. - fn confirm(&mut self, ctx: &Context) -> Option { - self.open(ctx); + fn confirm(&mut self, _: &Context) -> Option { if self.held.as_ref().is_some_and(|held| held.accepted) { return self.held.take().map(|held| held.result); } @@ -1181,8 +1175,7 @@ impl StackDialog for HostedParamDialog { /// Keeps `value` when the row `field` names (a parameter or its unit choice) is shown, takes input, and takes /// the value ([`set_param_field`]). - fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> { - self.open(ctx); + fn set_json_field(&mut self, _: &Context, field: &str, value: Value) -> Result<(), String> { let params = (self.build)(&mut self.fields).params.into_owned(); let before = self.fields.clone(); set_param_field(¶ms, &mut self.fields, field, value)?; diff --git a/crates/ui-patterns/src/patterns/form_dialogs/dialog/stories.rs b/crates/ui-patterns/src/patterns/form_dialogs/dialog/stories.rs index 2a67879dc..9c82e6003 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/dialog/stories.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/dialog/stories.rs @@ -85,7 +85,7 @@ const REFUSAL: &str = "The radius is too large for this layer."; fn hosted_param_dialog_with_a_refused_ok(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let ctx = ui.ctx().clone(); let open = move || { - let mut dialog = HostedParamDialog::new("blur", DialogFields::new(), |fields| { + let mut dialog = HostedParamDialog::new(&ctx, "blur", DialogFields::new(), |fields| { ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).values(Bind::bound(fields)) }) .held_ok(); diff --git a/crates/ui-patterns/src/patterns/form_dialogs/export/options.rs b/crates/ui-patterns/src/patterns/form_dialogs/export/options.rs index 2bbce2ba1..39e428fbc 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/export/options.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/export/options.rs @@ -719,14 +719,15 @@ fn jpeg_params(words: &FormatOptionsWords, options: JpegOptions) -> Vec { vec![ Param::section(words.image_options.clone()), Param::custom(QUALITY, words.quality.clone(), move |ui, fields, _| quality_rows(ui, fields, &quality_name, &preset_name, &presets, start)) + .opens_with(FieldValue::Int(i64::from(start))) .full_width(), Param::new(FORMAT, words.format_options.clone(), ParamKind::radio(formats, Some(options.format.id().to_owned()))), ] } -/// The quality in `fields`, else `start`, the quality the dialog opened with. +/// The quality in `fields`, in whatever form it was set, else `start`, the quality the dialog opened with. fn quality_of(fields: &DialogFields, start: u8) -> u8 { - fields.int(QUALITY).map_or(start, |quality| quality.clamp(0, i64::from(MAX_QUALITY)) as u8) + fields.number(QUALITY).filter(|quality| quality.is_finite()).map_or(start, |quality| quality.round().clamp(0.0, f64::from(MAX_QUALITY)) as u8) } /// The quality rows: the field named `name` and the preset list on one line, the slider across the form under them. diff --git a/crates/ui-patterns/src/patterns/form_dialogs/fields.rs b/crates/ui-patterns/src/patterns/form_dialogs/fields.rs index 4e357b16b..b5f292a88 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/fields.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/fields.rs @@ -129,10 +129,14 @@ impl DialogFields { self.values.contains_key(key) } + // The scalar readers also read the `Json` form of their value, which automation stores for a custom row's keys + // (`Param::custom`): one read whatever form the value was set in. + /// `Bool`, else `None`. pub fn bool(&self, key: &str) -> Option { match self.values.get(key)? { FieldValue::Bool(b) => Some(*b), + FieldValue::Json(value) => value.as_bool(), _ => None, } } @@ -142,15 +146,18 @@ impl DialogFields { match self.values.get(key)? { FieldValue::Number(n) => Some(*n), FieldValue::Int(i) => Some(*i as f64), + FieldValue::Json(value) => value.as_f64(), _ => None, } } /// `Int`, or a whole `Number`. pub fn int(&self, key: &str) -> Option { + let whole = |n: f64| (n.fract() == 0.0 && n.abs() < 9.0e15).then_some(n as i64); match self.values.get(key)? { FieldValue::Int(i) => Some(*i), - FieldValue::Number(n) if n.fract() == 0.0 && n.abs() < 9.0e15 => Some(*n as i64), + FieldValue::Number(n) => whole(*n), + FieldValue::Json(value) => value.as_i64().or_else(|| value.as_f64().and_then(whole)), _ => None, } } @@ -159,6 +166,7 @@ impl DialogFields { pub fn text(&self, key: &str) -> Option<&str> { match self.values.get(key)? { FieldValue::Text(s) => Some(s), + FieldValue::Json(value) => value.as_str(), _ => None, } } @@ -188,14 +196,18 @@ impl DialogFields { } /// A `List`, or a `Grid`, `Point` or `Color` as the list of its numbers (the shapes an - /// untagged read gives a stored list of numbers, and an empty list). The key may have no - /// parameter row: a host keeps its own data under it (a key without a row is not remembered). + /// untagged read gives a stored list of numbers, and an empty list), or a `Json` array read as + /// those values. The key may have no parameter row: a host keeps its own data under it (a key + /// without a row is not remembered). pub fn list(&self, key: &str) -> Option> { Some(match self.values.get(key)? { FieldValue::List(items) => Cow::Borrowed(items.as_slice()), FieldValue::Grid(cells) => Cow::Owned(cells.iter().map(|c| FieldValue::Int(*c)).collect()), FieldValue::Point(p) => Cow::Owned(p.iter().map(|n| FieldValue::Number(*n)).collect()), FieldValue::Color(c) => Cow::Owned(c.iter().map(|n| FieldValue::Number(f64::from(*n))).collect()), + FieldValue::Json(serde_json::Value::Array(items)) => { + Cow::Owned(items.iter().map(|item| serde_json::from_value(item.clone())).collect::>().ok()?) + } _ => return None, }) } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/param.rs b/crates/ui-patterns/src/patterns/form_dialogs/param.rs index 784fa1e3d..c5fb60702 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/param.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/param.rs @@ -145,7 +145,7 @@ pub enum ParamKind { /// The text shown; line breaks start new lines. text: Label, }, - /// A row the host draws: see [`Param::custom`]. It has no value of its own. + /// A row the host draws: see [`Param::custom`]. Its value and its companions' are what `draw` keeps. Custom(CustomRow), /// A select of blend modes, each with the Shift+Alt key that picks it. #[non_exhaustive] @@ -288,7 +288,8 @@ impl ParamKind { } ParamKind::Pattern { default } => FieldValue::Text(default.clone()?), ParamKind::Files { open_files, .. } => path_list(open_files), - ParamKind::ReadOnlyText { .. } | ParamKind::Custom(_) | ParamKind::Section => return None, + ParamKind::Custom(row) => row.opens_with.clone()?, + ParamKind::ReadOnlyText { .. } | ParamKind::Section => return None, }) } @@ -316,7 +317,8 @@ impl ParamKind { (ParamKind::Channel { names, .. }, FieldValue::Int(i)) => usize::try_from(*i).is_ok_and(|i| i < names.len()), (ParamKind::Text { .. }, FieldValue::Text(_)) => true, (ParamKind::OptionalNumber { min, max, .. }, v) => number(v).is_some_and(|n| n.is_finite() && n >= *min && n <= *max), - (ParamKind::Custom(_), FieldValue::Json(_)) => true, + // A custom row keeps whatever its `draw` writes. + (ParamKind::Custom(_), _) => true, (ParamKind::Blend { modes, .. }, FieldValue::Text(id)) => modes.iter().any(|(entry, _)| entry.key == *id), (ParamKind::Pattern { .. }, FieldValue::Text(_)) => true, (ParamKind::Files { .. }, v) => is_path_list(v), @@ -328,31 +330,43 @@ impl ParamKind { type CustomDraw = dyn Fn(&mut Ui, &mut DialogFields, &mut CustomContext) -> Response + Send + Sync; /// What draws a [`ParamKind::Custom`] row: it gets the row's control cell, the form's values and the row's -/// [`CustomContext`], and returns the response the row label names. Equal only to itself. +/// [`CustomContext`], and returns the response the row label names. Besides the row's own key, `draw` may keep values +/// under its companion keys ([`Param::companions`]). Equal only to a clone of itself with the same value and companions. #[derive(Clone)] -pub struct CustomRow(Arc); +pub struct CustomRow { + draw: Arc, + /// The value the row's key opens with ([`Param::opens_with`]). + opens_with: Option, + /// The other keys `draw` keeps values under. + companions: Vec, +} impl CustomRow { /// Wraps `draw`, which draws the row and edits the values it owns through the [`DialogFields`]. pub fn new(draw: impl Fn(&mut Ui, &mut DialogFields, &mut CustomContext) -> Response + Send + Sync + 'static) -> Self { - Self(Arc::new(draw)) + Self { draw: Arc::new(draw), opens_with: None, companions: Vec::new() } } /// Draws the row. pub(crate) fn draw(&self, ui: &mut Ui, fields: &mut DialogFields, context: &mut CustomContext) -> Response { - (self.0)(ui, fields, context) + (self.draw)(ui, fields, context) + } + + /// Whether `key` is one of the row's companion keys. + pub(crate) fn has_companion(&self, key: &str) -> bool { + self.companions.iter().any(|companion| companion == key) } } impl fmt::Debug for CustomRow { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str("CustomRow") + f.debug_struct("CustomRow").field("opens_with", &self.opens_with).field("companions", &self.companions).finish_non_exhaustive() } } impl PartialEq for CustomRow { fn eq(&self, other: &Self) -> bool { - Arc::ptr_eq(&self.0, &other.0) + Arc::ptr_eq(&self.draw, &other.draw) && self.opens_with == other.opens_with && self.companions == other.companions } } @@ -591,8 +605,10 @@ impl Param { } /// A row the host draws. `draw` gets the control cell, the form's values and the row's [`CustomContext`] (to ask - /// for the host's colour picker); the row label names the response it returns. The row has no default and - /// nothing remembered; `draw` reads and writes [`DialogFields`] under whatever keys it likes. + /// for the host's colour picker); the row label names the response it returns. Nothing of the row is remembered; + /// it opens with no value unless [`opens_with`](Param::opens_with) gives one. `draw` reads and writes the + /// [`DialogFields`] under its key and the keys [`companions`](Param::companions) declares; automation + /// (`set_json_field`) sets any of those keys to a JSON value, kept as [`FieldValue::Json`] (`null` removes it). pub fn custom( key: impl Into, label: impl Into