diff --git a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs
index 4d1544c67..266e09f4e 100644
--- a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs
+++ b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs
@@ -2,7 +2,7 @@
//! owned by a `DialogHost`. A command form is a `ParamDialog` without a preview.
use super::fields::{DialogFields, FieldValue};
-use crate::patterns::presets::PresetRow;
+use crate::patterns::presets::{PresetKind, PresetRow};
use crate::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer, ListingRequest, PathRequest};
use super::form::{FormDialog, FormDialogWords};
@@ -12,20 +12,24 @@ use super::preview::{PreviewPane, PreviewView, PreviewZoom};
use super::rows::{ParamRows, ParamRowsOutput};
-use crate::contract::{Bind, BodyCx, NoValue, Outcome, Remember as _, SaveKey, Show as _, ShowContainer as _};
+use crate::contract::{Bind, BodyCx, NoValue, Outcome, Remember as _, Sampler as _, SaveKey, Show as _, ShowContainer as _};
-use crate::dialog::{Dialog, DialogId, DialogResult, DialogStack, FooterHooks, StackDialog, dialog_id};
+use crate::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, FooterHooks, StackDialog, dialog_id};
+use crate::display::{Shade, Text};
use crate::layout_components::{Row, Stack};
+use crate::notices::{Notice, NoticeLayout};
use crate::runtime::env::{Env, Label};
-use crate::runtime::memory::{MemoryStage, unique};
+use crate::runtime::memory::MemoryStage;
use crate::runtime::overlay::CloseReason;
use crate::runtime::words::CommonWords;
use crate::sections::{DialogRole, FooterButton};
+use craft_theme::Srgba;
+use craft_theme::variant::Tone;
use egui::load::SizedTexture;
use egui::{Context, Pos2, Response, Ui};
use serde_json::Value;
@@ -61,8 +65,8 @@ pub struct ParamResult {
pub key: String,
/// The values the user confirmed, keyed by parameter.
pub fields: DialogFields,
- /// The id of the dialog that filed the result, instance ids included; set by `HostedParamDialog`.
- // P3(dialogs-w1): dl.K20 `ParamResult::id`
+ /// The id of the dialog that filed the result, instance ids included, so a family's step names the dialog that
+ /// answered. `HostedParamDialog` sets it; a `ParamDialog` shown on its own has no host id and leaves `Id::NULL`.
pub id: DialogId,
remember: Option<(SaveKey, DialogFields)>,
}
@@ -72,9 +76,7 @@ impl ParamResult {
/// its command succeeds, so a failed command leaves the previous values; without a remember key it does nothing.
pub fn remember(&self, ctx: &Context) {
if let Some((key, values)) = &self.remember {
- let mut stage = MemoryStage::open(ctx, unique(("craft_ui::param_result", key.as_str())));
- *stage.saved::>(key) = Some(values.clone());
- stage.write_back();
+ crate::runtime::memory::set_saved_value:: >(ctx, key, Some(values.clone()));
}
}
}
@@ -111,6 +113,10 @@ pub struct ParamDialogOutput {
pub preview_click: Option,
/// The id of the extra footer button pressed this pass (`ParamDialog::extra_buttons`).
pub footer_action: Option,
+ /// The answer OK would have given, the pass OK was pressed on a dialog that holds its OK for the host.
+ pub(crate) held: Option,
+ /// The picture point at the centre of the view the preview pane drew this pass; `None` without a preview.
+ pub(crate) preview_centre: Option,
}
impl Outcome for ParamDialogOutput {
@@ -122,7 +128,7 @@ impl Outcome for ParamDialogOutput {
}
/// A dialog from a parameter list: one row per [`Param`], the Preview check box with a preview pane when the host
-/// gives a picture, and OK, Cancel and a footer extra.
+/// gives a picture, and OK, Cancel, extra buttons and a footer note.
///
/// - Keys: Tab walks the fields, Enter is OK unless a field owns it, Escape cancels. Holding Alt turns Cancel into
/// Reset, which restores the values from when the dialog opened (or `reset_to`) and keeps the dialog open.
@@ -131,7 +137,9 @@ impl Outcome for ParamDialogOutput {
/// - Preview: the host renders from the reported values while `preview_on` and hands the picture to `preview`, the
/// unfiltered one while `comparing` (the Preview check box held down). Drag pans the picture, the zoom buttons
/// scale it. A dialog with a preview has its buttons in a column beside the body, with the Preview check box and
-/// the footer extra under them.
+/// the footer note under them.
+/// - Footer: [`extra_buttons`](ParamDialog::extra_buttons) keep the dialog open and come back as
+/// `ParamDialogOutput::footer_action`; [`footer_note`](ParamDialog::footer_note) is a muted line at the start edge.
/// - A command form is a dialog with no preview and no remember key.
#[must_use = "show the dialog with `show`"]
#[derive(crate::contract::Pattern, crate::contract::Props)]
@@ -189,18 +197,19 @@ pub struct ParamDialog<'a> {
/// preview clicks pick a colour turns it off. The default is true.
#[prop]
click_centres: bool,
- /// The canvas the rows' droppers sample (`ParamRows::canvas`).
+ /// The canvas the rows' droppers sample (`ParamRows::canvas`). While the dialog shows, its view stays usable under
+ /// the modal layer (`Sampler::keep_view_open`).
#[prop]
canvas: Option,
- /// Extra footer buttons, each an id and a label; a press comes back as `ParamDialogOutput::footer_action`.
+ /// Extra footer buttons after OK and Cancel (Color Table's Load… and Save…), each an id and a label. They keep the
+ /// dialog open; a press comes back as `ParamDialogOutput::footer_action`.
#[prop]
extra_buttons: Vec<(String, Label)>,
/// The patterns the dialog's [`ParamKind::Pattern`] rows offer.
#[prop]
patterns: Cow<'a, [PresetRow]>,
- /// Controls before the buttons in the footer (Color Table's Load and Save).
- #[prop(func = "FnMut(&mut Ui)")]
- footer_extra: Option>,
+ /// A muted line at the footer's start edge (JPEG Options' size estimate).
+ footer_note: Option,
/// A section under the rows that only reads the values (a monitor note).
#[prop(func = "Fn(&mut Ui, &DialogFields)")]
below: Option>,
@@ -208,23 +217,25 @@ pub struct ParamDialog<'a> {
/// The host's answers to the requests of earlier passes; the dialog writes them into its values first.
#[prop]
answers: Vec,
- /// The bound values were opened already ([`HostedParamDialog`] opens its own): the first pass leaves them.
- values_opened: bool,
+ /// The values a [`HostedParamDialog`] opened before the first pass: the first pass leaves them and Reset restores
+ /// them.
+ values_opened: Option,
+ /// OK keeps the dialog open and reports its answer in `ParamDialogOutput::held` ([`HostedParamDialog::held_ok`]).
+ hold: bool,
+ /// The host accepted the held OK: this pass closes the dialog as OK.
+ finish_held: bool,
+ /// Why the host refused the held OK, and the values it refused: the notice under the rows shows while the values
+ /// are those.
+ refusal: Option<(Label, DialogFields)>,
+ /// The picture point this pass centres the preview pane's view on ([`HostedParamDialog::centre_preview`]).
+ centre: Option,
+ /// The colours a child picker previews in the colour rows, by row key ([`HostedParamDialog::preview_color`]).
+ preview_colors: Vec<(String, Srgba)>,
}
/// What `ParamDialog::shaped` applies to the built [`Dialog`].
struct Shaped<'a>(Box) -> Dialog<'a> + 'a>);
-/// What `ParamDialog::footer_extra` draws before the buttons.
-pub struct FooterExtra<'a>(Box);
-
-impl<'a> FooterExtra<'a> {
- /// The extra that runs `add`.
- pub fn new(add: impl FnMut(&mut Ui) + 'a) -> Self {
- FooterExtra(Box::new(add))
- }
-}
-
type BelowRowsFn<'a> = Box;
/// What `ParamDialog::below` draws under the rows.
@@ -263,11 +274,16 @@ impl<'a> ParamDialog<'a> {
canvas: None,
extra_buttons: Vec::new(),
patterns: Cow::Borrowed(&[]),
- footer_extra: None,
+ footer_note: None,
below: None,
shaped: None,
answers: Vec::new(),
- values_opened: false,
+ values_opened: None,
+ hold: false,
+ finish_held: false,
+ refusal: None,
+ centre: None,
+ preview_colors: Vec::new(),
}
}
@@ -278,31 +294,69 @@ impl<'a> ParamDialog<'a> {
self
}
- /// Marks the bound values as opened by the host, so the first pass doesn't open them again.
- fn values_opened(mut self) -> Self {
- self.values_opened = true;
+ /// Marks the bound values as opened by the host with `opening`, so the first pass doesn't open them again and
+ /// Reset restores `opening`.
+ pub(crate) fn values_opened(mut self, opening: DialogFields) -> Self {
+ self.values_opened = Some(opening);
+ self
+ }
+
+ /// Makes OK keep the dialog open and report its answer in `ParamDialogOutput::held`.
+ fn hold_ok(mut self, on: bool) -> Self {
+ self.hold = on;
+ self
+ }
+
+ /// Closes the dialog as OK in this pass: the host accepted the held answer.
+ fn finish_held(mut self, on: bool) -> Self {
+ self.finish_held = on;
+ self
+ }
+
+ /// Shows `reason` under the rows while the values are `refused`.
+ fn refusal(mut self, refusal: Option<(Label, DialogFields)>) -> Self {
+ self.refusal = refusal;
+ self
+ }
+
+ /// Centres the preview pane's view on the picture point `point` in this pass; without a picture it does nothing.
+ fn centre_on(mut self, point: Option) -> Self {
+ self.centre = point;
+ self
+ }
+
+ /// The colours the colour rows show in place of their values in this pass, by row key.
+ fn preview_colors(mut self, colors: Vec<(String, Srgba)>) -> Self {
+ self.preview_colors = colors;
self
}
/// The answer OK gives with `fields`: with `remember`, it keeps the part of them the dialog saves.
fn result(key: String, params: &[Param], remember: Option, fields: DialogFields) -> ParamResult {
let remember = remember.map(|save| (save, Self::remembered(params, &fields)));
- ParamResult { key, fields, remember, id: DialogId::NULL } // P3(dialogs-w1): dl.K20, the hosted dialog sets its id
+ ParamResult { key, fields, remember, id: DialogId::NULL }
}
/// Opens `values` for `params`: the `saved` values a remembering dialog keeps over them, then the defaults of
- /// the keys still missing, then the snapshot Reset restores.
- fn open_values(params: &[Param], saved: Option<&DialogFields>, values: &mut DialogFields) {
+ /// the keys still missing, then the snapshot Reset restores. A saved pattern that is not among `patterns` any more
+ /// is left out, so its row starts at its default.
+ fn open_values(params: &[Param], patterns: &[PresetRow], saved: Option<&DialogFields>, values: &mut DialogFields) {
if let Some(saved) = saved {
+ let offered = |value: &FieldValue| matches!(value, FieldValue::Text(id) if patterns.iter().any(|row| row.kind == PresetKind::Item && row.key == *id));
+ let pattern_row = |name: &str| params.iter().any(|param| param.key == name && matches!(param.kind, ParamKind::Pattern { .. }));
for (name, value) in Self::remembered(params, saved).iter() {
- values.set(name, value.clone());
+ if !pattern_row(name) || offered(value) {
+ values.set(name, value.clone());
+ }
}
}
open_fields(params, values);
}
- /// The part of `fields` a remembering dialog saves: numbers, angles, choices and check boxes of the remembered
- /// rows and their unit choices; colours, grids, points, channels and free text start from their defaults.
+ /// The part of `fields` a remembering dialog saves: numbers, angles, choices, check boxes, colours, blend modes and
+ /// patterns of the remembered rows and their unit choices; grids, points, channels, free text, files and custom
+ /// rows start from their defaults. A colour row whose default follows the document opts out with
+ /// [`Param::not_remembered`].
pub fn remembered(params: &[Param], fields: &DialogFields) -> DialogFields {
let kept = |param: &Param| {
param.is_remembered()
@@ -315,6 +369,9 @@ impl<'a> ParamDialog<'a> {
| ParamKind::Bool { .. }
| ParamKind::Choice { .. }
| ParamKind::Radio { .. }
+ | ParamKind::Color { .. }
+ | ParamKind::Blend { .. }
+ | ParamKind::Pattern { .. }
)
};
let units = params.iter().filter(|param| param.is_remembered()).filter_map(Param::unit_key);
@@ -356,14 +413,20 @@ impl<'a> ParamDialog<'a> {
canvas,
extra_buttons,
patterns,
- footer_extra,
+ footer_note,
below,
shaped,
answers,
values_opened,
+ hold,
+ finish_held,
+ refusal,
+ centre,
+ preview_colors,
} = self;
- let _ = (&canvas, &extra_buttons, &patterns); // P3(dialogs-w1): dl.K21, dl.K22, dl.K28
let preview_label = Env::of(ui).words::().preview.clone();
+ // The footer `FormDialog` builds for this pass, made the same way, so its `pick` reads `FormOutput::picked`.
+ let footer = ResetFooter::new(ui, cancel_label.clone(), alt_resets);
let mut form = match bound {
Some(bind) => FormDialog::new(title.clone(), bind),
@@ -376,6 +439,7 @@ impl<'a> ParamDialog<'a> {
.history(history)
.collection_body(collection_body)
.closable(closable)
+ .accept_stays_open(hold)
.answers(answers)
.reset_with(move |current, opened| {
let mut values = current.clone();
@@ -393,14 +457,23 @@ impl<'a> ParamDialog<'a> {
if let Some(label) = cancel_label {
form = form.cancel_label(label);
}
+ let host_opened = values_opened.is_some();
+ if let Some(opening) = values_opened {
+ form = form.opening(opening);
+ }
if let Some(open) = open {
form = form.opened(open);
}
if preview.is_some() {
form = form.preview(None);
}
- if let Some(FooterExtra(extra)) = footer_extra {
- form = form.footer_extra(extra);
+ if !extra_buttons.is_empty() {
+ form = form.extra_buttons(extra_buttons.iter().map(|(_, label)| FooterButton::new(label.clone(), DialogRole::Other)));
+ }
+ if let Some(note) = footer_note {
+ form = form.footer_extra(move |ui| {
+ Text::new(note.clone()).shade(Shade::Muted).show(ui);
+ });
}
if let Some(Shaped(shape)) = shaped {
form = form.shaped(shape);
@@ -408,46 +481,81 @@ impl<'a> ParamDialog<'a> {
let mut live = Live::default();
let mut rows = None;
- let mut preview_click = None;
+ let mut shown_preview = ShownPreview::default();
+ let mut latest = None::;
let shown = form.show(ui, |ui, cx, values| {
- if cx.first() && !values_opened {
+ if cx.first() && !host_opened {
let saved = remember.as_ref().and_then(|key| cx.saved::>(key).clone());
- Self::open_values(¶ms, saved.as_ref(), values);
+ Self::open_values(¶ms, &patterns, saved.as_ref(), values);
}
for answer in cx.take_answers() {
match answer {
HostAnswer::Color { key, color } | HostAnswer::Eyedropper { key, color } => set_color_field(¶ms, values, &key, color),
HostAnswer::Path { key, path } => values.set(&key, FieldValue::Text(path.to_string_lossy().into_owned())),
- HostAnswer::Listing { .. } => {} // P3(dialogs-w1): dl.K26
+ HostAnswer::Listing { key, files } => {
+ let files = files.into_iter().map(|file| FieldValue::Text(file.to_string_lossy().into_owned())).collect();
+ if let Some(param) = params.iter().find(|param| param.key == key) {
+ values.set(param.folder_files_key(), FieldValue::List(files));
+ }
+ }
}
}
+ if let Some(canvas) = canvas {
+ cx.keep_view_open(canvas);
+ }
+ // A measuring run closes nothing: the real run of the same pass makes the close.
+ if finish_held && !crate::runtime::measure::active(ui.ctx()) {
+ cx.request_close_as(CloseReason::Activated);
+ }
live = cx.memory::().clone();
+ if let (Some(point), Some(texture)) = (centre, &preview) {
+ live.view = live.view.centred_on(point, texture.size);
+ }
let mut show_rows = |ui: &mut Ui, values: &mut DialogFields| {
- rows = Some(ParamRows::new(title.clone(), ¶ms, Bind::bound(values)).show(ui));
+ let mut shown = ParamRows::new(title.clone(), ¶ms, Bind::bound(values)).patterns(&patterns).preview_colors(&preview_colors);
+ if let Some(canvas) = canvas {
+ shown = shown.canvas(canvas);
+ }
+ rows = Some(shown.show(ui));
};
match (&preview, layout) {
(Some(texture), ParamLayout::Beside) => {
Row::new().show(ui, |ui, _| {
show_rows(ui, values);
- Stack::new().show(ui, |ui, _| preview_click = show_preview(ui, &preview_label, texture, click_centres, &mut live));
+ Stack::new().show(ui, |ui, _| shown_preview = show_preview(ui, &preview_label, texture, click_centres, &mut live));
});
}
(Some(texture), ParamLayout::Below) => {
Stack::new().show(ui, |ui, _| {
show_rows(ui, values);
- preview_click = show_preview(ui, &preview_label, texture, click_centres, &mut live);
+ shown_preview = show_preview(ui, &preview_label, texture, click_centres, &mut live);
});
}
(None, _) => show_rows(ui, values),
}
+ // The host's refusal of the held OK stays until a value changes.
+ if let Some((reason, _)) = refusal.as_ref().filter(|(_, refused)| *refused == *values) {
+ Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui);
+ }
if let Some(BelowRows(draw)) = &below {
draw(ui, values);
}
*cx.memory::() = live.clone();
+ latest = Some(values.clone());
true
});
- let result = shown.accepted.map(|fields| Self::result(key, ¶ms, remember, fields));
+ // `picked` is this pass's press: a second pass of the frame has none, so a press is reported once.
+ let pick = footer.pick(shown.picked);
+ let footer_action = match pick {
+ Some(ResetPick::Extra(at)) => extra_buttons.get(at).map(|(id, _)| id.clone()),
+ _ => None,
+ };
+ let (result, held) = match (shown.accepted, pick, latest) {
+ (Some(fields), _, _) => (Some(Self::result(key, ¶ms, remember, fields)), None),
+ (None, Some(ResetPick::Accept), Some(fields)) if hold => (None, Some(Self::result(key, ¶ms, remember, fields))),
+ _ => (None, None),
+ };
ParamDialogOutput {
response: shown.response,
closed: shown.closed,
@@ -456,16 +564,17 @@ impl<'a> ParamDialog<'a> {
values: shown.value,
preview_on: shown.preview_on,
comparing: shown.comparing,
- preview_click,
- footer_action: None, // P3(dialogs-w1): dl.K22, from `FormOutput::picked`
+ preview_click: shown_preview.clicked,
+ footer_action,
+ held,
+ preview_centre: shown_preview.centre,
}
}
- /// A note in the footer, left of the buttons (a file size estimate, say).
- #[allow(dead_code)] // P3(dialogs-w1): dl.K23
+ /// A muted line at the footer's start edge, left of the buttons (a file size estimate, say).
pub fn footer_note(mut self, note: impl Into) -> Self {
- let _ = (&mut self, note.into());
- todo!("dl.K23")
+ self.footer_note = Some(note.into());
+ self
}
}
@@ -599,12 +708,22 @@ impl ResetFooter {
}
}
-/// The zoom row and the pane; returns the picture point a click landed on.
-fn show_preview(ui: &mut Ui, label: &Label, texture: &SizedTexture, click_centres: bool, live: &mut Live) -> Option {
+/// What the preview pane reported in a pass.
+#[derive(Clone, Copy, Default)]
+struct ShownPreview {
+ /// The picture point a click landed on.
+ clicked: Option,
+ /// The picture point at the centre of the view the pane drew.
+ centre: Option,
+}
+
+/// The zoom row and the pane.
+fn show_preview(ui: &mut Ui, label: &Label, texture: &SizedTexture, click_centres: bool, live: &mut Live) -> ShownPreview {
let zoom = PreviewZoom::new(&live.view).show(ui);
let pane = PreviewPane::new(label.clone(), *texture, &live.view).click_centres(click_centres).show(ui);
+ let centre = pane.shown.centre(texture.size);
live.view = zoom.view.or(pane.view).unwrap_or(pane.shown);
- pane.clicked
+ ShownPreview { clicked: pane.clicked, centre: Some(centre) }
}
/// Builds the dialog over the host-owned values of a [`HostedParamDialog`] for one pass.
@@ -613,10 +732,19 @@ type Build = dyn for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send;
/// A [`ParamDialog`] the [`DialogHost`](crate::dialog::DialogHost) owns: the host keeps the values, and `build` makes
/// the dialog over them each pass.
///
+/// - The host keeps the dialog's open state, so a dialog opened again under the same key opens.
+/// - The preview picture comes from [`set_preview`](HostedParamDialog::set_preview) between passes, since `build` cannot
+/// capture a picture that changes; [`is_previewing`](HostedParamDialog::is_previewing) and
+/// [`is_comparing`](HostedParamDialog::is_comparing) say what to render.
+/// - With [`held_ok`](HostedParamDialog::held_ok), OK files its answer for the host to check
+/// ([`take_ok`](HostedParamDialog::take_ok)) and the dialog waits, OK disabled, for
+/// [`answer_ok`](HostedParamDialog::answer_ok).
+///
/// ```ignore
/// host.open(HostedParamDialog::new("radial-blur", DialogFields::new(), |fields| {
-/// ParamDialog::new("radial-blur", "Radial Blur", params.clone()).values(Bind::bound(fields)).preview(texture)
+/// 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()))) }
/// ```
pub struct HostedParamDialog {
id: DialogId,
@@ -627,32 +755,47 @@ pub struct HostedParamDialog {
opened: bool,
build: Box,
requests: HostRequests,
- /// Whether the dialog is open: bound to the dialog's `opened` prop.
- #[allow(dead_code)] // P3(dialogs-w1): dl.K17
+ /// Whether the dialog is open: bound to the dialog's `opened` prop, so the dialog's own open state, kept under
+ /// its id, cannot hold a dialog closed that the host opened again.
open: bool,
+ /// The values the dialog opened with, passed to the form as the values Reset restores.
+ opening: DialogFields,
/// The preview picture the host last gave (`set_preview`).
- #[allow(dead_code)] // P3(dialogs-w1): dl.K17
preview: Option,
/// What the dialog showed in its last pass.
- #[allow(dead_code)] // P3(dialogs-w1): dl.K17
shown: ShownState,
- /// An OK the host holds back until it answers `answer_ok` ([`held_ok`](HostedParamDialog::held_ok)).
- #[allow(dead_code)] // P3(dialogs-w1): dl.K17
+ /// Whether OK files its answer for the host instead of closing ([`held_ok`](HostedParamDialog::held_ok)).
+ hold: bool,
+ /// An OK the host holds back until it answers `answer_ok`.
held: Option,
+ /// The host's refusal of the last held OK, shown until a value changes.
+ refused: Option,
+ /// The picture point the next pass centres the preview on ([`centre_preview`](HostedParamDialog::centre_preview)).
+ centre: Option,
}
-/// What a [`HostedParamDialog`] showed in its last pass: whether the preview is on and held for comparing.
+/// What a [`HostedParamDialog`] showed in its last pass: whether the preview is on and held for comparing, and the
+/// picture point at the centre of the preview pane.
#[derive(Clone, Copy, Debug, Default)]
-#[allow(dead_code)] // P3(dialogs-w1): dl.K17
struct ShownState {
previewing: bool,
comparing: bool,
+ centre: Option,
}
/// An OK a [`HostedParamDialog`] holds back until the host answers it.
-#[allow(dead_code)] // P3(dialogs-w1): dl.K17
struct Held {
result: ParamResult,
+ /// `take_ok` has handed the result to the host.
+ taken: bool,
+ /// The host accepted it: the next pass closes the dialog with it.
+ accepted: bool,
+}
+
+/// Why the host refused a held OK, and the values it refused.
+struct Refused {
+ reason: Label,
+ fields: DialogFields,
}
impl HostedParamDialog {
@@ -669,12 +812,16 @@ impl HostedParamDialog {
instance: None,
fields,
opened: false,
+ opening: DialogFields::default(),
build: Box::new(build),
requests: HostRequests::new(),
- open: false,
+ open: true,
preview: None,
shown: ShownState::default(),
+ hold: false,
held: None,
+ refused: None,
+ centre: None,
}
}
@@ -731,89 +878,106 @@ impl HostedParamDialog {
self.requests.answer_eyedropper(key, color);
}
- /// Sets the picture the preview pane shows; `None` shows none.
+ /// Sets the picture the preview pane shows from the next pass on; `None` shows none.
pub fn set_preview(&mut self, picture: Option) {
- let _ = picture;
- todo!("dl.K18")
+ self.preview = picture;
}
- /// Whether the Preview check box is on: the host renders the preview while it is.
+ /// Whether the Preview check box was on in the last pass: the host renders the preview while it is.
pub fn is_previewing(&self) -> bool {
- todo!("dl.K18")
+ self.shown.previewing
}
- /// Whether the Preview check box is held down to compare with the unfiltered picture.
+ /// Whether the Preview check box was held down in the last pass, to compare with the unfiltered picture.
pub fn is_comparing(&self) -> bool {
- todo!("dl.K18")
+ self.shown.comparing
}
/// The eyedropper toggle that was pressed, once.
pub fn take_eyedropper(&mut self) -> Option {
- todo!("dl.K19")
+ self.requests.take_eyedropper()
}
/// Makes OK file its answer for the host to take instead of closing: the host checks it and answers with
- /// [`answer_ok`](HostedParamDialog::answer_ok).
+ /// [`answer_ok`](HostedParamDialog::answer_ok). OK stays disabled until then.
#[must_use]
- pub fn held_ok(self) -> Self {
- todo!("dl.K20")
+ pub fn held_ok(mut self) -> Self {
+ self.hold = true;
+ self
}
/// The OK filed by a held dialog, once.
pub fn take_ok(&mut self) -> Option {
- todo!("dl.K20")
+ let held = self.held.as_mut().filter(|held| !held.taken)?;
+ held.taken = true;
+ Some(held.result.clone())
}
- /// The host's answer to the held OK: `Ok` closes the dialog with it, `Err` shows the label as the dialog's error.
+ /// The host's answer to the held OK: `Ok` closes the dialog with the held answer in the next pass; `Err` enables
+ /// OK again and shows the label under the rows until a value changes. Without a held OK it does nothing.
pub fn answer_ok(&mut self, answer: Result<(), Label>) {
- let _ = answer;
- todo!("dl.K20")
+ match answer {
+ Ok(()) => {
+ if let Some(held) = self.held.as_mut() {
+ held.accepted = true;
+ }
+ }
+ Err(reason) => {
+ if let Some(held) = self.held.take() {
+ self.refused = Some(Refused { reason, fields: held.result.fields });
+ }
+ }
+ }
+ }
+
+ /// Holds `result` for the host: the OK of a held dialog, from the button or from `confirm`.
+ fn file_held(&mut self, mut result: ParamResult) {
+ result.id = self.id;
+ self.held = Some(Held { result, taken: false, accepted: false });
+ self.refused = None;
}
/// The footer button id that was pressed, once (`ParamDialog::extra_buttons`).
pub fn take_footer_action(&mut self) -> Option {
- todo!("dl.K22")
+ self.requests.take_footer_action()
}
/// The folder listing a files row asked for, once.
pub fn take_listing(&mut self) -> Option {
- todo!("dl.K25")
+ self.requests.take_listing()
}
/// Answers the listing request `key` with the `files` of its folder.
pub fn answer_listing(&mut self, key: impl Into, files: Vec) {
- let _ = (key.into(), files);
- todo!("dl.K25")
+ self.requests.answer_listing(key, files);
}
- /// Sets the value under `key` as an edit would; the dialog shows it in its next pass.
+ /// Sets the value under `key` as an edit would; the dialog shows it in its next pass. Unchecked: the app writes
+ /// a value its own custom row holds (Blur Gallery's pins dragged on the canvas), which has no JSON form to check.
pub fn set_field(&mut self, key: impl Into, value: FieldValue) {
- let _ = (key.into(), value);
- todo!("dl.K70")
+ self.fields.set(key, value);
}
/// Removes the value under `key`, as if it had never been set; the dialog shows that in its next pass.
- // P3(dialogs-w1): dl.K70 `HostedParamDialog::clear_field`
pub fn clear_field(&mut self, key: &str) {
- let _ = key;
- todo!("dl.K70")
+ self.fields.remove(key);
}
- /// Centres the preview pane on `point` of the picture.
+ /// Centres the preview pane on `point` of the picture in the next pass, as a click on the pane does. Without a
+ /// preview picture in that pass the point is dropped.
pub fn centre_preview(&mut self, point: Pos2) {
- let _ = point;
- todo!("dl.K71")
+ self.centre = Some(point);
}
- /// The point of the picture the preview pane is centred on, once it has been shown.
+ /// The point of the picture at the centre of the preview pane in the last pass; `None` before the pane has shown.
pub fn preview_centre(&self) -> Option {
- todo!("dl.K80")
+ self.shown.centre
}
- /// Shows `color` as the live preview of the colour row `key`; `None` ends it.
+ /// Shows `color` as the live preview of the colour row `key` from the next pass on; `None` ends it. The dialog's
+ /// values are left as they are.
pub fn preview_color(&mut self, key: &str, color: Option) {
- let _ = (key, color);
- todo!("dl.K77")
+ self.requests.preview_color(key, color);
}
/// The host cancelled its picker, file dialog or dropper: the requests not taken yet are dropped.
@@ -826,22 +990,61 @@ impl HostedParamDialog {
if std::mem::replace(&mut self.opened, true) {
return;
}
- let ParamDialog { params, remember, .. } = (self.build)(&mut self.fields);
- let params = params.into_owned();
+ 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, saved.as_ref(), &mut self.fields);
+ 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.
-#[allow(dead_code)] // P3(dialogs-w1): dl.K69
+/// 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.
pub fn set_param_field(params: &[Param], fields: &mut DialogFields, field: &str, value: Value) -> Result<(), String> {
- let _ = (params, fields, field, value);
- todo!("dl.K69")
+ let Some(param) = params.iter().find(|param| param.key == field || param.unit_key() == Some(field)) 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 {
+ 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)
+ } else {
+ read_value(¶m.kind, value.clone()).map(|read| vec![(field.to_owned(), Some(read))])
+ };
+ // `Param::accepts` checks every key a value sets, the Files row's companions included; `None` clears a key.
+ let writes = writes.filter(|writes| writes.iter().all(|(key, read)| read.as_ref().is_none_or(|read| param.accepts(key, read))));
+ let Some(writes) = writes else {
+ return Err(FieldRefusal::Rejects(&value).message(field));
+ };
+ for (key, read) in writes {
+ match read {
+ Some(read) => fields.set(key, read),
+ None => {
+ fields.remove(&key);
+ }
+ }
+ }
+ Ok(())
}
-/// `value` read as the value a row of `kind` keeps; `None` when it isn't one, or the row keeps none.
+/// The keys a Files row's `{files, folder, useFolder}` object sets: the row's list, its folder (cleared by a `null` or
+/// missing `folder`) and its Files/Folder mode; `None` when `value` is not that object.
+fn read_files(param: &Param, value: &Value) -> Option)>> {
+ let files = read_value(¶m.kind, value.clone())?;
+ let folder = match value.get("folder") {
+ None | Some(Value::Null) => None,
+ Some(folder) => Some(FieldValue::Text(folder.as_str()?.to_owned())),
+ };
+ let use_folder = FieldValue::Bool(value.get("useFolder")?.as_bool()?);
+ Some(vec![(param.key.clone(), Some(files)), (param.folder_key(), folder), (param.use_folder_key(), Some(use_folder))])
+}
+
+/// `value` read as the value a row of `kind` keeps under its own key; `None` when it isn't one, or the row keeps none.
fn read_value(kind: &ParamKind, value: Value) -> Option {
Some(match kind {
ParamKind::Range { .. } | ParamKind::Angle { .. } | ParamKind::Number { .. } | ParamKind::OptionalNumber { .. } => {
@@ -854,7 +1057,10 @@ fn read_value(kind: &ParamKind, value: Value) -> Option {
ParamKind::Point { .. } => FieldValue::Point(serde_json::from_value(value).ok()?),
ParamKind::Grid { .. } => FieldValue::Grid(serde_json::from_value(value).ok()?),
ParamKind::Blend { .. } | ParamKind::Pattern { .. } => FieldValue::Text(value.as_str()?.to_owned()),
- ParamKind::Files { .. } => todo!("dl.K26"),
+ ParamKind::Files { .. } => {
+ let files = value.get("files")?.as_array()?;
+ FieldValue::List(files.iter().map(|file| file.as_str().map(|path| FieldValue::Text(path.to_owned()))).collect::>()?)
+ }
ParamKind::Custom(_) => FieldValue::Json(value),
ParamKind::ReadOnlyText { .. } | ParamKind::Section => return None,
})
@@ -868,17 +1074,52 @@ impl StackDialog for HostedParamDialog {
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> {
- let answers = if crate::runtime::measure::active(ui.ctx()) { Vec::new() } else { self.requests.take_answers() };
+ let measuring = crate::runtime::measure::active(ui.ctx());
+ let answers = if measuring { Vec::new() } else { self.requests.take_answers() };
self.open(ui.ctx());
- let shown = (self.build)(&mut self.fields).values_opened().answers(answers).show(ui);
+ 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() };
+ let mut dialog = (self.build)(&mut self.fields)
+ .values_opened(self.opening.clone())
+ .answers(answers)
+ .opened(Bind::bound(&mut self.open))
+ .hold_ok(self.hold)
+ .finish_held(finish)
+ .refusal(self.refused.as_ref().map(|refused| (refused.reason.clone(), refused.fields.clone())))
+ .preview_colors(self.requests.previewed_colors().to_vec())
+ .centre_on(centre);
+ // OK waits for the host's answer: a second OK cannot file over the held one.
+ if self.held.is_some() {
+ dialog = dialog.ok_enabled(false);
+ }
+ if let Some(picture) = self.preview {
+ dialog = dialog.preview(picture);
+ }
+ let shown = dialog.show(ui);
if let Some(mut rows) = shown.rows {
self.requests.absorb(&mut rows);
}
if let Some(point) = shown.preview_click {
self.requests.request_preview_click(point);
}
+ // The pass reports a press only in the pass that took the input, so a second pass of the frame files nothing.
+ if let Some(action) = shown.footer_action {
+ self.requests.request_footer_action(action);
+ }
+ self.shown = ShownState { previewing: shown.preview_on, comparing: shown.comparing, centre: shown.preview_centre };
+ if self.refused.as_ref().is_some_and(|refused| refused.fields != self.fields) {
+ self.refused = None;
+ }
+ if let Some(result) = shown.held {
+ self.file_held(result);
+ }
match (shown.result, shown.closed) {
- (Some(result), _) => Some(DialogResult::Ok(result)),
+ (Some(mut result), _) => {
+ result.id = self.id;
+ Some(DialogResult::Ok(result))
+ }
+ (None, Some(CloseReason::Activated)) if finish => Some(self.held.take().map_or(DialogResult::Cancel, |held| DialogResult::Ok(held.result))),
(None, Some(_)) => Some(DialogResult::Cancel),
(None, None) => None,
}
@@ -892,15 +1133,25 @@ impl StackDialog for HostedParamDialog {
self.instance
}
- /// Answers OK as the button does: none while OK is disabled. The result keeps what a remembering dialog saves.
+ /// 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.
fn confirm(&mut self, ctx: &Context) -> Option {
self.open(ctx);
+ if self.held.is_some() {
+ return None;
+ }
let ParamDialog { key, params, remember, ok_enabled, .. } = (self.build)(&mut self.fields);
if !ok_enabled {
return None;
}
let params = params.into_owned();
- Some(ParamDialog::result(key, ¶ms, remember, self.fields.clone()))
+ let mut result = ParamDialog::result(key, ¶ms, remember, self.fields.clone());
+ if self.hold {
+ self.file_held(result);
+ return None;
+ }
+ result.id = self.id;
+ Some(result)
}
/// The values by parameter key, as [`DialogFields`] serializes them.
@@ -909,24 +1160,22 @@ 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 ([`Param::accepts`]).
+ /// the value ([`set_param_field`]).
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
self.open(ctx);
let params = (self.build)(&mut self.fields).params.into_owned();
- let Some(param) = params.iter().find(|param| param.key == field || param.unit_key() == Some(field)) else {
- return Err(format!("unknown field `{field}`"));
- };
- if !param.visible(&self.fields) || !param.enabled(&self.fields) {
- return Err(format!("`{field}` takes no input now: its row is hidden or disabled"));
- }
- let read =
- if param.key == field { read_value(¶m.kind, value.clone()) } else { value.as_str().map(|unit| FieldValue::Text(unit.to_owned())) };
- match read.filter(|read| param.accepts(field, read)) {
- Some(read) => {
- self.fields.set(field, read);
- Ok(())
+ let before = self.fields.clone();
+ set_param_field(¶ms, &mut self.fields, field, value)?;
+ for param in params.iter().filter(|param| matches!(param.kind, ParamKind::Files { .. })) {
+ if let Some(request) = param.listing_after(&before, &self.fields) {
+ self.requests.request_listing(request);
}
- None => Err(format!("`{field}` can't take {value}")),
}
+ Ok(())
+ }
+
+ /// Shows a child picker's live colour in the colour row `key`, as [`HostedParamDialog::preview_color`] does.
+ fn preview_color(&mut self, key: &str, color: Option) {
+ self.requests.preview_color(key, color);
}
}
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 c9d9a5a76..ee9f904cc 100644
--- a/crates/ui-patterns/src/patterns/form_dialogs/dialog/stories.rs
+++ b/crates/ui-patterns/src/patterns/form_dialogs/dialog/stories.rs
@@ -1,8 +1,10 @@
//! Stories of `ParamDialog`.
-use super::{ParamDialog, ParamLayout};
+use super::{HostedParamDialog, ParamDialog, ParamLayout};
use crate::contract::Bind;
-use crate::patterns::form_dialogs::Param;
+use crate::dialog::StackDialog as _;
+use crate::dialog::stories::hosted_with;
+use crate::patterns::form_dialogs::{DialogFields, Param};
use crate::primitives::TextureCache;
use crate::runtime::env::Label;
use crate::testing::{Drive, StoryData, StoryOutput, story};
@@ -66,6 +68,40 @@ fn param_dialog_close_without_reset(ui: &mut Ui, data: &mut StoryData) -> StoryO
const COMMAND_SPEC: &str = r#"{"name":text,"size":1..100=10,"method":"fit|fill","keep":bool}"#;
+#[story(ParamDialog<'static>, covers = [], drive = Drive::Never)]
+fn param_dialog_with_footer_buttons(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
+ ParamDialog::new("color-table", "Color Table", Param::parse_list(SPEC))
+ .opened(Bind::bound(data.value("open", true)))
+ .extra_buttons(vec![("load".to_owned(), Label::from("Load…")), ("save".to_owned(), Label::from("Save…"))])
+ .footer_note("About 1.2 MB")
+ .show(ui)
+ .into()
+}
+
+/// Why the story's host refuses every OK.
+const REFUSAL: &str = "The radius is too large for this layer.";
+
+#[story(ParamDialog<'static>, covers = [], drive = Drive::Never)]
+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| ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).values(Bind::bound(fields)))
+ .held_ok();
+ // The story opens with an OK already refused, so the notice shows under the rows.
+ let _ = dialog.confirm(&ctx);
+ dialog.answer_ok(Err(Label::from(REFUSAL)));
+ dialog
+ };
+ hosted_with(ui, data, (), open, |host| {
+ if let Some(dialog) = host.get_mut::()
+ && dialog.take_ok().is_some()
+ {
+ dialog.answer_ok(Err(Label::from(REFUSAL)));
+ }
+ })
+}
+
#[story(ParamDialog<'static>, covers = [], drive = Drive::Never)]
fn command_form(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
ParamDialog::command("fit-image", "Fit Image", Param::parse_list(COMMAND_SPEC)).opened(Bind::bound(data.value("open", true))).show(ui).into()
diff --git a/crates/ui-patterns/src/patterns/form_dialogs/fields.rs b/crates/ui-patterns/src/patterns/form_dialogs/fields.rs
index 5e08a425c..4e357b16b 100644
--- a/crates/ui-patterns/src/patterns/form_dialogs/fields.rs
+++ b/crates/ui-patterns/src/patterns/form_dialogs/fields.rs
@@ -32,8 +32,10 @@ pub enum FieldValue {
/// three numbers reads back as `Grid`, `Point` or `Color`, which [`DialogFields::list`] turns
/// back into the list.
List(Vec),
- /// Any JSON value: what a [`ParamKind::Custom`](super::ParamKind::Custom) row keeps under its key. Last so an
- /// untagged read keeps the fixed-shape variants above.
+ /// Any JSON value: what a [`ParamKind::Custom`](super::ParamKind::Custom) row keeps under its key when its value is
+ /// structured (Blur Gallery's pins, `[{x, y, blur, …}]`). Last so an untagged read keeps the fixed-shape variants
+ /// above: an array of objects reads back as a `List` of `Json`, so a reader of the key takes that form as well as
+ /// `Json` of an array.
Json(serde_json::Value),
}
diff --git a/crates/ui-patterns/src/patterns/form_dialogs/form.rs b/crates/ui-patterns/src/patterns/form_dialogs/form.rs
index 09cf6f9bf..bcdcebc3b 100644
--- a/crates/ui-patterns/src/patterns/form_dialogs/form.rs
+++ b/crates/ui-patterns/src/patterns/form_dialogs/form.rs
@@ -172,6 +172,8 @@ pub struct FormDialog<'a, V: Value + Default> {
answers: Vec,
reset_with: Option>,
on_reset: Option>,
+ /// Values the host opened before the first pass: the first pass keeps them as the opening values Reset restores.
+ opening: Option,
}
impl<'a, V: Value + Default> FormDialog<'a, V> {
@@ -198,6 +200,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
shaped: None,
answers: Vec::new(),
reset_with: None,
+ opening: None,
on_reset: None,
}
}
@@ -317,6 +320,13 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
self
}
+ /// Values the host opened before the first pass. The first pass stores them, not its own values, as the opening
+ /// values Reset restores and the edited check compares with.
+ pub fn opening(mut self, opening: V) -> Self {
+ self.opening = Some(opening);
+ self
+ }
+
/// Runs when Reset is picked, for what the body keeps in its own memory.
pub fn on_reset(mut self, restore: impl FnMut(&mut BodyCx<'_>) + 'a) -> Self {
self.on_reset = Some(Box::new(restore));
@@ -347,6 +357,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
mut answers,
reset_with,
on_reset,
+ opening,
} = self;
let env = Env::of(ui);
let common = env.words::();
@@ -459,7 +470,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
crate::runtime::edit::watch_gestures(&ctx, || body(ui, &mut form, &mut values))
};
if first {
- cx.memory::>().0 = Some(values.clone());
+ cx.memory::>().0 = Some(opening.clone().unwrap_or_else(|| values.clone()));
}
if history && !measuring {
let mut steps = steps.unwrap_or_else(|| EditHistory::new(&values));
diff --git a/crates/ui-patterns/src/patterns/form_dialogs/host_requests.rs b/crates/ui-patterns/src/patterns/form_dialogs/host_requests.rs
index b56c6071b..85f38f7b3 100644
--- a/crates/ui-patterns/src/patterns/form_dialogs/host_requests.rs
+++ b/crates/ui-patterns/src/patterns/form_dialogs/host_requests.rs
@@ -24,15 +24,22 @@ impl PreviewRequest {
}
}
-/// The requests of parameter rows that the host answers: the colour picker, the file dialog and the eyedropper, and
-/// the click on a dialog's preview picture (an eyedropper there samples it). A hosted dialog embeds one, feeds it each pass's rows with [`absorb`](HostRequests::absorb) and offers the
-/// `take_*` methods to its host. A request stays until it is taken; a newer one of the same kind replaces it.
+/// The requests of parameter rows that the host answers: the colour picker, the file dialog, the eyedropper and a
+/// folder listing, the click on a dialog's preview picture (an eyedropper there samples it) and a footer button that
+/// keeps the dialog open. A hosted dialog embeds one, feeds it each pass's rows with [`absorb`](HostRequests::absorb)
+/// and offers the `take_*` methods to its host. A request stays until it is taken; a newer one of the same kind
+/// replaces it. It also keeps the colours a child picker previews in the dialog's colour rows
+/// ([`preview_color`](HostRequests::preview_color)).
#[derive(Clone, Debug, Default)]
pub struct HostRequests {
color: Option,
path: Option,
eyedropper: Option,
+ listing: Option,
preview_click: Option,
+ footer_action: Option,
+ /// The previewed colour of each colour row a child picker edits, by row key; one entry per key.
+ previews: Vec<(String, Srgba)>,
answers: Vec,
}
@@ -53,6 +60,9 @@ impl HostRequests {
if let Some(request) = rows.eyedropper.take() {
self.request_eyedropper(request);
}
+ if let Some(request) = rows.listing.take() {
+ self.request_listing(request);
+ }
}
/// Files a colour request; it replaces one not taken yet.
@@ -119,52 +129,59 @@ impl HostRequests {
/// Moves the requests and answers of `other` in; its requests replace the ones not taken yet.
pub fn extend(&mut self, other: HostRequests) {
- let HostRequests { color, path, eyedropper, preview_click, answers } = other;
+ let HostRequests { color, path, eyedropper, listing, preview_click, footer_action, previews, answers } = other;
self.color = color.or(self.color.take());
self.path = path.or(self.path.take());
self.eyedropper = eyedropper.or(self.eyedropper.take());
+ self.listing = listing.or(self.listing.take());
self.preview_click = preview_click.or(self.preview_click.take());
+ self.footer_action = footer_action.or(self.footer_action.take());
+ for (key, color) in previews {
+ self.preview_color(key, Some(color));
+ }
self.answers.extend(answers);
}
/// Files a footer button's id the user pressed; it replaces one not taken yet.
- #[allow(dead_code)] // P3(dialogs-w1): dl.K24
pub fn request_footer_action(&mut self, id: String) {
- let _ = id;
- todo!("dl.K24")
+ self.footer_action = Some(id);
}
/// The footer button id that was pressed, once.
- #[allow(dead_code)] // P3(dialogs-w1): dl.K24
pub fn take_footer_action(&mut self) -> Option {
- todo!("dl.K24")
+ self.footer_action.take()
}
/// Files a request for the files of a folder; it replaces one not taken yet.
- #[allow(dead_code)] // P3(dialogs-w1): dl.K24
pub fn request_listing(&mut self, request: ListingRequest) {
- let _ = request;
- todo!("dl.K24")
+ self.listing = Some(request);
}
/// The folder listing that was requested, once.
- #[allow(dead_code)] // P3(dialogs-w1): dl.K24
pub fn take_listing(&mut self) -> Option {
- todo!("dl.K24")
+ self.listing.take()
}
/// Answers the listing request `key` with the `files` of its folder: the dialog applies them in its next pass.
- #[allow(dead_code)] // P3(dialogs-w1): dl.K24
pub fn answer_listing(&mut self, key: impl Into, files: Vec) {
- let _ = (key.into(), files);
- todo!("dl.K24")
+ self.listing = None;
+ self.answers.push(HostAnswer::Listing { key: key.into(), files });
}
- /// Shows `color` as the live preview of the colour row `key` while it is picked; `None` ends the preview.
- #[allow(dead_code)] // P3(dialogs-w1): dl.K77
+ /// Shows `color` as the live preview of the colour row `key` while it is picked; `None` ends the preview. A newer
+ /// colour for the same row replaces the earlier one.
pub fn preview_color(&mut self, key: impl Into, color: Option) {
- let _ = (key.into(), color);
- todo!("dl.K77")
+ let key = key.into();
+ self.previews.retain(|(previewed, _)| *previewed != key);
+ if let Some(color) = color {
+ self.previews.push((key, color));
+ }
+ }
+
+ /// The colours child pickers preview, by colour row key: the dialog draws each in its row in place of the row's
+ /// value, and writes none of them into its values.
+ pub fn previewed_colors(&self) -> &[(String, Srgba)] {
+ &self.previews
}
/// Drops the colour request not taken yet (the picker was cancelled).
diff --git a/crates/ui-patterns/src/patterns/form_dialogs/mod.rs b/crates/ui-patterns/src/patterns/form_dialogs/mod.rs
index aaadce7b9..6ac988146 100644
--- a/crates/ui-patterns/src/patterns/form_dialogs/mod.rs
+++ b/crates/ui-patterns/src/patterns/form_dialogs/mod.rs
@@ -18,8 +18,7 @@ mod path_row;
mod preview;
pub use dialog::{
- BelowRows, FooterExtra, HostedParamDialog, ParamDialog, ParamDialogOutput, ParamDialogWords, ParamLayout, ParamResult, ResetFooter, ResetPick,
- set_param_field,
+ BelowRows, HostedParamDialog, ParamDialog, ParamDialogOutput, ParamDialogWords, ParamLayout, ParamResult, ResetFooter, ResetPick, set_param_field,
};
pub use form::{FormCx, FormDialog, FormDialogWords, FormOutput};
pub use host_requests::{HostRequests, PreviewRequest};
diff --git a/crates/ui-patterns/src/patterns/form_dialogs/preview.rs b/crates/ui-patterns/src/patterns/form_dialogs/preview.rs
index f0553f14e..b21f23433 100644
--- a/crates/ui-patterns/src/patterns/form_dialogs/preview.rs
+++ b/crates/ui-patterns/src/patterns/form_dialogs/preview.rs
@@ -159,6 +159,24 @@ impl PreviewView {
}
PreviewView { transform: PreviewPane::rescaled(self.transform, scale, &self.range, Vec2::ZERO), fit: false, ..self.clone() }
}
+
+ /// The view at the same zoom with the point `point` of a picture of `picture` points at the well's centre, as a
+ /// click there centres it; it no longer follows the well. The pane settles it at the picture's edges. The inverse
+ /// of [`centre`](PreviewView::centre).
+ #[must_use]
+ pub(crate) fn centred_on(&self, point: Pos2, picture: Vec2) -> Self {
+ if self.fixed {
+ return self.clone();
+ }
+ let scale = self.transform.scale;
+ PreviewView { transform: CanvasTransform::new(scale, (picture / 2.0 - point.to_vec2()) * scale), fit: false, ..self.clone() }
+ }
+
+ /// The point of a picture of `picture` points at the well's centre in this view: `offset` is how far the
+ /// picture's centre lies from the well's centre, at the view's zoom.
+ pub(crate) fn centre(&self, picture: Vec2) -> Pos2 {
+ (picture / 2.0 - self.transform.offset / self.transform.scale).to_pos2()
+ }
}
impl Default for PreviewView {
diff --git a/crates/ui-patterns/src/patterns/form_dialogs/rows.rs b/crates/ui-patterns/src/patterns/form_dialogs/rows.rs
index 4b7ab3c95..94f7a73dc 100644
--- a/crates/ui-patterns/src/patterns/form_dialogs/rows.rs
+++ b/crates/ui-patterns/src/patterns/form_dialogs/rows.rs
@@ -100,12 +100,20 @@ pub struct ParamRows<'a> {
seed: Option>,
read_only: bool,
canvas: Option,
+ preview_colors: &'a [(String, Srgba)],
}
impl<'a> ParamRows<'a> {
/// Rows for `params` over `fields`, the group named `label`.
pub fn new(label: impl Into, params: &'a [Param], fields: Bind<'a, DialogFields>) -> Self {
- ParamRows { label: label.into(), params, fields, seed: None, read_only: false, canvas: None }
+ ParamRows { label: label.into(), params, fields, seed: None, read_only: false, canvas: None, preview_colors: &[] }
+ }
+
+ /// The colours child pickers preview, by colour row key: each such row draws its colour for the pass in place of
+ /// its value and writes nothing, so the values stay as they were when the picker closes.
+ pub fn preview_colors(mut self, colors: &'a [(String, Srgba)]) -> Self {
+ self.preview_colors = colors;
+ self
}
/// The state of the Random button's sequence: each press reads it and writes the next.
@@ -136,12 +144,13 @@ impl<'a> ParamRows<'a> {
/// Shows the rows across the width offered.
pub fn show(self, ui: &mut Ui) -> ParamRowsOutput {
- let ParamRows { label, params, mut fields, mut seed, read_only, canvas } = self;
+ let ParamRows { label, params, mut fields, mut seed, read_only, canvas, preview_colors } = self;
let env = Env::of(ui);
let words = env.words::();
let units = env.units();
let name: Arc = label.as_str().into();
let mut pass = Pass::new(&words, &units);
+ pass.previews = preview_colors;
let mut changed = false;
let mut values = None;
let mut group = |ui: &mut Ui| {
@@ -208,6 +217,8 @@ struct Pass<'p> {
eyedropper: Option,
/// An eyedropper row is armed.
sampling: bool,
+ /// The colours shown in colour rows in place of their values (`ParamRows::preview_colors`).
+ previews: &'p [(String, Srgba)],
}
/// A parameter as the pass shows it: its key, its label without the colon, and whether it takes input.
@@ -251,6 +262,7 @@ impl<'p> Pass<'p> {
path: None,
eyedropper: None,
sampling: false,
+ previews: &[],
}
}
@@ -469,7 +481,11 @@ impl<'p> Pass<'p> {
}
}
let armed = self.memo.armed.as_deref() == Some(line.key);
- let shown = color.map_or(Mixed::Mixed, |rgb| Mixed::Same(Srgba::from_rgb_array(rgb)));
+ let previewed = self.previews.iter().find(|(key, _)| key == line.key).map(|(_, color)| *color);
+ let shown = match previewed {
+ Some(color) => Mixed::Same(color),
+ None => color.map_or(Mixed::Mixed, |rgb| Mixed::Same(Srgba::from_rgb_array(rgb))),
+ };
line.show(ui, |ui| {
beside(ui, |ui| {
let swatch = Swatch::new(line.name.clone(), shown).picker(line.key).id_salt("choose").show(ui);
diff --git a/crates/ui-patterns/tests/it/form_dialogs/dialog.rs b/crates/ui-patterns/tests/it/form_dialogs/dialog.rs
index 36fe2c5bf..061104cea 100644
--- a/crates/ui-patterns/tests/it/form_dialogs/dialog.rs
+++ b/crates/ui-patterns/tests/it/form_dialogs/dialog.rs
@@ -1,11 +1,20 @@
-//! `ParamDialog`: the dialog's own undo history, the Preview box's hold-to-compare and Enter in a multi-line row.
+//! `ParamDialog` and `HostedParamDialog`: the dialog's own undo history, the Preview box's hold-to-compare, Enter in
+//! a multi-line row and on a focused Cancel, Alt+Reset to `reset_to`, the held OK, reopening under the same key, the
+//! request slots, disabled options and the remembered values a row refuses.
-use craft_ui::contract::{Bind, Role};
-use craft_ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind};
+use craft_ui::contract::{Bind, Role, SaveKey};
+use craft_ui::dialog::{DialogHost, DialogResult, dialog_id};
+use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
+use craft_ui::patterns::presets::PresetRow;
+use craft_ui::runtime::env::Label;
+use craft_ui::runtime::overlay::CloseReason;
use craft_ui::testing::{Fixture, trial};
use egui::load::SizedTexture;
-use egui::{Key, Modifiers, TextureId, vec2};
+use egui::{Key, Modifiers, TextureId, Vec2, vec2};
+use serde_json::json;
+use std::borrow::Cow;
use std::cell::{Cell, RefCell};
+use std::path::PathBuf;
use std::rc::Rc;
const SPEC: &str = r#"{"radius":0..100=10,"smooth":bool}"#;
@@ -97,3 +106,348 @@ fn enter_in_a_multi_line_row_inserts_a_line_and_the_dialog_stays_open() {
let (_, accepted) = enter_in_notes(None);
assert!(accepted, "Enter in a single-line row answers OK");
}
+
+/// A Blur dialog over the host's values.
+fn blur(fields: &mut DialogFields) -> ParamDialog<'_> {
+ ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).values(Bind::bound(fields))
+}
+
+/// A fixture that runs `host` every pass. While `twice` is on, egui runs each frame twice and gives the frame's input
+/// to its first pass only.
+fn host_fixture(host: &Rc>, twice: &Rc>) -> Fixture {
+ let (shown, twice) = (Rc::clone(host), Rc::clone(twice));
+ let mut fixture = Fixture::new(move |ui| {
+ shown.borrow_mut().run(ui);
+ if twice.get() && ui.ctx().current_pass_index() == 0 {
+ ui.ctx().request_discard("the frame runs twice");
+ }
+ });
+ fixture.room(Vec2::new(1200.0, 900.0));
+ fixture
+}
+
+/// `act` on the open `HostedParamDialog`; `None` when none is open.
+fn on_dialog(host: &Rc>, act: impl FnOnce(&mut HostedParamDialog) -> T) -> Option {
+ host.borrow_mut().get_mut::().map(act)
+}
+
+/// Why the host refuses the held OK.
+const REFUSED: &str = "The radius is too large for this layer.";
+
+// OK of a held dialog files its answer once, in a frame that runs twice too, and waits with OK disabled; a refusal
+// shows under the rows until a value changes; `confirm` files like the button, and the accepted answer closes the
+// dialog with the held values.
+#[trial]
+fn a_held_ok_refused_keeps_the_dialog_open_and_an_accepted_one_closes() {
+ let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
+ let mut fixture = host_fixture(&host, &twice);
+ host.borrow_mut().open(HostedParamDialog::new("blur", DialogFields::new(), blur).held_ok());
+ fixture.idle(10);
+
+ twice.set(true);
+ fixture.key(Key::Enter, Modifiers::NONE);
+ assert_eq!(fixture.passes(), 2, "the frame ran a second pass");
+ twice.set(false);
+ fixture.idle(4);
+ let filed = on_dialog(&host, HostedParamDialog::take_ok).flatten().expect("Enter files the held OK");
+ assert_eq!(filed.id, dialog_id("blur"), "the answer names the dialog that filed it");
+ assert_eq!(on_dialog(&host, HostedParamDialog::take_ok).flatten(), None, "the OK is filed once");
+ assert!(host.borrow().is_open::(), "a held OK keeps the dialog open");
+ let ok = fixture.by_label("OK").expect("the OK button");
+ assert!(fixture.tree().is_disabled_key(ok.node), "OK waits disabled for the host's answer");
+
+ on_dialog(&host, |dialog| dialog.answer_ok(Err(Label::from(REFUSED))));
+ fixture.idle(4);
+ assert!(fixture.by_label(REFUSED).is_some(), "the refusal shows under the rows");
+ let ok = fixture.by_label("OK").expect("the OK button");
+ assert!(!fixture.tree().is_disabled_key(ok.node), "a refusal enables OK again");
+ let smooth = fixture.by_label("Smooth").expect("the smooth row has a check box");
+ fixture.click(&smooth).idle(4);
+ assert!(fixture.by_label(REFUSED).is_none(), "a changed value clears the refusal");
+
+ let ctx = fixture.ctx().clone();
+ assert!(!host.borrow_mut().confirm::(&ctx), "confirm on a held dialog answers nothing yet");
+ let filed = on_dialog(&host, HostedParamDialog::take_ok).flatten().expect("confirm files the held OK as the button does");
+ assert_eq!(filed.fields.bool("smooth"), Some(true), "the held answer has the values confirmed");
+ on_dialog(&host, |dialog| dialog.answer_ok(Ok(())));
+ fixture.idle(4);
+ let answered = host.borrow_mut().take::().and_then(DialogResult::ok);
+ assert_eq!(answered.map(|result| result.fields), Some(filed.fields), "the accepted OK closes the dialog with the held values");
+}
+
+// A dialog the app opens again under the same key, in the pass it takes the first one's Cancel, shows and answers.
+#[trial]
+fn a_hosted_dialog_reopened_under_the_same_key_opens() {
+ let host = Rc::new(RefCell::new(DialogHost::new()));
+ let reopen = Rc::new(Cell::new(true));
+ let answered = Rc::new(RefCell::new(None::>));
+ let (shown, again, out) = (Rc::clone(&host), Rc::clone(&reopen), Rc::clone(&answered));
+ let mut fixture = Fixture::new(move |ui| {
+ let mut host = shown.borrow_mut();
+ host.run(ui);
+ if let Some(result) = host.take::() {
+ if again.replace(false) {
+ host.open(HostedParamDialog::new("blur", DialogFields::new(), blur));
+ } else {
+ *out.borrow_mut() = Some(result);
+ }
+ }
+ });
+ fixture.room(Vec2::new(1200.0, 900.0));
+ host.borrow_mut().open(HostedParamDialog::new("blur", DialogFields::new(), blur));
+ fixture.idle(10);
+ fixture.key(Key::Escape, Modifiers::NONE).idle(10);
+ assert!(!reopen.get(), "Escape closed the first dialog");
+ assert!(fixture.by_label("Blur").is_some(), "the dialog opened again under the same key shows");
+ fixture.key(Key::Enter, Modifiers::NONE).idle(4);
+ assert!(matches!(*answered.borrow(), Some(DialogResult::Ok(_))), "the reopened dialog answers OK");
+}
+
+/// A dialog with a files row and two footer buttons that keep it open.
+fn stack_dialog(fields: &mut DialogFields) -> ParamDialog<'_> {
+ ParamDialog::new("stack", "Load Files into Stack", vec![Param::files("sources", "Source Files").folder_mode(true)])
+ .values(Bind::bound(fields))
+ .extra_buttons(vec![("load".to_owned(), Label::from("Load…")), ("save".to_owned(), Label::from("Save…"))])
+}
+
+/// The `{files, folder, useFolder}` value of a files row that lists `folder`.
+fn folder_value(folder: &str) -> serde_json::Value {
+ json!({ "files": [], "folder": folder, "useFolder": true })
+}
+
+// A footer button that keeps the dialog open is reported once by its id, in a frame that runs twice too; a folder
+// listing is asked for once; `cancel_requests` drops both.
+#[trial]
+fn a_hosted_dialogs_new_requests_come_once_and_a_cancel_drops_them() {
+ let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
+ let mut fixture = host_fixture(&host, &twice);
+ host.borrow_mut().open(HostedParamDialog::new("stack", DialogFields::new(), stack_dialog));
+ fixture.idle(10);
+
+ let save = fixture.by_label("Save…").expect("the Save… button");
+ twice.set(true);
+ fixture.click(&save);
+ twice.set(false);
+ fixture.idle(4);
+ assert_eq!(on_dialog(&host, HostedParamDialog::take_footer_action).flatten().as_deref(), Some("save"), "the press is reported by its id");
+ assert_eq!(on_dialog(&host, HostedParamDialog::take_footer_action).flatten(), None, "the press is reported once");
+ assert!(host.borrow().is_open::(), "the button keeps the dialog open");
+
+ let ctx = fixture.ctx().clone();
+ host.borrow_mut().set_json_field(&ctx, dialog_id("stack"), "sources", folder_value("/photos/shoot")).expect("the files row takes a folder");
+ fixture.idle(4);
+ let listing = on_dialog(&host, HostedParamDialog::take_listing).flatten().expect("a new folder asks for its files");
+ assert_eq!((listing.key.as_str(), listing.folder), ("sources", PathBuf::from("/photos/shoot")));
+ assert_eq!(on_dialog(&host, HostedParamDialog::take_listing).flatten(), None, "the listing is asked for once");
+
+ let load = fixture.by_label("Load…").expect("the Load… button");
+ fixture.click(&load).idle(2);
+ host.borrow_mut().set_json_field(&ctx, dialog_id("stack"), "sources", folder_value("/photos/other")).expect("the files row takes a folder");
+ fixture.idle(4);
+ on_dialog(&host, HostedParamDialog::cancel_requests);
+ assert_eq!(on_dialog(&host, HostedParamDialog::take_footer_action).flatten(), None, "a cancel drops the footer press");
+ assert_eq!(on_dialog(&host, HostedParamDialog::take_listing).flatten(), None, "a cancel drops the listing request");
+}
+
+/// A dialog with a radio row whose second option is disabled.
+fn brush_tip(fields: &mut DialogFields) -> ParamDialog<'_> {
+ let options = vec![("round".to_owned(), Label::from("Round")), ("square".to_owned(), Label::from("Square"))];
+ let shape = Param::new("shape", "Shape", ParamKind::radio(options, Some("round".to_owned()))).disabled_options(["square"]);
+ ParamDialog::new("brush", "Brush Tip", vec![shape]).values(Bind::bound(fields))
+}
+
+// A disabled radio option is a disabled node, a click on it changes nothing, and the control surface is refused it.
+#[trial]
+fn a_disabled_radio_option_is_greyed_and_refused() {
+ let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
+ let mut fixture = host_fixture(&host, &twice);
+ host.borrow_mut().open(HostedParamDialog::new("brush", DialogFields::new(), brush_tip));
+ fixture.idle(10);
+ let shape = || on_dialog(&host, |dialog| dialog.fields().text("shape").map(str::to_owned)).flatten();
+
+ let square = fixture.by_label("Square").expect("the disabled option shows");
+ assert!(fixture.tree().is_disabled_key(square.node), "the disabled option is a disabled node");
+ fixture.click(&square).idle(4);
+ assert_eq!(shape().as_deref(), Some("round"), "a click on the disabled option changes nothing");
+
+ let ctx = fixture.ctx().clone();
+ let refused = host.borrow_mut().set_json_field(&ctx, dialog_id("brush"), "shape", json!("square"));
+ assert!(refused.as_ref().is_err_and(|message| message.contains("`shape` can't take")), "the disabled option is refused: {refused:?}");
+ assert_eq!(shape().as_deref(), Some("round"), "the refused value is not set");
+}
+
+/// The filter's parameters; `narrow` is the next version, whose rows take less.
+fn filter_params(narrow: bool) -> Vec {
+ let spec = if narrow {
+ r#"{"radius":0..50=10,"method":"spin|zoom","smooth":bool}"#
+ } else {
+ r#"{"radius":0..100=10,"method":"spin|zoom|twist","smooth":bool}"#
+ };
+ let edges = vec![("wrap".to_owned(), Label::from("Wrap")), ("repeat".to_owned(), Label::from("Repeat"))];
+ let edge = Param::new("edge", "Edge", ParamKind::radio(edges, Some("wrap".to_owned())));
+ let mut params = Param::parse_list(spec);
+ params.push(if narrow { edge.disabled_options(["repeat"]) } else { edge });
+ params.push(Param::new("pattern", "Pattern", ParamKind::pattern(Some("dots".to_owned()))));
+ params
+}
+
+/// A remembering filter dialog; `narrow` offers fewer patterns.
+fn filter(fields: &mut DialogFields, narrow: bool) -> ParamDialog<'_> {
+ let ids: &[&str] = if narrow { &["dots"] } else { &["dots", "stripes"] };
+ let patterns: Vec> = ids.iter().map(|id| PresetRow::item((*id).to_owned(), *id, 0)).collect();
+ ParamDialog::new("filter", "Filter", filter_params(narrow))
+ .values(Bind::bound(fields))
+ .remember(SaveKey::new("trial.filter"))
+ .patterns(Cow::Owned(patterns))
+}
+
+fn wide_filter(fields: &mut DialogFields) -> ParamDialog<'_> {
+ filter(fields, false)
+}
+
+fn narrow_filter(fields: &mut DialogFields) -> ParamDialog<'_> {
+ filter(fields, true)
+}
+
+// The open path keeps a remembered value only where its row takes it: a value past a range that shrank, an option no
+// longer offered, a disabled option and a pattern the dialog no longer offers open as the row's default, and a value
+// the row still takes opens as remembered.
+#[trial]
+fn a_remembered_value_its_row_refuses_opens_as_the_default() {
+ let host = Rc::new(RefCell::new(DialogHost::new()));
+ let shown = Rc::clone(&host);
+ let mut fixture = Fixture::new(move |ui| {
+ let mut host = shown.borrow_mut();
+ host.run(ui);
+ // The app remembers an answer where it takes it, after its command ran.
+ if let Some(DialogResult::Ok(result)) = host.take::() {
+ result.remember(ui.ctx());
+ }
+ });
+ fixture.room(Vec2::new(1200.0, 900.0));
+ let ctx = fixture.ctx().clone();
+
+ host.borrow_mut().open(HostedParamDialog::new("filter", DialogFields::new(), wide_filter));
+ fixture.idle(4);
+ let values = [("radius", json!(80.0)), ("method", json!("twist")), ("edge", json!("repeat")), ("pattern", json!("stripes")), ("smooth", json!(true))];
+ for (field, value) in values {
+ host.borrow_mut().set_json_field(&ctx, dialog_id("filter"), field, value).expect("the first version takes each value");
+ }
+ assert!(host.borrow_mut().confirm::(&ctx), "OK answers");
+ fixture.idle(2);
+
+ host.borrow_mut().open(HostedParamDialog::new("filter", DialogFields::new(), narrow_filter));
+ fixture.idle(4);
+ let fields = host.borrow().get::().map(|dialog| dialog.fields().clone()).expect("the next version is open");
+ assert_eq!(fields.bool("smooth"), Some(true), "a value its row still takes opens as remembered");
+ assert_eq!(fields.number("radius"), Some(10.0), "a value past the shrunk range opens as the default");
+ assert_eq!(fields.text("method"), Some("spin"), "an option no longer offered opens as the default");
+ assert_eq!(fields.text("edge"), Some("wrap"), "a disabled option opens as the default");
+ assert_eq!(fields.text("pattern"), Some("dots"), "a pattern no longer offered opens as the default");
+}
+
+// With Cancel focused, Enter cancels: the footer's Enter goes to the focused button, not to OK.
+#[trial]
+fn enter_on_a_focused_cancel_cancels_the_form() {
+ let seen = Rc::new(Cell::new(None::<(CloseReason, bool)>));
+ let out = seen.clone();
+ let mut fixture = Fixture::new(move |ui| {
+ let shown = ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).show(ui);
+ if let Some(closed) = shown.closed {
+ out.set(Some((closed, shown.result.is_some())));
+ }
+ });
+ fixture.settle();
+ let cancel = fixture.by_label("Cancel").expect("the Cancel button");
+ let on_cancel = |fixture: &Fixture| craft_ui::testing::access::focused_key(fixture.tree()) == cancel.node;
+ for _ in 0..16 {
+ if on_cancel(&fixture) {
+ break;
+ }
+ fixture.key(Key::Tab, Modifiers::NONE);
+ }
+ assert!(on_cancel(&fixture), "Tab reaches Cancel");
+ fixture.key(Key::Enter, Modifiers::NONE).settle();
+ let closed = seen.get();
+ assert!(matches!(closed, Some((reason, false)) if !matches!(reason, CloseReason::Activated | CloseReason::Enter)), "Enter cancels: {closed:?}");
+}
+
+// Alt turns Cancel into Reset, which sets the `reset_to` keys and leaves the keys `reset_to` lacks as they are.
+#[trial]
+fn alt_reset_sets_the_reset_to_values_and_keeps_the_other_keys() {
+ let values = Rc::new(RefCell::new(DialogFields::new()));
+ let shown = values.clone();
+ let mut fixture = Fixture::new(move |ui| {
+ ParamDialog::new("blur", "Blur", Param::parse_list(SPEC))
+ .values(Bind::bound(&mut *shown.borrow_mut()))
+ .reset_to(DialogFields::from_pairs([("radius", 50.0)]))
+ .show(ui);
+ });
+ fixture.settle();
+ let smooth = fixture.by_label("Smooth").expect("the smooth row has a check box");
+ fixture.click(&smooth).settle();
+ assert_eq!(values.borrow().bool("smooth"), Some(true));
+
+ fixture.hold(Modifiers::ALT).idle(2);
+ let reset = fixture.by_label("Reset").expect("Alt turns Cancel into Reset");
+ fixture.click(&reset).idle(2);
+ fixture.hold(Modifiers::NONE).settle();
+ assert_eq!(values.borrow().number("radius"), Some(50.0), "Reset sets the reset_to value");
+ assert_eq!(values.borrow().bool("smooth"), Some(true), "Reset keeps a key reset_to lacks");
+ assert!(fixture.by_label("Blur").is_some(), "Reset keeps the dialog open");
+}
+
+/// A dialog with one colour row.
+fn tint(fields: &mut DialogFields) -> ParamDialog<'_> {
+ ParamDialog::new("tint", "Tint", vec![Param::new("tint", "Tint", ParamKind::color(None))]).values(Bind::bound(fields))
+}
+
+/// Whether any rectangle of `shapes` is filled with `color`.
+fn paints(shapes: &[egui::Shape], color: egui::Color32) -> bool {
+ shapes.iter().any(|shape| match shape {
+ egui::Shape::Rect(rect) => rect.fill == color,
+ egui::Shape::Vec(inner) => paints(inner, color),
+ _ => false,
+ })
+}
+
+// A colour the host previews (a child picker's live colour) shows in its row and leaves the dialog's values alone;
+// ending the preview shows the stored colour again.
+#[trial]
+fn a_previewed_colour_shows_in_its_row_and_leaves_the_fields() {
+ let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
+ let mut fixture = host_fixture(&host, &twice);
+ let (red, blue) = (craft_theme::Srgba::new(1.0, 0.0, 0.0, 1.0), craft_theme::Srgba::new(0.0, 0.0, 1.0, 1.0));
+ host.borrow_mut().open(HostedParamDialog::new("tint", DialogFields::from_pairs([("tint", FieldValue::Color([0.0, 0.0, 1.0]))]), tint));
+ fixture.idle(10);
+ let before = on_dialog(&host, |dialog| dialog.fields().clone()).expect("the dialog is open");
+ assert!(paints(&fixture.frame_shapes(), blue.into()), "the swatch shows the stored colour");
+
+ on_dialog(&host, |dialog| dialog.preview_color("tint", Some(red)));
+ fixture.idle(4);
+ assert!(paints(&fixture.frame_shapes(), red.into()), "the swatch shows the previewed colour");
+ assert_eq!(on_dialog(&host, |dialog| dialog.fields().clone()), Some(before), "the preview leaves the fields");
+
+ on_dialog(&host, |dialog| dialog.preview_color("tint", None));
+ fixture.idle(4);
+ assert!(paints(&fixture.frame_shapes(), blue.into()), "ending the preview shows the stored colour again");
+}
+
+// A field the host sets before the dialog's first pass is a change from the values the dialog opened with: Reset
+// restores the opening value.
+#[trial]
+fn a_field_set_before_the_first_show_resets_to_the_opening_value() {
+ let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
+ let mut fixture = host_fixture(&host, &twice);
+ host.borrow_mut().open(HostedParamDialog::new("blur", DialogFields::new(), blur));
+ let ctx = fixture.ctx().clone();
+ host.borrow_mut().set_json_field(&ctx, dialog_id("blur"), "radius", json!(60.0)).expect("the radius row takes a number");
+ fixture.idle(10);
+ assert_eq!(on_dialog(&host, |dialog| dialog.fields().number("radius")).flatten(), Some(60.0), "the set value shows");
+
+ fixture.hold(Modifiers::ALT).idle(2);
+ let reset = fixture.by_label("Reset").expect("Alt turns Cancel into Reset, enabled while the values differ");
+ fixture.click(&reset).idle(2);
+ fixture.hold(Modifiers::NONE).settle();
+ assert_eq!(on_dialog(&host, |dialog| dialog.fields().number("radius")).flatten(), Some(10.0), "Reset restores the opening value");
+}
diff --git a/crates/ui-patterns/tests/it/form_dialogs/mod.rs b/crates/ui-patterns/tests/it/form_dialogs/mod.rs
index c55af3c7d..44159cf68 100644
--- a/crates/ui-patterns/tests/it/form_dialogs/mod.rs
+++ b/crates/ui-patterns/tests/it/form_dialogs/mod.rs
@@ -4,10 +4,12 @@
mod about;
mod dialog;
mod export;
+mod files;
mod hosted;
mod new_document;
mod params;
mod password;
mod preview;
mod preview_width;
+mod save_for_web;
mod size_model;
diff --git a/migration/api-map/form-dialogs.toml b/migration/api-map/form-dialogs.toml
index 944eda50a..157fb2bb7 100644
--- a/migration/api-map/form-dialogs.toml
+++ b/migration/api-map/form-dialogs.toml
@@ -26,7 +26,7 @@ name = "CommandForm"
old = "craft_ui::dialog::command_form::CommandForm"
new = ""
status = "replaced"
-note = "Replaced by the constructor `ParamDialog::command(key, title, params)`: a `ParamDialog` with no `preview` and no `remember` key, with every option of `ParamDialog` (`values`, `opened`, `ok_enabled`, `ok_reason`, `ok_label`, `cancel_label`, `closable`, `outer_gesture`, `footer_extra`, `below`). Hosted, `HostedParamDialog::command(key, fields, build)`."
+note = "Replaced by the constructor `ParamDialog::command(key, title, params)`: a `ParamDialog` with no `preview` and no `remember` key, with every option of `ParamDialog` (`values`, `opened`, `ok_enabled`, `ok_reason`, `ok_label`, `cancel_label`, `closable`, `outer_gesture`, `footer_note`, `below`). Hosted, `HostedParamDialog::command(key, fields, build)`."
[[type]]
name = "ParamLayout"
@@ -403,7 +403,9 @@ note = "The close action is named by the dialog title row; `closable(false)` rem
[[setter]]
type = "ParamDialog"
old = "footer_extra(FnMut(&mut Ui) + Send + 'static)"
-new = "footer_extra(FnMut(&mut Ui) + 'a)"
+new = ""
+status = "removed"
+note = "A footer line is `footer_note(impl Into)`; footer buttons that keep the dialog open are `extra_buttons(Vec<(String, Label)>)`, reported as `ParamDialogOutput::footer_action`."
[[setter]]
type = "ParamDialog"
@@ -502,7 +504,9 @@ new = "below(impl Fn(&mut Ui, &DialogFields))"
[[setter]]
type = "ParamDialog"
old = "footer_extra(impl FnMut(&mut Ui))"
-new = "footer_extra(impl FnMut(&mut Ui))"
+new = ""
+status = "removed"
+note = "A footer line is `footer_note(impl Into)`; footer buttons that keep the dialog open are `extra_buttons(Vec<(String, Label)>)`, reported as `ParamDialogOutput::footer_action`."
[[setter]]
type = "ParamDialog"
|