forms-w1: net change of 2 commits

- forms-w1: written from its sheet
- forms-w1: finished by an agent
This commit is contained in:
bflatastic committed 2026-11-21 23:21:24 +07:00
1 parent 6766559d37
commit 893caadf6d
13 files changed
+1531 -219

No files matched your search

+1 -1
View File
@@ -370,7 +370,7 @@ impl<V: Value + Default + Serialize + DeserializeOwned, E: Send + 'static> Stack
}
});
let form = match reset_with.as_deref() {
Some(target) => form.reset_with(|current, opened, _| target(current, opened)), // P3(forms-w1): ex.P11
Some(target) => form.reset_with(|current, opened, _| target(current, opened)),
None => form,
};
let shown = form.show(ui, |ui, form, value| {
+150
View File
@@ -327,3 +327,153 @@ fn body_buttons_stand_in_the_slot_the_body_keeps_and_keep_their_keys() {
let (escaped, _) = run(Some(Key::Escape)).1;
assert_eq!(escaped, Some(CloseReason::Escape), "Escape cancels");
}
/// A fixture that shows a dialog "Options" while `open` is set, with `body` inside it.
fn dialog_fixture(
open: &std::rc::Rc<Cell<bool>>,
make: impl Fn(Dialog<'_>) -> Dialog<'_> + 'static,
body: impl Fn(&mut Ui) + 'static,
) -> Fixture {
let shown = std::rc::Rc::clone(open);
Fixture::new(move |ui| {
let mut now = shown.get();
if now {
make(Dialog::new("Options").opened(Bind::bound(&mut now))).show(ui, |ui, _| body(ui));
}
shown.set(now);
})
}
/// Closes the dialog of `fixture` for a pass and opens it again.
fn reopen(fixture: &mut Fixture, open: &std::rc::Rc<Cell<bool>>) {
open.set(false);
fixture.idle(3);
open.set(true);
fixture.settle();
}
#[trial]
fn a_reopened_dialog_focuses_its_first_enabled_field_again() {
let open = std::rc::Rc::new(Cell::new(true));
let mut fixture = dialog_fixture(&open, |dialog| dialog, |ui| {
let (mut first, mut second) = (String::new(), String::new());
TextField::new("First", Bind::bound(&mut first)).enabled(false).show(ui);
TextField::new("Second", Bind::bound(&mut second)).show(ui);
});
fixture.settle();
let on_second = |fixture: &Fixture| {
let second = fixture.by_label("Second").expect("the second field is shown");
crate::testing::access::focused_key(fixture.tree()) == second.node
};
assert!(on_second(&fixture), "the first enabled field takes the focus, not the disabled one before it");
reopen(&mut fixture, &open);
assert!(on_second(&fixture), "and takes it again after a reopen");
}
#[trial]
fn a_dialog_moves_by_its_title_band_stays_on_screen_and_reopens_where_left() {
let open = std::rc::Rc::new(Cell::new(true));
let mut fixture = dialog_fixture(
&open,
|dialog| dialog.remember(crate::contract::SaveKey::new("trial.dialog-band")),
|ui| {
Text::new("Body text").show(ui);
},
);
fixture.room(egui::vec2(900.0, 700.0));
fixture.settle();
let dialog = |fixture: &Fixture| fixture.by_role(Role::DIALOG).into_iter().next().expect("the dialog is shown").rect;
let band = |fixture: &Fixture| fixture.by_role(Role::HEADING).into_iter().find(|target| fixture.tree().name_of(target.node) == Some("Options")).expect("the title band");
let start = dialog(&fixture);
let from = start.center_bottom() - egui::vec2(0.0, 6.0);
fixture.drag_at(from, egui::vec2(60.0, 40.0)).settle();
assert_eq!(dialog(&fixture), start, "a drag that starts in the body moves nothing");
let title = band(&fixture);
fixture.drag(&title, egui::vec2(80.0, 50.0)).settle();
let moved = dialog(&fixture);
assert_eq!(moved.min - start.min, egui::vec2(80.0, 50.0), "a drag of the band moves the dialog by it");
let title = band(&fixture);
fixture.drag(&title, egui::vec2(5000.0, 5000.0)).settle();
let screen = fixture.shown();
assert!(screen.contains_rect(dialog(&fixture)), "a drag past the edge stops at it: {:?} in {screen:?}", dialog(&fixture));
for _ in 0..8 {
fixture.key(Key::Tab, Modifiers::NONE);
}
let band_node = band(&fixture).node;
assert_ne!(crate::testing::access::focused_key(fixture.tree()), band_node, "the title band is no Tab stop");
let left = dialog(&fixture);
reopen(&mut fixture, &open);
assert_eq!(dialog(&fixture), left, "a reopen under the same key starts where the dialog was left");
}
#[trial]
fn a_tall_body_scrolls_under_a_footer_that_stays_in_view() {
let open = std::rc::Rc::new(Cell::new(true));
let mut fixture = dialog_fixture(&open, |dialog| dialog.buttons([FooterButton::new("OK", DialogRole::Accept)]), |ui| {
for line in 0..60 {
Text::new(format!("Line {line}")).show(ui);
}
});
fixture.room(egui::vec2(600.0, 320.0));
fixture.settle();
let first = |fixture: &Fixture| fixture.by_label("Line 0").map(|target| target.rect);
let at_top = first(&fixture).expect("the first line is shown");
let screen = fixture.shown();
let ok = fixture.by_label("OK").expect("the footer is shown").rect;
assert!(screen.contains_rect(ok), "the footer stays inside the short window: {ok:?} in {screen:?}");
assert!(fixture.by_label("Line 59").is_none_or(|last| !screen.contains_rect(last.rect)), "the body does not all fit: it scrolls");
let over = fixture.by_role(Role::DIALOG).into_iter().next().expect("the dialog is shown").rect.center();
let wheel = egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: egui::vec2(0.0, -400.0), modifiers: Modifiers::NONE };
fixture.frame(vec![egui::Event::PointerMoved(over), wheel]).settle();
assert_ne!(first(&fixture), Some(at_top), "the wheel scrolled the body");
assert!(screen.contains_rect(fixture.by_label("OK").expect("the footer is shown").rect), "the footer stays in view while the body scrolls");
reopen(&mut fixture, &open);
assert_eq!(first(&fixture), Some(at_top), "a reopen starts at the top");
}
#[trial]
fn an_armed_answer_waits_until_its_prompt_was_seen() {
let open = std::rc::Rc::new(Cell::new(true));
let closed = std::rc::Rc::new(Cell::new(None));
let (shown, seen) = (std::rc::Rc::clone(&open), std::rc::Rc::clone(&closed));
let mut fixture = Fixture::new(move |ui| {
let mut now = shown.get();
if now {
let out = Dialog::new("Options")
.opened(Bind::bound(&mut now))
.buttons([FooterButton::new("Delete", DialogRole::Destructive).armed_after(1.0), FooterButton::new("Cancel", DialogRole::Cancel)])
.show(ui, |_, _| {});
if out.output.closed.is_some() {
seen.set(out.output.closed);
}
}
shown.set(now);
});
fixture.settle();
let press = |fixture: &mut Fixture| {
let delete = fixture.by_label("Delete").expect("the armed button is shown");
fixture.click(&delete).idle(2);
};
press(&mut fixture);
assert_eq!(closed.get(), None, "a click before the delay does nothing");
fixture.key(Key::Enter, Modifiers::NONE).idle(2);
assert_eq!(closed.get(), None, "nor does Enter");
open.set(false);
fixture.idle(2);
open.set(true);
fixture.idle(40);
press(&mut fixture);
assert_eq!(closed.get(), None, "a frame without the prompt restarted the wait");
fixture.idle(90);
press(&mut fixture);
assert_eq!(closed.get(), Some(CloseReason::Activated), "after the delay the answer takes the click");
}
@@ -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::{NamedPresetEvent, PresetKind, PresetRow};
use crate::patterns::presets::{NamedPresetEvent, NamedPresetRow, PickerField, PresetError, PresetKind, PresetPicker, PresetRow};
use crate::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer, ListingRequest, PathRequest};
use super::form::{FormDialog, FormDialogWords};
@@ -47,6 +47,7 @@ craft_ui::words! {
/// The words of the parameter dialog beside the common OK and Cancel.
pub struct ParamDialogWords {
reset: "paramDialog.reset" = "Reset";
presets: "paramDialog.presets" = "Preset";
}
}
@@ -102,8 +103,11 @@ 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, lifetime, values)) = &self.remember {
let _ = lifetime; // P3(forms-w1): od.OD3
crate::runtime::memory::set_saved_value::<Option<DialogFields>>(ctx, key, Some(values.clone()));
let values = Some(values.clone());
match lifetime {
Lifetime::Run => crate::runtime::memory::set_run_value::<Option<DialogFields>>(ctx, key, values),
_ => crate::runtime::memory::set_saved_value::<Option<DialogFields>>(ctx, key, values),
}
}
}
}
@@ -284,6 +288,9 @@ pub struct ParamDialog<'a> {
/// Shows `reason` under the rows while the values are `refused`.
#[prop(vis = "pub(crate)")]
refusal: Option<(Label, DialogFields)>,
/// Shows the refusal whatever the values are: the host keeps it until it withdraws it.
#[prop(vis = "pub(crate)")]
refusal_blocks: bool,
/// Centres the preview pane's view on the picture point `point` in this pass; without a picture it does nothing.
#[prop(name = "centre_on", vis = "pub(crate)")]
centre: Option<Pos2>,
@@ -358,6 +365,7 @@ impl<'a> ParamDialog<'a> {
hold: false,
finish_held: false,
refusal: None,
refusal_blocks: false,
centre: None,
preview_colors: Vec::new(),
}
@@ -372,7 +380,6 @@ impl<'a> ParamDialog<'a> {
/// 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<SaveKey>, remember_for: Lifetime, fields: DialogFields) -> ParamResult {
// P3(forms-w1): od.OD3 -- callers pass the dialog's `remember_for`.
let remember = remember.map(|save| (save, remember_for, Self::remembered(params, &fields)));
ParamResult { key, fields, remember, id: DialogId::NULL }
}
@@ -400,6 +407,7 @@ impl<'a> ParamDialog<'a> {
pub fn remembered(params: &[Param], fields: &DialogFields) -> DialogFields {
let kept = |param: &Param| {
param.is_remembered()
&& param.footer_on().is_none()
&& matches!(
param.kind,
ParamKind::Range { .. }
@@ -438,7 +446,7 @@ impl<'a> ParamDialog<'a> {
open,
remember,
remember_for,
presets: _,
presets,
ok_enabled,
ok_reason,
ok_label,
@@ -466,6 +474,7 @@ impl<'a> ParamDialog<'a> {
hold,
finish_held,
refusal,
refusal_blocks,
centre,
preview_colors,
} = self;
@@ -487,14 +496,7 @@ impl<'a> ParamDialog<'a> {
.accept_stays_open(hold)
.answers(answers);
if let Some(reset_to) = reset_to {
form = form.reset_with(move |_, opened, _| {
// P3(forms-w1): ex.P11
let mut values = opened.clone();
for (name, value) in reset_to.iter() {
values.set(name, value.clone());
}
values
});
form = form.reset_with(move |_, opened, _| reset_target(opened, Some(&reset_to)));
}
if let Some(reason) = ok_reason {
form = form.ok_reason(reason);
@@ -517,9 +519,23 @@ impl<'a> ParamDialog<'a> {
}
// The pane shows only in a dialog that previews.
let preview = preview.filter(|_| previews);
if !extra_buttons.is_empty() {
form = form.extra_buttons(extra_buttons.iter().map(|(_, button)| button.clone())); // P3(forms-w1): q337
// The footer rows' buttons follow the extra buttons. A button's label cannot change inside the pass that
// draws it, so it shows the state the previous pass left.
let footer_rows: Vec<&Param> = params.iter().filter(|param| param.footer_on().is_some()).collect();
let footer_id = egui::Id::new(("paramDialog.footer", key.as_str()));
let flip_id = footer_id.with("flip");
let footer_states: Vec<bool> = if footer_rows.is_empty() { Vec::new() } else { ui.data(|data| data.get_temp(footer_id)).unwrap_or_default() };
let footer_buttons = footer_rows.iter().enumerate().map(|(at, param)| {
let on = footer_states.get(at).copied().unwrap_or(false);
let label = param.footer_on().filter(|_| on).unwrap_or_else(|| param.label.clone());
FooterButton::new(label, DialogRole::Other).stays_open(true)
});
let buttons: Vec<FooterButton> = extra_buttons.iter().map(|(_, button)| button.clone()).chain(footer_buttons).collect();
if !buttons.is_empty() {
form = form.extra_buttons(buttons);
}
let presets_label = Env::of(ui).words::<ParamDialogWords>().presets.clone();
let mut preset_events = Vec::new();
if let Some(note) = footer_note {
form = form.footer_extra(move |ui| {
Text::new(note.clone()).shade(Shade::Muted).show(ui);
@@ -535,31 +551,20 @@ impl<'a> ParamDialog<'a> {
let mut latest = None::<DialogFields>;
let shown = form.show(ui, |ui, cx, values| {
if cx.first() && !host_opened {
let saved = remember.as_ref().and_then(|key| cx.saved::<Option<DialogFields>>(key).clone());
let saved = remember.as_ref().and_then(|key| remembered_values(ui.ctx(), key, remember_for));
Self::open_values(&params, &patterns, saved.as_ref(), values);
}
for answer in cx.take_answers() {
let answered = match &answer {
HostAnswer::Color { key, .. } | HostAnswer::Eyedropper { key, .. } | HostAnswer::Path { key, .. } => {
params.iter().find(|param| param.key == *key)
}
HostAnswer::Listing { .. } => None,
};
let held = answered.and_then(|param| values.get(&param.key).cloned());
match answer {
HostAnswer::Color { key, color } | HostAnswer::Eyedropper { key, color } => set_color_field(&params, values, &key, color),
HostAnswer::Path { key, path } => values.set(&key, FieldValue::Text(path.to_string_lossy().into_owned())),
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(param) = answered {
param.drop_dependents(held.as_ref(), values);
apply_answers(&params, values, cx.take_answers());
// A footer row pressed in the previous pass flips once; a measuring run leaves it for the real one.
if !footer_rows.is_empty() && !crate::runtime::measure::active(ui.ctx()) {
if let Some(flip) = ui.data_mut(|data| data.remove_temp::<String>(flip_id)) {
let on = values.bool(&flip).unwrap_or(false);
values.set(flip, FieldValue::Bool(!on));
}
}
if let Some(presets) = &presets {
show_presets(ui, &presets_label, presets, values, &mut preset_events);
}
if let Some(canvas) = canvas {
cx.keep_view_open(canvas);
}
@@ -603,8 +608,8 @@ impl<'a> ParamDialog<'a> {
}
(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) {
// The host's refusal of the held OK stays until a value changes, or until the host withdraws it.
if let Some((reason, _)) = refusal.as_ref().filter(|(_, refused)| refusal_blocks || *refused == *values) {
Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui);
}
if let Some(BelowRows(draw)) = &below {
@@ -612,7 +617,12 @@ impl<'a> ParamDialog<'a> {
}
*cx.memory::<Live>() = live.clone();
latest = Some(values.clone());
true
if !footer_rows.is_empty() {
let states: Vec<bool> = footer_rows.iter().map(|param| values.bool(&param.key).unwrap_or(false)).collect();
ui.data_mut(|data| data.insert_temp(footer_id, states));
}
// OK and Enter wait while a row's text does not parse.
rows.as_ref().is_none_or(|rows| !rows.unparsed)
});
// `picked` is this pass's press: a second pass of the frame has none, so a press is reported once.
@@ -621,11 +631,18 @@ impl<'a> ParamDialog<'a> {
Some(ResetPick::Extra(at)) => extra_buttons.get(at).map(|(id, _)| id.clone()),
_ => None,
};
if let Some(ResetPick::Extra(at)) = pick
&& let Some(param) = at.checked_sub(extra_buttons.len()).and_then(|at| footer_rows.get(at))
{
ui.data_mut(|data| data.insert_temp(flip_id, param.key.clone()));
crate::runtime::frame::request_repaint(ui.ctx());
}
let (result, held) = match (shown.accepted, pick, latest) {
(Some(fields), _, _) => (Some(Self::result(key, &params, remember, remember_for, fields)), None),
(None, Some(ResetPick::Accept), Some(fields)) if hold => (None, Some(Self::result(key, &params, remember, remember_for, fields))),
_ => (None, None),
};
let help_link = rows.as_ref().and_then(|rows| rows.help_link.clone());
ParamDialogOutput {
response: shown.response,
closed: shown.closed,
@@ -636,26 +653,95 @@ impl<'a> ParamDialog<'a> {
comparing: shown.comparing,
preview_click: shown_preview.clicked,
footer_action,
presets: Vec::new(),
help_link: None,
presets: preset_events,
help_link,
held,
preview_centre: shown_preview.centre,
}
}
}
/// The values `ctx` remembers under `key` for `lifetime`: the saved tier for `Saved`, the session tier for `Run`.
#[allow(dead_code)] // P3(forms-w1): od.OD3
fn remembered_values(ctx: &Context, key: &SaveKey, lifetime: Lifetime) -> Option<DialogFields> {
let _ = (ctx, key, lifetime);
todo!("od.OD3")
/// The values Reset restores: those from when the dialog opened, with `reset_to`'s over them. The one rule for the
/// Alt footer and for a host's reset.
fn reset_target(opened: &DialogFields, reset_to: Option<&DialogFields>) -> DialogFields {
let mut values = opened.clone();
for (name, value) in reset_to.into_iter().flat_map(DialogFields::iter) {
values.set(name, value.clone());
}
values
}
/// Applies the host's `answers` to `values` for `params`: a colour, path or eyedropper answer writes its row.
#[allow(dead_code)] // P3(forms-w1): fl.F35
/// The presets row above the rows: a pick writes the preset's values over `values` as one edit, and the presets made,
/// renamed or deleted come back in `events` for the host to store.
fn show_presets(ui: &mut Ui, label: &Label, presets: &ParamPresets<'_>, values: &mut DialogFields, events: &mut Vec<NamedPresetEvent<String>>) {
let current = presets.values.iter().find(|(_, preset)| preset_applies(preset, values)).map(|(name, _)| name.clone());
let picker = PresetPicker::new(label.clone(), Bind::given(current), presets.rows, Bind::kept()).field(PickerField::Name);
let taken = |name: &str| {
let same = |other: &str| other.to_lowercase() == name.to_lowercase();
presets.built_in.iter().any(|built_in| same(built_in)) || presets.rows.iter().any(|row| same(&row.label))
};
let shown = NamedPresetRow::new(label.clone(), picker)
.check_name(|name| taken(name).then_some(PresetError::NameTaken))
.built_in(|name: &String| presets.built_in.contains(name))
.show(ui);
for event in shown.events {
match event {
NamedPresetEvent::Apply(name) => {
if let Some((_, preset)) = presets.values.iter().find(|(preset, _)| *preset == name) {
apply_preset(preset, values);
}
}
event @ (NamedPresetEvent::Create { .. } | NamedPresetEvent::Rename { .. } | NamedPresetEvent::Delete(_)) => events.push(event),
_ => {}
}
}
}
/// Whether `values` hold every value `preset` sets.
fn preset_applies(preset: &DialogFields, values: &DialogFields) -> bool {
preset.iter().all(|(key, value)| values.get(key) == Some(value))
}
/// Writes the values of `preset` over `values`.
fn apply_preset(preset: &DialogFields, values: &mut DialogFields) {
for (key, value) in preset.iter() {
values.set(key, value.clone());
}
}
/// The values `ctx` remembers under `key` for `lifetime`: the saved tier for `Saved`, the session tier for `Run`.
fn remembered_values(ctx: &Context, key: &SaveKey, lifetime: Lifetime) -> Option<DialogFields> {
match lifetime {
Lifetime::Run => crate::runtime::memory::run_value::<Option<DialogFields>>(ctx, key),
_ => MemoryStage::peek_saved::<Option<DialogFields>>(ctx, key),
}
}
/// Applies the host's `answers` to `values` for `params`: a colour, path or eyedropper answer writes its row, and a
/// row that resets other rows drops them.
pub(crate) fn apply_answers(params: &[Param], values: &mut DialogFields, answers: Vec<HostAnswer>) {
let _ = (params, values, answers);
todo!("fl.F35")
for answer in answers {
let answered = match &answer {
HostAnswer::Color { key, .. } | HostAnswer::Eyedropper { key, .. } | HostAnswer::Path { key, .. } => {
params.iter().find(|param| param.key == *key)
}
HostAnswer::Listing { .. } => None,
};
let held = answered.and_then(|param| values.get(&param.key).cloned());
match answer {
HostAnswer::Color { key, color } | HostAnswer::Eyedropper { key, color } => set_color_field(params, values, &key, color),
HostAnswer::Path { key, path } => values.set(&key, FieldValue::Text(path.to_string_lossy().into_owned())),
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(param) = answered {
param.drop_dependents(held.as_ref(), values);
}
}
}
/// What the footer of an installed Reset footer reads from the body.
@@ -861,6 +947,17 @@ pub struct HostedParamDialog {
held: HeldAnswer<ParamResult>,
/// The picture point the next pass centres the preview on ([`centre_preview`](HostedParamDialog::centre_preview)).
centre: Option<Pos2>,
/// The named presets the presets row lists ([`set_presets`](HostedParamDialog::set_presets)).
presets: Option<HeldPresets>,
/// The preset edits of the dialog's passes, until the host takes them.
preset_events: Vec<NamedPresetEvent<String>>,
}
/// The presets a hosted dialog lists: the rows, the values each applies and the built-in names.
struct HeldPresets {
rows: Vec<PresetRow<String>>,
values: Vec<(String, DialogFields)>,
built_in: Vec<String>,
}
/// What a [`HostedParamDialog`] showed in its last pass: whether the Preview check box is held for comparing, and the
@@ -882,9 +979,9 @@ impl HostedParamDialog {
build: impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static,
) -> Self {
let key = key.into();
let ParamDialog { params, remember, patterns, previews, .. } = build(&mut fields);
let ParamDialog { params, remember, remember_for, patterns, previews, .. } = build(&mut fields);
let (params, patterns) = (params.into_owned(), patterns.into_owned());
let saved = remember.and_then(|key| MemoryStage::peek_saved::<Option<DialogFields>>(ctx, &key));
let saved = remember.and_then(|key| remembered_values(ctx, &key, remember_for));
ParamDialog::open_values(&params, &patterns, saved.as_ref(), &mut fields);
let id = dialog_id(key.as_str());
HostedParamDialog {
@@ -903,6 +1000,8 @@ impl HostedParamDialog {
hold: false,
held: HeldAnswer::new(),
centre: None,
presets: None,
preset_events: Vec::new(),
}
}
@@ -933,11 +1032,6 @@ impl HostedParamDialog {
&self.fields
}
/// The colour parameter whose button was pressed, once.
pub fn pick_color(&mut self) -> Option<ColorRequest> {
self.requests.take_color()
}
/// The Browse button that was pressed, once.
pub fn pick_path(&mut self) -> Option<PathRequest> {
self.requests.take_path()
@@ -948,11 +1042,6 @@ impl HostedParamDialog {
self.requests.take_preview_click()
}
/// Answers the colour request `key`: the dialog writes the colour into its values in its next pass.
pub fn answer_color(&mut self, key: impl Into<String>, color: craft_theme::Srgba) {
self.requests.answer_color(key, color);
}
/// Answers the Browse request `key` with the chosen path.
pub fn answer_path(&mut self, key: impl Into<String>, path: std::path::PathBuf) {
self.requests.answer_path(key, path);
@@ -986,9 +1075,9 @@ impl HostedParamDialog {
/// The Preview check box starts off.
#[must_use]
pub fn preview_off(self) -> Self {
let _ = self;
todo!("ef.F1")
pub fn preview_off(mut self) -> Self {
self.preview_on = false;
self
}
/// The ids of the actions the custom rows requested since the last call (`CustomContext::request_action`).
@@ -1024,33 +1113,43 @@ impl HostedParamDialog {
/// `Some`: the host refuses the current values, and OK stays off with `reason` shown under the rows until the values
/// change; `None` ends the refusal.
pub fn refuse(&mut self, reason: Option<Label>) {
let _ = (self, reason);
todo!("ef.F8")
match reason {
Some(reason) => {
let (result, _) = self.current_result();
self.held.refuse(reason, result);
}
None => self.held.clear_refusal(),
}
}
/// Sets the named presets the dialog's presets row lists (`ParamDialog::presets`): the rows, the values each
/// applies and the built-in names, which `check_name` refuses.
pub fn set_presets(&mut self, rows: Vec<PresetRow<String>>, values: Vec<(String, DialogFields)>, built_in: Vec<String>) {
let _ = (self, rows, values, built_in);
todo!("ex.E4")
self.presets = Some(HeldPresets { rows, values, built_in });
}
/// The preset edits of the last pass (Create, Rename, Delete), once.
pub fn take_preset_events(&mut self) -> Vec<NamedPresetEvent<String>> {
let _ = self;
todo!("ex.E4")
std::mem::take(&mut self.preset_events)
}
/// Whether an Escape ended a row's sampling in the last pass, once; the next Escape cancels as usual.
pub fn take_sampling_ended(&mut self) -> bool {
let _ = self;
todo!("ap.AP11")
self.requests.take_sampling_ended()
}
/// The help link a row's button reported in the last pass, once.
pub fn take_help_link(&mut self) -> Option<String> {
let _ = self;
todo!("wg.W25")
self.requests.take_help_link()
}
/// The answer OK would give with the values now, and whether the dialog lets OK be pressed.
fn current_result(&mut self) -> (ParamResult, bool) {
let ParamDialog { key, params, remember, remember_for, ok_enabled, .. } = (self.build)(&mut self.fields);
let params = params.into_owned();
let mut result = ParamDialog::result(key, &params, remember, remember_for, self.fields.clone());
result.id = self.id;
(result, ok_enabled)
}
/// Holds `result` for the host: the OK of a held dialog, from the button or from `confirm`.
@@ -1232,12 +1331,20 @@ impl StackDialog for HostedParamDialog {
.hold_ok(self.hold)
.finish_held(finish)
.preview_colors(self.requests.previewed_colors().to_vec());
let blocks = self.held.refusal_blocks();
if let Some((reason, refused)) = self.held.refusal() {
dialog = dialog.refusal((reason.clone(), refused.fields.clone()));
// A refusal the host keeps shows whatever the values are; the other until a value changes.
dialog = dialog.refusal((reason.clone(), refused.fields.clone())).refusal_blocks(blocks);
if blocks {
dialog = dialog.ok_enabled(false).ok_reason(reason.clone());
}
}
if let Some(point) = centre {
dialog = dialog.centre_on(point);
}
if let Some(presets) = &self.presets {
dialog = dialog.presets(ParamPresets { rows: &presets.rows, values: &presets.values, built_in: &presets.built_in });
}
// OK waits for the host's answer: a second OK cannot file over the held one.
if self.held.is_waiting() {
dialog = dialog.ok_enabled(false);
@@ -1261,7 +1368,8 @@ impl StackDialog for HostedParamDialog {
self.requests.request_footer_action(action);
}
self.shown = ShownState { comparing: shown.comparing, centre: shown.preview_centre };
if self.held.refusal().is_some_and(|(_, refused)| refused.fields != self.fields) {
self.preset_events.extend(shown.presets);
if !blocks && self.held.refusal().is_some_and(|(_, refused)| refused.fields != self.fields) {
self.held.clear_refusal();
}
if let Some(result) = shown.held {
@@ -1299,20 +1407,45 @@ impl StackDialog for HostedParamDialog {
}
/// Sets the fields on a clone of the values and commits the clone only when every field is accepted.
fn set_json_fields(&mut self, ctx: &Context, fields: &[(String, Value)]) -> Result<(), String> {
let _ = (ctx, fields);
todo!("sh.K25")
fn set_json_fields(&mut self, _: &Context, fields: &[(String, Value)]) -> Result<(), String> {
let params = (self.build)(&mut self.fields).params.into_owned();
let mut staged = self.fields.clone();
let mut preview = self.preview_on;
for (field, value) in fields {
match (field.as_str(), &self.presets) {
("preview", _) if self.previews => {
preview = value.as_bool().ok_or_else(|| FieldRefusal::Rejects(value).message(field))?;
}
("preset", Some(presets)) => {
let preset = value.as_str().and_then(|name| presets.values.iter().find(|(preset, _)| preset == name));
let (_, preset) = preset.ok_or_else(|| FieldRefusal::Rejects(value).message(field))?;
apply_preset(preset, &mut staged);
}
_ => set_param_field(&params, &mut staged, field, value.clone())?,
}
}
for param in params.iter().filter(|param| matches!(param.kind, ParamKind::Files { .. })) {
if let Some(request) = param.listing_after(&self.fields, &staged) {
self.requests.request_listing(request);
}
}
self.fields = staged;
self.preview_on = preview;
Ok(())
}
/// Whether the Reset footer's restore would change the values.
fn can_reset(&self) -> bool {
todo!("wg.W26")
self.fields != self.opening
}
/// Runs the restore the Reset footer runs.
fn reset(&mut self, ctx: &Context) -> bool {
let _ = ctx;
todo!("wg.W26")
/// Runs the restore the Reset footer runs: the opening values with `reset_to` over them.
fn reset(&mut self, _: &Context) -> bool {
let reset_to = (self.build)(&mut self.fields).reset_to;
let target = reset_target(&self.opening, reset_to.as_ref());
let changed = self.fields != target;
self.fields = target;
changed
}
/// Answers OK as the button does: none while OK is disabled. The result keeps what a remembering dialog saves. A
@@ -1325,37 +1458,37 @@ impl StackDialog for HostedParamDialog {
if self.held.is_waiting() {
return None;
}
let ParamDialog { key, params, remember, remember_for, ok_enabled, .. } = (self.build)(&mut self.fields);
let (result, ok_enabled) = self.current_result();
if !ok_enabled {
return None;
}
let params = params.into_owned();
let mut result = ParamDialog::result(key, &params, remember, remember_for, 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.
/// The values by parameter key, as [`DialogFields`] serializes them, with the Preview check box under `preview`
/// for a dialog that previews and the preset the values equal under `preset` for one with presets.
fn json_fields(&self) -> Option<Value> {
serde_json::to_value(&self.fields).ok()
let mut fields = serde_json::to_value(&self.fields).ok()?;
if let Some(map) = fields.as_object_mut() {
if self.previews {
map.insert("preview".to_owned(), Value::Bool(self.preview_on));
}
if let Some(presets) = &self.presets {
let current = presets.values.iter().find(|(_, preset)| preset_applies(preset, &self.fields));
map.insert("preset".to_owned(), current.map_or(Value::Null, |(name, _)| Value::String(name.clone())));
}
}
Some(fields)
}
/// 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, _: &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(&params, &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);
}
}
Ok(())
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
self.set_json_fields(ctx, &[(field.to_owned(), value)])
}
/// Shows a child picker's live colour in the colour row `key`, as [`HostedParamDialog::preview_color`] does.
@@ -1,10 +1,11 @@
//! Stories of `ParamDialog`.
use super::{HostedParamDialog, ParamDialog, ParamLayout};
use super::{HostedParamDialog, ParamDialog, ParamLayout, ParamPresets};
use crate::contract::Bind;
use crate::dialog::StackDialog as _;
use crate::dialog::stories::hosted_with;
use crate::patterns::form_dialogs::{DialogFields, Param};
use crate::patterns::form_dialogs::{DialogFields, Param, ParamKind};
use crate::patterns::presets::PresetRow;
use crate::primitives::TextureCache;
use crate::runtime::env::Label;
use crate::sections::{DialogRole, FooterButton};
@@ -82,7 +83,7 @@ fn param_dialog_with_footer_buttons(ui: &mut Ui, data: &mut StoryData) -> StoryO
.extra_buttons(vec![
("load".to_owned(), FooterButton::new(Label::from("Load…"), DialogRole::Other)),
("save".to_owned(), FooterButton::new(Label::from("Save…"), DialogRole::Other)),
]) // P3(forms-w1): q337
])
.footer_note("About 1.2 MB")
.show(ui)
.into()
@@ -113,6 +114,54 @@ fn hosted_param_dialog_with_a_refused_ok(ui: &mut Ui, data: &mut StoryData) -> S
})
}
/// The open state of a story's dialog, which starts closed: a button opens it.
fn opener<'d>(ui: &mut Ui, data: &'d mut StoryData) -> &'d mut bool {
let open = data.value("open", false);
if ui.button("Open").clicked() {
*open = true;
}
open
}
/// A footer toggle: a `Bool` row drawn as a footer button that shows its on label while on.
#[story(ParamDialog<'static>, covers = [], drive = Drive::Never)]
fn param_dialog_with_a_footer_toggle(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let params = vec![
Param::new("radius", "Radius", ParamKind::range(0.0, 100.0, 10.0, Default::default())),
Param::new("grid", "Show Grid", ParamKind::bool(false)).in_footer("Hide Grid"),
];
ParamDialog::new("grid", "Grid", params).opened(Bind::bound(opener(ui, data))).show(ui).into()
}
/// A named presets row above the rows.
#[story(ParamDialog<'static>, covers = [], drive = Drive::Never)]
fn param_dialog_with_presets(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let rows = [PresetRow::item("soft".to_owned(), "Soft", 0), PresetRow::item("hard".to_owned(), "Hard", 0)];
let values = [
("soft".to_owned(), DialogFields::from_pairs([("radius", 2.0)])),
("hard".to_owned(), DialogFields::from_pairs([("radius", 60.0)])),
];
let built_in = ["soft".to_owned()];
ParamDialog::new("blur", "Blur", Param::parse_list(SPEC))
.opened(Bind::bound(opener(ui, data)))
.presets(ParamPresets { rows: &rows, values: &values, built_in: &built_in })
.show(ui)
.into()
}
/// A dialog whose OK is refused with a reason: OK is off and the reason shows under the rows.
#[story(ParamDialog<'static>, covers = [], drive = Drive::Never)]
fn param_dialog_with_refused_values(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
ParamDialog::new("blur", "Blur", Param::parse_list(SPEC))
.opened(Bind::bound(opener(ui, data)))
.ok_enabled(false)
.ok_reason(Label::from(REFUSAL))
.refusal((Label::from(REFUSAL), DialogFields::new()))
.refusal_blocks(true)
.show(ui)
.into()
}
#[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()
@@ -39,6 +39,7 @@ pub struct HostRequests {
preview_click: Option<Pos2>,
footer_action: Option<String>,
help_link: Option<String>,
sampling_ended: bool,
/// The previewed colour of each colour row a child picker edits, by row key; one entry per key.
previews: Vec<(String, Srgba)>,
answers: Vec<HostAnswer>,
@@ -67,6 +68,7 @@ impl HostRequests {
if let Some(link) = rows.help_link.take() {
self.help_link = Some(link);
}
self.sampling_ended |= std::mem::take(&mut rows.sampling_ended);
}
/// The help link a row's button reported, once.
@@ -74,6 +76,11 @@ impl HostRequests {
self.help_link.take()
}
/// Whether an Escape ended a row's sampling since the last call, once.
pub fn take_sampling_ended(&mut self) -> bool {
std::mem::take(&mut self.sampling_ended)
}
/// Files a colour request; it replaces one not taken yet.
pub fn request_color(&mut self, request: ColorRequest) {
self.color = Some(request);
@@ -138,7 +145,8 @@ 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, listing, preview_click, footer_action, help_link, previews, answers } = other;
let HostRequests { color, path, eyedropper, listing, preview_click, footer_action, help_link, sampling_ended, previews, answers } = other;
self.sampling_ended |= sampling_ended;
self.help_link = help_link.or(self.help_link.take());
self.color = color.or(self.color.take());
self.path = path.or(self.path.take());
@@ -55,6 +55,7 @@ pub use sizing::{
mod new_document;
// PLAN: decisions.md (files-2) asks for a `RasterMemory` re-export here; the type exists in no tree of this set, so files-w3 adds it with its definition.
pub use new_document::{
BACKGROUND_COLOR_KEY, BackgroundContents, BitDepth, CardCx, CardSource, ColorMode, ColorProfiles, DetailsCx, DocumentCard, DocumentOptions,
DocumentPreset, DocumentSettings, HostedNewDocument, NewDocumentDialog, NewDocumentOutput, NewDocumentPresetWords, NewDocumentResult,
@@ -11,7 +11,7 @@ use crate::runtime::env::{Label, LengthUnits, UnitKind};
use crate::runtime::requests::{ColorRequest, EyedropperRequest, ListingRequest, PathKind};
use crate::text::StepArrows;
use crate::value_drag::SliderScale;
use craft_behavior::{EditEvents, NumberCodec};
use craft_behavior::{CancelReason, EditEvent, EditEvents, GestureId, GesturePhase, NumberCodec};
use craft_host::PickRequest;
use craft_theme::Srgba;
use egui::{Response, Ui};
@@ -219,8 +219,8 @@ impl ParamKind {
/// A group of radio buttons whose options each carry a detail line: `(id, label, detail)`.
pub fn radio_with_details(options: Vec<(String, Label, Label)>, default: Option<String>) -> Self {
let _ = (options, default);
todo!("co.K27")
let (options, details) = options.into_iter().map(|(id, label, detail)| ((id, label), detail)).unzip();
ParamKind::Radio { options, default, details }
}
/// An angle dial with its field: one turn, -180 to 180, to a tenth of a degree.
@@ -286,7 +286,6 @@ impl ParamKind {
ParamKind::Int { default, .. } => FieldValue::Int(*default),
ParamKind::Number { default, .. } => FieldValue::Number(*default),
ParamKind::Bool { default } => FieldValue::Bool(*default),
// P3(forms-w1): co.K27
ParamKind::Choice { options, default } | ParamKind::Radio { options, default, .. } => {
let initial = default.as_deref().or_else(|| options.first().map(|(id, _)| id.as_str()));
FieldValue::Text(initial.unwrap_or_default().to_owned())
@@ -403,12 +402,32 @@ pub struct CustomContext {
canvas: Option<egui::Id>,
eyedropper: Option<EyedropperRequest>,
sampling: bool,
/// Whether an Escape ended sampling in the previous pass.
sampling_ended: bool,
/// The gesture steps the row's controls reported ([`CustomContext::gesture`]).
gestures: Vec<Lifted>,
}
/// One edit event of a custom row's control with its value erased.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Lifted {
/// The gesture, `None` for a one-step set.
pub(crate) id: Option<GestureId>,
/// Where the gesture stands, `None` for a set.
pub(crate) phase: Option<GesturePhase>,
/// Why a cancel ended it.
pub(crate) reason: Option<CancelReason>,
}
impl CustomContext {
/// The context of a row labelled `title`.
pub(crate) fn new(title: Label, canvas: Option<egui::Id>) -> Self {
CustomContext { title, request: None, canvas, eyedropper: None, sampling: false }
/// The context of a row labelled `title`; `sampling_ended` says an Escape ended sampling in the previous pass.
pub(crate) fn new(title: Label, canvas: Option<egui::Id>, sampling_ended: bool) -> Self {
CustomContext { title, request: None, canvas, eyedropper: None, sampling: false, sampling_ended, gestures: Vec::new() }
}
/// The gesture steps the row reported, once.
pub(crate) fn take_gestures(&mut self) -> Vec<Lifted> {
std::mem::take(&mut self.gestures)
}
/// Asks the host to run the action `id`; the host takes this pass's requests once with
@@ -425,8 +444,7 @@ impl CustomContext {
/// Whether an Escape ended the row's sampling in the previous pass (the dialog claims Escape while a row samples).
pub fn sampling_ended(&self) -> bool {
let _ = self;
todo!("ap.AP11")
self.sampling_ended
}
/// Whether the row's dropper samples now: `true` while the row wants canvas presses to pick colours.
@@ -437,8 +455,14 @@ impl CustomContext {
/// Hands a custom row's control events to the rows, which lift them as a value row's: each event's gesture id,
/// phase and cancel reason, type-erased.
pub fn gesture<T>(&mut self, events: &EditEvents<T>) {
let _ = (self, events);
todo!("ef.F6")
self.gestures.extend(events.iter().map(|event| Lifted {
id: event.id(),
phase: event.phase(),
reason: match event {
EditEvent::Cancel { reason, .. } => Some(*reason),
_ => None,
},
}));
}
/// The canvas the dialog's rows work on (`ParamDialog::canvas`), when it has one.
@@ -500,7 +524,6 @@ pub(crate) struct RowOptions {
eyedropper_armed: bool,
full_width: bool,
/// The row or section stands beside the one before it ([`Param::beside`]).
#[allow(dead_code)] // P3(forms-w1): od.OD5
beside: bool,
not_remembered: bool,
/// The lines a multi-line text row shows.
@@ -512,14 +535,83 @@ pub(crate) struct RowOptions {
searchable: bool,
/// The keys a change of the row's value removes ([`Param::resets`]).
resets: Vec<String>,
/// How a section head draws ([`Param::group`], [`Param::section_check`]).
head: Head,
/// The row's label shows a reset dot ([`Param::resettable`]).
resettable: bool,
/// The label a footer row shows while on ([`Param::in_footer`]).
footer_on: Option<Label>,
/// The lengths a number row keeps and shows ([`Param::length`]).
length: Option<LengthUnits>,
/// The codec a number row reads and writes with ([`Param::codec`]).
codec: Option<NumberCodec>,
/// The step arrows of a number row's field.
step_arrows: Option<StepArrows>,
/// The labelled marks of a range row's slider.
marks: Vec<(f64, Label)>,
/// The link the row's help button reports ([`Param::help_link`]).
help_link: Option<String>,
}
/// How a section head draws: a fixed title, a disclosure over its rows, or a check box that switches its rows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Head {
/// A title over a rule.
#[default]
Fixed,
/// A title that opens and closes the rows.
Group {
/// Whether the disclosure starts open.
open: bool,
},
/// A check box over the rows, which take input only while it is checked.
Check,
}
impl RowOptions {
/// Whether the row or section stands beside the one before it.
#[allow(dead_code)] // P3(forms-w1): od.OD5
pub(crate) fn beside(&self) -> bool {
let _ = self;
todo!("od.OD5")
self.beside
}
/// How a section head draws.
pub(crate) fn head(&self) -> Head {
self.head
}
/// Whether the row's label shows a reset dot.
pub(crate) fn resettable(&self) -> bool {
self.resettable
}
/// The label a footer row shows while on; `Some` for a row drawn in the footer.
pub(crate) fn footer_on(&self) -> Option<&Label> {
self.footer_on.as_ref()
}
/// The lengths a number row keeps and shows.
pub(crate) fn length(&self) -> Option<LengthUnits> {
self.length
}
/// The codec a number row reads and writes with.
pub(crate) fn codec(&self) -> Option<&NumberCodec> {
self.codec.as_ref()
}
/// The step arrows of a number row's field.
pub(crate) fn step_arrows(&self) -> Option<StepArrows> {
self.step_arrows
}
/// The labelled marks of a range row's slider.
pub(crate) fn marks(&self) -> &[(f64, Label)] {
&self.marks
}
/// The link the row's help button reports.
pub(crate) fn help_link(&self) -> Option<&str> {
self.help_link.as_deref()
}
}
@@ -761,80 +853,94 @@ impl Param {
/// A section head that is a check box: it holds a `Bool` under `key`, and its rows take input only while it is
/// checked.
pub fn section_check(key: impl Into<String>, label: impl Into<Label>, default: bool) -> Self {
let _ = (key, label, default);
todo!("od.OD6")
let mut head = Self::new(key, label, ParamKind::Bool { default });
head.options.get_or_insert_default().head = Head::Check;
head
}
/// A section head whose title is a disclosure, open by default: its rows hide while it is closed and keep their
/// values.
pub fn group(label: impl Into<Label>) -> Self {
let _ = label;
todo!("wg.W24")
let mut head = Self::section(label);
head.options.get_or_insert_default().head = Head::Group { open: true };
head
}
/// Binds the row's control to the value's reset (`Bind::given(value).reset(default)`) and shows the label's reset
/// dot while the value differs from the default.
#[must_use]
pub fn resettable(self) -> Self {
let _ = self;
todo!("ef.F2")
pub fn resettable(mut self) -> Self {
self.options.get_or_insert_default().resettable = true;
self
}
/// On a [`Param::group`]: whether its disclosure starts open (the default is open).
#[must_use]
pub fn initially_open(self, on: bool) -> Self {
let _ = (self, on);
todo!("ef.F3")
pub fn initially_open(mut self, on: bool) -> Self {
if let Some(Head::Group { open }) = self.options.as_deref_mut().map(|options| &mut options.head) {
*open = on;
}
self
}
/// Draws a `Bool` row as a footer button that shows the row's label while off and `on_label` while on; a press
/// flips the value and the dialog stays open.
#[must_use]
pub fn in_footer(self, on_label: impl Into<Label>) -> Self {
let _ = (self, on_label);
todo!("ex.E1")
pub fn in_footer(mut self, on_label: impl Into<Label>) -> Self {
self.options.get_or_insert_default().footer_on = Some(on_label.into());
self
}
/// The row or section stands beside the one before it; the pair falls under when the form lacks room.
/// The row or section stands beside the one before it; the pair falls under when the form lacks room. A custom
/// row beside its section's rows spans its width, as [`full_width`](Param::full_width) does.
#[must_use]
pub fn beside(self) -> Self {
let _ = self;
todo!("od.OD5")
pub fn beside(mut self) -> Self {
let custom = matches!(self.kind, ParamKind::Custom(_));
let options = self.options.get_or_insert_default();
options.beside = true;
options.full_width |= custom;
self
}
/// Draws a `Number` row as a length: the stored unit in the binding, the shown unit in the field.
#[must_use]
pub fn length(self, lengths: LengthUnits) -> Self {
let _ = (self, lengths);
todo!("wg.W21")
pub fn length(mut self, lengths: LengthUnits) -> Self {
self.options.get_or_insert_default().length = Some(lengths);
self
}
/// Sets the `Number` row's codec.
#[must_use]
pub fn codec(self, codec: NumberCodec) -> Self {
let _ = (self, codec);
todo!("wg.W21")
pub fn codec(mut self, codec: NumberCodec) -> Self {
self.options.get_or_insert_default().codec = Some(codec);
self
}
/// Passes `arrows` to the `Number` row's field.
#[must_use]
pub fn step_arrows(self, arrows: StepArrows) -> Self {
let _ = (self, arrows);
todo!("wg.W22")
pub fn step_arrows(mut self, arrows: StepArrows) -> Self {
self.options.get_or_insert_default().step_arrows = Some(arrows);
self
}
/// Passes labelled `marks` to the `Range` row's slider.
#[must_use]
pub fn marks_labelled<L: Into<Label>>(self, marks: impl IntoIterator<Item = (f64, L)>) -> Self {
let _ = (self, marks);
todo!("wg.W22")
pub fn marks_labelled<L: Into<Label>>(mut self, marks: impl IntoIterator<Item = (f64, L)>) -> Self {
self.options.get_or_insert_default().marks = marks.into_iter().map(|(at, label)| (at, label.into())).collect();
self
}
/// Adds an icon button after the row's control that reports `link` as the help link; a press opens nothing.
#[must_use]
pub fn help_link(self, link: impl Into<String>) -> Self {
let _ = (self, link);
todo!("wg.W23")
pub fn help_link(mut self, link: impl Into<String>) -> Self {
self.options.get_or_insert_default().help_link = Some(link.into());
self
}
/// Whether the row starts a section: a section head, or a check head ([`Param::section_check`]).
pub(crate) fn is_head(&self) -> bool {
// A section head and a check head are the two rows that open a section.
matches!(self.kind, ParamKind::Section) || matches!(self.options.as_deref(), Some(options) if options.head == Head::Check)
}
/// A number row with a unit menu after the field. `base` is the value in base units; the field shows
@@ -889,16 +995,15 @@ impl Param {
/// otherwise it takes no space. Its value stays in the fields and in the result.
#[must_use]
pub fn visible_when(mut self, key: impl Into<String>, value: impl Into<FieldValue>) -> Self {
self.visible_when.push((key.into(), vec![value.into()])); // P3(forms-w1): od.OD4
self
self.visible_when_in(key, [value])
}
/// The row is shown only while `fields[key]` is one of `values`; the one-value case is
/// [`visible_when`](Param::visible_when).
/// The row is shown only while `fields[key]` is one of `values`, besides the conditions it already has; the
/// one-value case is [`visible_when`](Param::visible_when).
#[must_use]
pub fn visible_when_in(self, key: impl Into<String>, values: impl IntoIterator<Item = impl Into<FieldValue>>) -> Self {
let _ = (self, key, values);
todo!("od.OD4")
pub fn visible_when_in(mut self, key: impl Into<String>, values: impl IntoIterator<Item = impl Into<FieldValue>>) -> Self {
self.visible_when.push((key.into(), values.into_iter().map(Into::into).collect()));
self
}
/// The row takes input only while `fields[key]` equals `value`; otherwise it is shown disabled. The one-value case
@@ -1034,6 +1139,11 @@ impl Param {
self.texts.as_deref()?.tooltip.as_ref()
}
/// The label a [`Param::in_footer`] row shows while on; `None` for a row in the body.
pub(crate) fn footer_on(&self) -> Option<Label> {
self.options.as_deref()?.footer_on.clone()
}
/// Whether the row's value is saved with the form.
pub fn is_remembered(&self) -> bool {
!self.option().not_remembered
@@ -1096,7 +1206,6 @@ impl Param {
/// Whether the row is shown with `fields`.
pub fn visible(&self, fields: &DialogFields) -> bool {
// P3(forms-w1): od.OD4
self.visible_when.iter().all(|(key, values)| fields.get(key).is_some_and(|held| values.contains(held)))
}
@@ -1203,10 +1312,12 @@ pub fn open_fields(params: &[Param], fields: &mut DialogFields) {
fields.snapshot();
}
/// Fills the keys `params` have defaults for and `fields` lack, including the unit key of a row with units.
/// Fills the keys `params` have defaults for and `fields` lack, including the unit key of a row with units. A key
/// marked mixed stays absent: its row shows it blank.
pub(crate) fn fill_defaults(params: &[Param], fields: &mut DialogFields) {
for param in params {
if !fields.contains(&param.key)
&& !fields.is_mixed(&param.key)
&& let Some(value) = param.default_value()
{
fields.set(param.key.as_str(), value);
@@ -7,13 +7,14 @@ use crate::patterns::presets::{PresetKind, PresetPicker, PresetRow};
use crate::runtime::commands::{CommandState, Commands as _};
use crate::runtime::requests::{ColorRequest, EyedropperRequest, ListingRequest, PathRequest};
use super::param::{CustomContext, Param, ParamKind, fill_defaults, path_list, rounded};
use super::param::{CustomContext, Head, Lifted, Param, ParamKind, fill_defaults, path_list, rounded};
use super::path_row::PathRow;
use super::words::ParamWords;
use crate::buttons::{Button, ToggleButton};
use crate::choice::{Checkbox, Radio, RadioGroup, Swatch};
use crate::contract::{
Bind, BodyCx, CanvasGesture, Entry, NoValue, Outcome, Props as _, Remember as _, Sampler as _, Show as _, ShowContainer as _, clicked,
Bind, BodyCx, CanvasGesture, Entry, FieldLayout, NoValue, Outcome, Props as _, Remember as _, Sampler as _, Show as _, ShowContainer as _,
SideLabel, clicked,
};
use crate::form::{Field, FieldGroup, SliderField, SliderFieldLayout};
@@ -28,11 +29,13 @@ use crate::text::{NumberField, RangeAlert, SelectableText, TextField};
use crate::value_drag::{AngleDial, PointPicker, SliderScale};
use craft_behavior::{EditEvent, EditEvents, IconId, Mixed, NumberCodec};
use craft_behavior::{CancelReason, EditEvent, EditEvents, GesturePhase, IconId, Mixed, NumberCodec};
use craft_host::PickRequest;
use craft_keymap::{Chord, Key};
use craft_theme::Srgba;
use egui::{Id, Response, Ui};
use std::cell::Cell;
use std::collections::BTreeMap;
use std::ops::RangeInclusive;
use std::path::PathBuf;
@@ -49,6 +52,8 @@ const PERCENT: RangeInclusive<f64> = 0.0..=100.0;
const RANDOM_HIGH: i64 = i32::MAX as i64;
/// The first state of the Random button's sequence when the caller gives no seed.
const SEED_START: u64 = 0x9E37_79B9_7F4A_7C15;
/// The chord that ends a row's sampling: held by the rows while one samples, so the dialog does not cancel.
const ESCAPE: Chord = Chord::plain(Key::Escape);
/// What a [`ParamRows`] reports.
#[derive(Debug)]
@@ -81,6 +86,8 @@ pub struct ParamRowsOutput {
pub unparsed: bool,
/// The help link a row's button (`Param::help_link`) reported in this pass.
pub help_link: Option<String>,
/// An Escape ended a row's sampling in this pass: the dialog stays open, and the next Escape cancels as usual.
pub sampling_ended: bool,
}
impl Outcome for ParamRowsOutput {
@@ -205,15 +212,30 @@ impl<'a> ParamRows<'a> {
pass.blend_keys(cx, params);
}
pass.rows(ui, params);
if let Some(canvas) = canvas.filter(|_| pass.sampling && !read_only) {
// While a row samples the rows hold Escape from every component, renewed each pass; the held press is
// consumed here, so a second pass of the frame ends nothing new. The capture lapses once sampling stops.
let escaped = pass.sampling && !read_only && !ui.is_sizing_pass() && {
crate::runtime::keys::capture(ui.ctx(), cx.id, ESCAPE);
crate::runtime::keys::take_claimed(ui.ctx(), cx.id, ESCAPE)
};
if escaped {
pass.memo.armed = None;
pass.memo.ended = true;
pass.sampling_ended = true;
}
if let Some(canvas) = canvas.filter(|_| pass.sampling && !escaped && !read_only) {
cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY);
}
*cx.keep::<Memo>() = pass.memo.clone();
changed = pass.work != filled;
values = (pass.work != before).then(|| pass.work.clone());
if let Some(after) = &values {
let event = EditEvent::set(Mixed::Same(before), after.clone(), name.clone(), None);
let event = EditEvent::set(Mixed::Same(before.clone()), after.clone(), name.clone(), None);
let _ = fields.reborrow().write(cx, &event);
// A gesture's own events stand for the edit; a change no control lifted is one set.
if pass.events.is_empty() {
pass.events.push(event);
}
}
if let (Some(bind), Some(next)) = (seed.as_mut(), pass.seed) {
let held = Mixed::Same(state.unwrap_or(SEED_START));
@@ -222,8 +244,11 @@ impl<'a> ParamRows<'a> {
})
};
let shown = if read_only { with_env(ui, |scope| scope.read_only = Some(true), group) } else { group(ui) };
let (pick_color, path, eyedropper, listing, out_of_range) =
if read_only { Default::default() } else { (pass.color, pass.path, pass.eyedropper, pass.listing, pass.out_of_range) };
let (pick_color, path, eyedropper, listing, out_of_range, help_link) = if read_only {
Default::default()
} else {
(pass.color, pass.path, pass.eyedropper, pass.listing, pass.out_of_range, pass.help_link)
};
ParamRowsOutput {
response: shown.output,
changed,
@@ -233,9 +258,10 @@ impl<'a> ParamRows<'a> {
eyedropper,
listing,
out_of_range,
events: EditEvents::default(),
unparsed: false,
help_link: None,
events: pass.events,
unparsed: pass.unparsed,
help_link,
sampling_ended: pass.sampling_ended,
}
}
}
@@ -253,6 +279,8 @@ struct Memo {
sequence: Option<u64>,
/// The selected file of each files row: the selection belongs to the list's view, not to the row's values.
selected: BTreeMap<String, PathBuf>,
/// An Escape ended sampling in the pass that kept this memo; the next pass tells its custom rows.
ended: bool,
}
/// One pass over the rows: the working values, what the rows ask of the host, and what the pass reads.
@@ -282,6 +310,20 @@ struct Pass<'p> {
previews: &'p [(String, Srgba)],
/// How range rows arrange their slider and number field (`ParamRows::sliders`).
sliders: SliderFieldLayout,
/// The pass's edits of the whole values, lifted from the rows' controls.
events: EditEvents<DialogFields>,
/// A number or length field holds text that does not parse.
unparsed: bool,
/// The help link a row's button reported.
help_link: Option<String>,
/// An Escape ended sampling in this pass.
sampling_ended: bool,
/// An Escape ended sampling in the previous pass.
ended_prev: bool,
/// The edits of the row being shown, until `lift` makes them edits of the whole values.
pending: EditEvents<FieldValue>,
/// The rows take no input: they stand under a check head that is off.
locked: bool,
}
/// A parameter as the pass shows it: its key, its label without the colon, and whether it takes input.
@@ -290,16 +332,48 @@ struct Line<'r> {
key: &'r str,
name: Label,
enabled: bool,
/// The key is marked mixed: the row shows it blank until an edit.
mixed: bool,
/// The row's help button was pressed in this pass.
helped: Cell<bool>,
}
impl Line<'_> {
/// Shows `body` in a field named by the row: its label beside the control, its tooltip over both.
/// Shows `body` in a field named by the row: its label beside the control, its tooltip over both, the reset dot
/// after the label of a resettable row.
fn show(&self, ui: &mut Ui, mut body: impl FnMut(&mut Ui)) {
let mut field = Field::new(self.name.clone()).id_salt(self.key).enabled(self.enabled);
if let Some(tip) = self.param.tooltip_text() {
field = field.tooltip(tip.clone());
}
field.show(ui, |ui, _| body(ui));
if self.param.option().resettable() {
field = field.side(SideLabel::new().reset_dot(true));
}
field.show(ui, |ui, _| match self.param.option().help_link() {
None => body(ui),
Some(_) => beside(ui, |ui| {
body(ui);
self.help_button(ui);
}),
});
}
/// The help button after a row's control: a press is noted for the pass, which reports the row's link.
fn help_button(&self, ui: &mut Ui) {
let help = Env::of(ui).words::<ParamWords>().help.clone();
if clicked(&Button::new(help).icon(IconId::new("help")).icon_only().id_salt("help").show(ui)) {
self.helped.set(true);
}
}
/// The binding of a control that shows `value` (blank while the key is mixed); a resettable row's carries the
/// row's default, which its reset dot restores.
fn bind<T: Clone + PartialEq + Send + Sync + 'static>(&self, value: T, default: Option<T>) -> Bind<'static, T> {
let bind = if self.mixed { Bind::given(Mixed::<T>::Mixed) } else { Bind::given(value) };
match default {
Some(default) if self.param.option().resettable() => bind.reset(default),
_ => bind,
}
}
/// Shows `body` across the form for a full-width row, without a label, or else beside the row's label.
@@ -331,15 +405,29 @@ impl<'p> Pass<'p> {
canvas,
previews: &[],
sliders: SliderFieldLayout::Inline,
events: EditEvents::new(),
unparsed: false,
help_link: None,
sampling_ended: false,
ended_prev: false,
pending: EditEvents::new(),
locked: false,
}
}
/// Starts a body run over `work`: the body may run more than once in a pass, and each run starts clean.
fn begin(&mut self, work: &DialogFields, seed: Option<u64>, memo: Memo) {
fn begin(&mut self, work: &DialogFields, seed: Option<u64>, mut memo: Memo) {
self.work = work.clone();
self.start = seed.or(memo.sequence).unwrap_or(SEED_START);
self.seed = None;
self.ended_prev = std::mem::take(&mut memo.ended);
self.memo = memo;
self.events = EditEvents::new();
self.unparsed = false;
self.help_link = None;
self.sampling_ended = false;
self.pending = EditEvents::new();
self.locked = false;
self.color = None;
self.path = None;
self.eyedropper = None;
@@ -383,36 +471,128 @@ impl<'p> Pass<'p> {
}
}
/// The rows of `params`: those before the first section, then each section with the rows up to the next.
/// The rows of `params`: those before the first head, then each section with the rows up to the next head.
fn rows(&mut self, ui: &mut Ui, params: &[Param]) {
let is_section = |param: &Param| matches!(param.kind, ParamKind::Section);
let first = params.iter().position(is_section).unwrap_or(params.len());
for param in &params[..first] {
self.row(ui, param);
}
let first = params.iter().position(Param::is_head).unwrap_or(params.len());
self.body(ui, &params[..first]);
let mut sections = Vec::new();
let mut rest = &params[first..];
while let Some((head, tail)) = rest.split_first() {
let end = tail.iter().position(is_section).unwrap_or(tail.len());
let end = tail.iter().position(Param::is_head).unwrap_or(tail.len());
let (body, after) = tail.split_at(end);
if head.visible(&self.work) {
Section::fixed(plain(&head.label)).id_salt(head.key.as_str()).show(ui, |ui, _| {
for param in body {
self.row(ui, param);
}
});
sections.push((head, body));
}
rest = after;
}
self.sides(ui, &sections, |(head, _)| head.option().beside(), |pass, ui, (head, body)| pass.section(ui, head, body));
}
/// The visible rows of `rows` that the body shows: a footer row is drawn by the dialog's footer.
fn shown<'a>(&self, rows: &'a [Param]) -> Vec<&'a Param> {
rows.iter().filter(|param| param.visible(&self.work) && param.footer_on().is_none()).collect()
}
/// The rows of one section.
fn body(&mut self, ui: &mut Ui, rows: &[Param]) {
let shown = self.shown(rows);
self.sides(ui, &shown, |param| param.option().beside(), |pass, ui, param| pass.row(ui, param));
}
/// Draws `items` in order with `draw`; an item that stands `beside` the one before it shares a wrapping row with
/// it, so the pair falls under when the room is short. Values and answers keep the order of `items`.
fn sides<T: Copy>(&mut self, ui: &mut Ui, items: &[T], beside: impl Fn(&T) -> bool, mut draw: impl FnMut(&mut Self, &mut Ui, T)) {
let mut at = 0;
while at < items.len() {
let end = at + 1 + items[at + 1..].iter().take_while(|item| beside(item)).count();
match &items[at..end] {
[one] => draw(self, ui, *one),
run => {
Row::new().wrap(true).id_salt(at).show(ui, |ui, _| {
for (place, item) in run.iter().enumerate() {
Stack::new().id_salt(place).show(ui, |ui, _| draw(self, ui, *item));
}
});
}
}
at = end;
}
}
/// One section: its head, then its rows.
fn section(&mut self, ui: &mut Ui, head: &Param, body: &[Param]) {
let title = plain(&head.label);
match head.option().head() {
Head::Fixed => {
Section::fixed(title).id_salt(head.key.as_str()).show(ui, |ui, _| self.body(ui, body));
}
Head::Group { open } => {
Section::new(title).initially_open(open).id_salt(head.key.as_str()).show(ui, |ui, _| self.body(ui, body));
}
Head::Check => {
Stack::new().id_salt(head.key.as_str()).show(ui, |ui, _| {
self.row(ui, head);
// The rows take input only while the head is checked.
let locked = self.locked;
self.locked |= !self.work.bool(&head.key).unwrap_or(false);
self.body(ui, body);
self.locked = locked;
});
}
}
}
/// `param` as the pass shows it.
fn line<'r>(&self, param: &'r Param) -> Line<'r> {
let key = param.key.as_str();
Line {
param,
key,
name: plain(&param.label),
enabled: param.enabled(&self.work) && !self.locked,
mixed: self.work.is_mixed(key),
helped: Cell::new(false),
}
}
fn row(&mut self, ui: &mut Ui, param: &Param) {
if !param.visible(&self.work) {
return;
}
let line = Line { param, key: param.key.as_str(), name: plain(&param.label), enabled: param.enabled(&self.work) };
let line = self.line(param);
let held = self.work.get(line.key).cloned();
self.show_row(ui, &line);
param.drop_dependents(held.as_ref(), &mut self.work);
self.lift(line.key, held);
if let Some(link) = param.option().help_link().filter(|_| line.helped.get()) {
self.help_link = Some(link.to_owned());
}
}
/// Notes the events of a control that edits one value, as edits of the whole values once the row has written it.
fn note<T: Clone>(&mut self, events: &EditEvents<T>, to: impl Fn(T) -> Option<FieldValue>) {
self.pending.extend(events.clone().filter_map(to));
}
/// Lifts the events the row's control noted to edits of the whole values: each carries the values around the
/// row's own, which stood at `held` before the row.
fn lift(&mut self, key: &str, held: Option<FieldValue>) {
let events = std::mem::take(&mut self.pending);
if events.is_empty() {
return;
}
let mut base = self.work.clone();
match held {
Some(held) => base.set(key, held),
None => {
base.remove(key);
}
}
self.events.extend(events.map(|value| {
let mut fields = base.clone();
fields.set(key, value);
fields
}));
}
/// Shows `line`'s control, chosen by its kind.
@@ -425,7 +605,7 @@ impl<'p> Pass<'p> {
ParamKind::Int { min, max, .. } => self.int(ui, line, *min, *max),
ParamKind::Bool { default } => self.check(ui, line, *default),
ParamKind::Choice { options, .. } => self.choice(ui, line, options),
ParamKind::Radio { options, .. } => self.radio_options(ui, line, options),
ParamKind::Radio { options, details, .. } => self.radio_options(ui, line, options, details),
ParamKind::Angle { default, min, max, decimals } => self.angle(ui, line, *default, *min..=*max, *decimals),
ParamKind::Color { .. } => self.color(ui, line),
ParamKind::Grid { cells, .. } => self.grid(ui, line, *cells),
@@ -452,13 +632,18 @@ impl<'p> Pass<'p> {
/// A range row: inline beside its label in the row's field, or stacked under its own caption across the form.
fn range(&mut self, ui: &mut Ui, line: &Line<'_>, range: RangeInclusive<f64>, scale: SliderScale) {
let value = self.work.number(line.key).unwrap_or(*range.start());
let places = line.param.option().range_places();
let option = line.param.option();
let places = option.range_places();
let layout = self.sliders;
let default = line.param.default_value().and_then(number_of);
let mut show = |ui: &mut Ui| {
let mut slider = SliderField::new(line.name.clone(), Bind::given(value), range.clone()).scale(scale).layout(layout);
let mut slider = SliderField::new(line.name.clone(), line.bind(value, default), range.clone()).scale(scale).layout(layout);
if let Some(places) = places {
slider = slider.step(10f64.powi(-(places as i32)));
}
if !option.marks().is_empty() {
slider = slider.marks_labelled(option.marks().iter().cloned());
}
if let Some(kind) = line.param.unit {
slider = slider.unit_kind(kind);
}
@@ -470,6 +655,8 @@ impl<'p> Pass<'p> {
}
let shown = slider.show(ui);
let value = shown.value().cloned();
self.unparsed |= shown.edit.unparsed;
self.note(&shown.edit.events, |v| Some(rounded(v, places)));
self.alert(shown.out_of_range);
if let Some(v) = value {
self.work.set(line.key, rounded(v, places));
@@ -483,13 +670,23 @@ impl<'p> Pass<'p> {
fn number(&mut self, ui: &mut Ui, line: &Line<'_>, range: Option<RangeInclusive<f64>>, step: f64, decimals: u32) {
let value = self.work.number(line.key).unwrap_or(0.0);
let option = line.param.option();
let default = line.param.default_value().and_then(number_of).map(Some);
line.show(ui, |ui| {
let mut field = number_field(self.units, line.name.clone(), Some(value), decimals, line.param.unit).step(step);
let mut field = match option.length() {
Some(lengths) => NumberField::length(line.name.clone(), line.bind(Some(value), default), lengths).step(step),
None => bound_field(self.units, line.name.clone(), line.bind(Some(value), default), decimals, line.param.unit, option.codec()).step(step),
};
if let Some(range) = range.clone() {
field = field.range(range);
}
if let Some(arrows) = option.step_arrows() {
field = field.step_arrows(arrows);
}
let shown = field.show(ui);
self.alert(shown.out_of_range);
self.unparsed |= shown.edit.unparsed;
self.note(&shown.edit.events, |v| v.map(FieldValue::Number));
if let Some(v) = shown.edit.value().cloned().flatten() {
self.work.set(line.key, FieldValue::Number(v));
}
@@ -510,7 +707,7 @@ impl<'p> Pass<'p> {
let unit_name = self.words.unit.clone();
if choices.is_shared() {
line.show(ui, |ui| {
let mut field = number_field(self.units, line.name.clone(), Some(base / factor), *decimals, Some(chosen.kind))
let mut field = bound_field(self.units, line.name.clone(), line.bind(Some(base / factor), None), *decimals, Some(chosen.kind), None)
.step(*step / factor)
.id_salt("field");
if let Some(range) = range.clone() {
@@ -518,6 +715,8 @@ impl<'p> Pass<'p> {
}
let shown = field.show(ui);
self.alert(shown.out_of_range);
self.unparsed |= shown.edit.unparsed;
self.note(&shown.edit.events, |v| v.map(|v| FieldValue::Number(v * factor)));
if let Some(v) = shown.edit.value().cloned().flatten() {
self.work.set(line.key, FieldValue::Number(v * factor));
}
@@ -525,7 +724,7 @@ impl<'p> Pass<'p> {
return;
}
line.show(ui, |ui| {
let mut field = UnitSelect::new(line.name.clone(), Bind::given(Some(base / factor)), Bind::given(chosen.kind), &entries)
let mut field = UnitSelect::new(line.name.clone(), line.bind(Some(base / factor), None), Bind::given(chosen.kind), &entries)
.unit_label(unit_name.clone())
.id_salt("field");
if let Some(range) = range.clone() {
@@ -533,6 +732,8 @@ impl<'p> Pass<'p> {
}
let shown = field.show(ui);
self.alert(shown.out_of_range);
self.unparsed |= shown.edit.unparsed;
self.note(&shown.edit.events, |v| v.map(|v| FieldValue::Number(v * factor)));
if let Some(v) = shown.edit.value().cloned().flatten() {
self.work.set(line.key, FieldValue::Number(v * factor));
}
@@ -547,14 +748,18 @@ impl<'p> Pass<'p> {
let value = self.work.int(line.key).unwrap_or(0);
let range = bounds(min.map(|m| m as f64), max.map(|m| m as f64));
let random = line.param.option().randomize();
let default = line.param.default_value().and_then(number_of).map(Some);
line.show(ui, |ui| {
beside(ui, |ui| {
let mut field = number_field(self.units, line.name.clone(), Some(value as f64), WHOLE, line.param.unit).id_salt("field");
let mut field = bound_field(self.units, line.name.clone(), line.bind(Some(value as f64), default), WHOLE, line.param.unit, None)
.id_salt("field");
if let Some(range) = range.clone() {
field = field.range(range);
}
let shown = field.show(ui);
self.alert(shown.out_of_range);
self.unparsed |= shown.edit.unparsed;
self.note(&shown.edit.events, |v| v.map(|v| FieldValue::Int(v.round() as i64)));
if let Some(v) = shown.edit.value().cloned().flatten() {
self.work.set(line.key, FieldValue::Int(v.round() as i64));
}
@@ -571,11 +776,13 @@ impl<'p> Pass<'p> {
fn check(&mut self, ui: &mut Ui, line: &Line<'_>, default: bool) {
let value = self.work.bool(line.key).unwrap_or(default);
let mut check = Checkbox::new(Bind::given(value)).label(line.name.clone()).id_salt(line.key).enabled(line.enabled);
let mut check = Checkbox::new(line.bind(value, Some(default))).label(line.name.clone()).id_salt(line.key).enabled(line.enabled);
if let Some(tip) = line.param.tooltip_text() {
check = check.tooltip(tip.clone());
}
if let Some(v) = check.show(ui).value().cloned() {
let shown = check.show(ui);
self.note(&shown.events, |v| Some(FieldValue::Bool(v)));
if let Some(v) = shown.value().cloned() {
self.work.set(line.key, FieldValue::Bool(v));
}
}
@@ -585,12 +792,15 @@ impl<'p> Pass<'p> {
let entries: Vec<Entry<String>> =
options.iter().map(|(id, label)| Entry::new(id.clone(), label.clone()).enabled(line.param.option_enabled(id))).collect();
let searchable = line.param.option().searchable();
let default = line.param.default_value().and_then(text_of);
line.show(ui, |ui| {
let mut select = Select::new(line.name.clone(), Bind::given(value.clone()), &entries);
let mut select = Select::new(line.name.clone(), line.bind(value.clone(), default.clone()), &entries);
if searchable {
select = select.searchable();
}
if let Some(v) = select.show(ui).value().cloned() {
let shown = select.show(ui);
self.note(&shown.events, |v| Some(FieldValue::Text(v)));
if let Some(v) = shown.value().cloned() {
self.work.set(line.key, FieldValue::Text(v));
}
});
@@ -609,7 +819,9 @@ impl<'p> Pass<'p> {
})
.collect();
line.show(ui, |ui| {
if let Some(v) = Select::new(line.name.clone(), Bind::given(value.clone()), &entries).show(ui).value().cloned() {
let shown = Select::new(line.name.clone(), line.bind(value.clone(), None), &entries).show(ui);
self.note(&shown.events, |v| Some(FieldValue::Text(v)));
if let Some(v) = shown.value().cloned() {
self.work.set(line.key, FieldValue::Text(v));
}
});
@@ -628,7 +840,8 @@ impl<'p> Pass<'p> {
.or_else(|| rows.iter().find(is_pattern))
.map(|row| row.key.clone());
// With no pattern to offer the row is disabled and writes nothing.
let line = Line { param: line.param, key: line.key, name: line.name.clone(), enabled: line.enabled && current.is_some() };
let enabled = line.enabled && current.is_some();
let line = Line { enabled, name: line.name.clone(), helped: Cell::new(false), ..*line };
line.show(ui, |ui| {
let picked = PresetPicker::pattern(line.name.clone(), Bind::given(current.clone()), rows, Bind::kept()).show(ui).picked;
if let Some(id) = picked.filter(|id| rows.iter().filter(is_pattern).any(|row| row.key == *id)) {
@@ -689,20 +902,32 @@ impl<'p> Pass<'p> {
}
/// A radio row is its own section: the title shows the row's name once, and the group it names follows.
fn radio_options(&mut self, ui: &mut Ui, line: &Line<'_>, options: &[(String, Label)]) {
let value = self.work.text(line.key).map(str::to_owned).or_else(|| line.param.kind.default_value().and_then(text_of)).unwrap_or_default();
fn radio_options(&mut self, ui: &mut Ui, line: &Line<'_>, options: &[(String, Label)], details: &[Label]) {
let default = line.param.kind.default_value().and_then(text_of);
let value = self.work.text(line.key).map(str::to_owned).or_else(|| default.clone()).unwrap_or_default();
Section::fixed(line.name.clone()).strength(HeaderStrength::Caption).id_salt(line.key).show(ui, |ui, _| {
let mut group = RadioGroup::new(line.name.clone(), Bind::given(value.clone())).enabled(line.enabled);
let mut group = RadioGroup::new(line.name.clone(), line.bind(value.clone(), default.clone())).enabled(line.enabled);
if let Some(tip) = line.param.tooltip_text() {
group = group.tooltip(tip.clone());
}
let group = group.show(ui, |ui, _| {
let group = group.show(ui, |ui, cx| {
Stack::new().show(ui, |ui, _| {
for (id, label) in options {
Radio::new(id.clone()).label(label.clone()).enabled(line.param.option_enabled(id) && line.enabled).show(ui);
for (at, (id, label)) in options.iter().enumerate() {
let radio = Radio::new(id.clone()).enabled(line.param.option_enabled(id) && line.enabled);
match details.get(at) {
// An option with a detail line draws it under its label through the body's label step.
Some(detail) => {
let side = SideLabel::new().layout(FieldLayout::After).detail(detail.clone());
cx.labelled(ui, id, label.clone(), side, radio);
}
None => {
radio.label(label.clone()).show(ui);
}
}
}
});
});
self.note(&group.output.events, |v| Some(FieldValue::Text(v)));
if let Some(v) = group.output.value().cloned() {
self.work.set(line.key, FieldValue::Text(v));
}
@@ -714,15 +939,19 @@ impl<'p> Pass<'p> {
fn angle(&mut self, ui: &mut Ui, line: &Line<'_>, default: f64, range: std::ops::RangeInclusive<f64>, decimals: u32) {
let value = self.work.number(line.key).unwrap_or(default);
let field_name = Label::from(self.words.angle_field.fill(&[("name", line.name.as_str())]));
let default = Some(default);
line.show(ui, |ui| {
beside(ui, |ui| {
let dial = AngleDial::new(Bind::given(value)).label(line.name.clone()).range(range.clone()).id_salt("dial").show(ui);
let field = number_field(self.units, field_name.clone(), Some(value), decimals, Some(UnitKind::Degrees))
let dial = AngleDial::new(line.bind(value, default)).label(line.name.clone()).range(range.clone()).id_salt("dial").show(ui);
let field = bound_field(self.units, field_name.clone(), line.bind(Some(value), default.map(Some)), decimals, Some(UnitKind::Degrees), None)
.range(range.clone())
.commit_decimals(decimals as usize)
.id_salt("field");
let shown = field.show(ui);
self.alert(shown.out_of_range);
self.unparsed |= shown.edit.unparsed;
self.note(&dial.events, |v| Some(FieldValue::Number(v)));
self.note(&shown.edit.events, |v| v.map(FieldValue::Number));
let typed = shown.edit.value().cloned().flatten();
if let Some(v) = dial.value().cloned().or(typed) {
self.work.set(line.key, FieldValue::Number(v));
@@ -794,7 +1023,9 @@ impl<'p> Pass<'p> {
("column", (column + 1).to_string().as_str()),
]);
let cell = number_field(self.units, Label::from(name), Some(cells[at] as f64), WHOLE, None).id_salt(at);
if let Some(v) = cell.show(ui).edit.value().cloned().flatten() {
let shown = cell.show(ui);
self.unparsed |= shown.edit.unparsed;
if let Some(v) = shown.edit.value().cloned().flatten() {
next[at] = v.round() as i64;
}
}
@@ -825,6 +1056,7 @@ impl<'p> Pass<'p> {
let field = number_field(self.units, name.clone(), Some(point[axis]), 1, Some(UnitKind::Percent)).range(PERCENT).id_salt(axis);
let shown = field.show(ui);
self.alert(shown.out_of_range);
self.unparsed |= shown.edit.unparsed;
if let Some(v) = shown.edit.value().cloned().flatten() {
next[axis] = v;
}
@@ -840,7 +1072,8 @@ impl<'p> Pass<'p> {
let value = self.work.int(line.key).and_then(|i| usize::try_from(i).ok()).unwrap_or(default);
let entries: Vec<Entry<usize>> = names.iter().enumerate().map(|(i, name)| Entry::new(i, Label::from(name.clone()))).collect();
line.show(ui, |ui| {
if let Some(v) = Select::new(line.name.clone(), Bind::given(value), &entries).show(ui).value().cloned() {
let shown = Select::new(line.name.clone(), line.bind(value, None), &entries).show(ui);
if let Some(v) = shown.value().cloned() {
self.work.set(line.key, FieldValue::Int(i64::try_from(v).unwrap_or(0)));
}
});
@@ -863,7 +1096,7 @@ impl<'p> Pass<'p> {
shown.edit.value().cloned()
}
None => {
let mut field = TextField::new(line.name.clone(), Bind::given(value.clone())).id_salt("text");
let mut field = TextField::new(line.name.clone(), line.bind(value.clone(), Some(default.to_owned()))).id_salt("text");
if let Some(lines) = line.param.option().lines() {
field = field.lines(lines);
}
@@ -899,6 +1132,7 @@ impl<'p> Pass<'p> {
let field = field.id_salt("field").enabled(self.work.number(line.key).is_some());
let shown = field.show(ui);
self.alert(shown.out_of_range);
self.unparsed |= shown.edit.unparsed;
if let Some(v) = shown.edit.value().cloned().flatten() {
self.work.set(line.key, FieldValue::Number(v));
}
@@ -908,10 +1142,14 @@ impl<'p> Pass<'p> {
fn custom(&mut self, ui: &mut Ui, line: &Line<'_>) {
let ParamKind::Custom(row) = &line.param.kind else { return };
let mut context = CustomContext::new(line.name.clone(), self.canvas);
let mut context = CustomContext::new(line.name.clone(), self.canvas, self.ended_prev);
let before = self.work.clone();
line.show_body(ui, |ui| {
let _ = row.draw(ui, &mut self.work, &mut context);
});
for step in context.take_gestures() {
self.events.push(lifted_edit(step, &before, &self.work, &line.name));
}
if let Some(request) = context.take_request() {
self.color = Some(request);
}
@@ -931,6 +1169,19 @@ fn read_only_text(ui: &mut Ui, line: &Line<'_>, text: &Label) {
});
}
/// A custom row's control event as an edit of the whole values: they stood at `before` until the row drew and at
/// `after` since.
fn lifted_edit(step: Lifted, before: &DialogFields, after: &DialogFields, label: &Label) -> EditEvent<DialogFields> {
let was = Mixed::Same(before.clone());
match (step.id, step.phase) {
(Some(id), Some(GesturePhase::Begin)) => EditEvent::begin(id, was, label.as_str().into(), None),
(Some(id), Some(GesturePhase::Update)) => EditEvent::update(id, after.clone()),
(Some(id), Some(GesturePhase::Commit)) => EditEvent::commit(id, was, after.clone()),
(Some(id), Some(GesturePhase::Cancel)) => EditEvent::cancel(id, step.reason.unwrap_or(CancelReason::Dismissed), Some(was)),
_ => EditEvent::set(was, after.clone(), label.as_str().into(), None),
}
}
/// The mode entries of a Blend row's `modes`, in menu order.
fn blend_key_entries(modes: &[(BlendKeyEntry<String>, Label)]) -> Vec<BlendKeyEntry<String>> {
modes.iter().map(|(entry, _)| entry.clone()).collect()
@@ -956,7 +1207,29 @@ fn beside(ui: &mut Ui, mut body: impl FnMut(&mut Ui)) {
/// A number field named `name` that reads and writes `decimals` digits and the spellings of `unit`.
fn number_field(units: &Units, name: Label, value: Option<f64>, decimals: u32, unit: Option<UnitKind>) -> NumberField<'static> {
NumberField::new(name, Bind::given(value)).codec(NumberCodec::new(units.reader(unit), decimals as usize))
bound_field(units, name, Bind::given(value), decimals, unit, None)
}
/// [`number_field`] over `value`, read and written with `codec` when the row has one.
fn bound_field(
units: &Units,
name: Label,
value: Bind<'static, Option<f64>>,
decimals: u32,
unit: Option<UnitKind>,
codec: Option<&NumberCodec>,
) -> NumberField<'static> {
let codec = codec.cloned().unwrap_or_else(|| NumberCodec::new(units.reader(unit), decimals as usize));
NumberField::new(name, value).codec(codec)
}
/// The number `value` holds, an int as a number.
fn number_of(value: FieldValue) -> Option<f64> {
match value {
FieldValue::Number(n) => Some(n),
FieldValue::Int(i) => Some(i as f64),
_ => None,
}
}
/// The range that has the bounds that are set, open on the other side; `None` when neither is.
@@ -74,6 +74,119 @@ fn param_rows(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
ParamRows::new("Filter", &params, Bind::bound(fields)).patterns(&patterns).show(ui).into()
}
/// The rows of `params` over the story's values, which `setup` may prepare once.
fn rows_story(ui: &mut Ui, data: &mut StoryData, params: &[Param], setup: impl FnOnce(&mut DialogFields)) -> StoryOutput {
let first = data.present::<DialogFields>("fields").is_none();
let fields = data.value("fields", DialogFields::new());
if first {
setup(fields);
}
ParamRows::new("Filter", params, Bind::bound(fields)).show(ui).into()
}
/// Rows with a reset dot after their label while the value differs from the default.
#[story(ParamRows<'static>, covers = [], drive = Drive::Never)]
fn param_rows_resettable(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let params = [
Param::new("radius", "Radius", ParamKind::range(0.0, 100.0, 10.0, Default::default())).resettable(),
Param::new("method", "Method", ParamKind::choice(vec![("spin".to_owned(), "Spin".into()), ("zoom".to_owned(), "Zoom".into())], None)).resettable(),
Param::new("smooth", "Smooth", ParamKind::bool(false)).resettable(),
];
rows_story(ui, data, &params, |fields| {
fields.set("radius", 40.0);
fields.set("method", "zoom");
})
}
/// Rows whose keys differ over what is edited: they show blank and stay out of the answer until an edit.
#[story(ParamRows<'static>, covers = [], drive = Drive::Never)]
fn param_rows_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let params = [
Param::new("radius", "Radius", ParamKind::range(0.0, 100.0, 10.0, Default::default())),
Param::number("width", "Width", 640.0, 1.0, 0),
Param::new("method", "Method", ParamKind::choice(vec![("spin".to_owned(), "Spin".into()), ("zoom".to_owned(), "Zoom".into())], None)),
Param::new("smooth", "Smooth", ParamKind::bool(false)),
];
rows_story(ui, data, &params, |fields| {
for key in ["radius", "width", "method", "smooth"] {
fields.set_mixed(key);
}
})
}
/// A group that starts closed: its rows hide while it is closed and keep their values.
#[story(ParamRows<'static>, covers = [], drive = Drive::Never)]
fn param_rows_closed_group(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let params = [
Param::number("width", "Width", 640.0, 1.0, 0),
Param::group("Advanced").initially_open(false),
Param::number("height", "Height", 480.0, 1.0, 0),
Param::new("smooth", "Smooth", ParamKind::bool(false)),
];
rows_story(ui, data, &params, |_| {})
}
/// Rows with a help button after the control.
#[story(ParamRows<'static>, covers = [], drive = Drive::Never)]
fn param_rows_with_help_link(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let params = [
Param::number("width", "Width", 640.0, 1.0, 0).help_link("help/width"),
Param::new("smooth", "Smooth", ParamKind::bool(false)),
];
rows_story(ui, data, &params, |_| {})
}
/// Two sections side by side: the second stands beside the first and falls under it when the room is short.
#[story(ParamRows<'static>, covers = [], drive = Drive::Never)]
fn param_rows_with_sections_side_by_side(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let params = [
Param::section("Size"),
Param::number("width", "Width", 640.0, 1.0, 0),
Param::number("height", "Height", 480.0, 1.0, 0),
Param::section("Colour").beside(),
Param::new("tint", "Tint", ParamKind::color(Some([0.2, 0.4, 0.6]))),
Param::new("smooth", "Smooth", ParamKind::bool(false)),
];
rows_story(ui, data, &params, |_| {})
}
/// A section with a check box head, turned off: its rows take no input.
#[story(ParamRows<'static>, covers = [], drive = Drive::Never)]
fn param_rows_with_a_checked_section_off(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let params = [
Param::section_check("rays", "Rays", false),
Param::new("count", "Count", ParamKind::range(1.0, 50.0, 12.0, Default::default())),
Param::new("soft", "Soft", ParamKind::bool(true)),
];
rows_story(ui, data, &params, |_| {})
}
/// A custom row that draws a picture, beside the three rows it belongs to.
#[story(ParamRows<'static>, covers = [], drive = Drive::Never)]
fn param_rows_with_a_picture_beside(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let params = [
Param::number("width", "Width", 640.0, 1.0, 0),
Param::number("height", "Height", 480.0, 1.0, 0),
Param::new("smooth", "Smooth", ParamKind::bool(false)),
Param::custom("picture", "Picture", |ui, _, _| ui.label("Picture")).beside(),
];
rows_story(ui, data, &params, |_| {})
}
/// A radio row whose options carry a detail line.
#[story(ParamRows<'static>, covers = [], drive = Drive::Never)]
fn param_rows_with_radio_details(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let kind = ParamKind::radio_with_details(
vec![
("fast".to_owned(), "Fast".into(), "Lower quality, smaller file".into()),
("best".to_owned(), "Best".into(), "Full quality, largest file".into()),
],
None,
);
let params = [Param::new("quality", "Quality", kind)];
rows_story(ui, data, &params, |_| {})
}
#[story(ParamRows<'static>, covers = [], drive = Drive::Never)]
fn param_rows_read_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let params = params();
@@ -8,6 +8,7 @@ use craft_ui::dialog::{DialogHost, DialogResult, HeldOk, dialog_id};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult};
use craft_ui::patterns::presets::PresetRow;
use craft_ui::runtime::env::Label;
use craft_ui::runtime::memory::{Lifetime, saved_value};
use craft_ui::runtime::overlay::CloseReason;
use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::testing::relations::{above, left_of};
@@ -285,7 +286,7 @@ fn stack_dialog(fields: &mut DialogFields) -> ParamDialog<'_> {
.extra_buttons(vec![
("load".to_owned(), FooterButton::new(Label::from("Load…"), DialogRole::Other)),
("save".to_owned(), FooterButton::new(Label::from("Save…"), DialogRole::Other)),
]) // P3(forms-w1): q337
])
}
/// The `{files, folder, useFolder}` value of a files row that lists `folder`.
@@ -680,3 +681,233 @@ fn a_typed_value_past_a_rows_range_is_clamped_and_the_host_takes_one_range_alert
assert_eq!(on_dialog(&host, |dialog| dialog.fields().int("size")).flatten(), Some(1), "text that is no number leaves the value");
assert!(!alert(), "and raises no alert");
}
/// Runs a one-row dialog for `row`; the values of its answer are filed in the returned cell.
fn single_row(row: Param) -> (Fixture, Rc<RefCell<Option<DialogFields>>>) {
let answered = Rc::new(RefCell::new(None::<DialogFields>));
let out = Rc::clone(&answered);
let fixture = Fixture::new(move |ui| {
if let Some(result) = ParamDialog::new("row", "Row", vec![row.clone()]).show(ui).result {
*out.borrow_mut() = Some(result.fields);
}
});
(fixture, answered)
}
// Text that does not parse in a number row holds OK: it is disabled and Enter answers nothing; text that parses
// answers OK with the new value.
#[trial]
fn a_row_whose_text_does_not_parse_holds_ok() {
let (mut fixture, answered) = single_row(Param::new("size", "Size", ParamKind::int(Some(1), Some(100), 10)));
fixture.settle();
let field = fixture.by_label("Size").expect("the size row has a field");
fixture.click(&field).settle();
fixture.key(Key::A, Modifiers::COMMAND).type_text("abc");
fixture.idle(2);
let ok = fixture.by_label("OK").expect("the footer has OK");
assert!(fixture.tree().is_disabled_key(ok.node), "OK waits while the text does not parse");
fixture.key(Key::Enter, Modifiers::NONE).settle();
assert!(answered.borrow().is_none(), "Enter answers nothing while the text does not parse");
fixture.key(Key::A, Modifiers::COMMAND).type_text("42");
fixture.idle(2);
let ok = fixture.by_label("OK").expect("the footer has OK");
assert!(!fixture.tree().is_disabled_key(ok.node), "text that parses frees OK");
fixture.key(Key::Enter, Modifiers::NONE).settle();
assert_eq!(answered.borrow().as_ref().and_then(|fields| fields.int("size")), Some(42), "OK answers the typed value");
}
// Shift+Enter in a row's field confirms the dialog with the typed value.
#[trial]
fn shift_enter_in_a_row_answers_ok() {
let (mut fixture, answered) = single_row(Param::new("notes", "Notes", ParamKind::text("")));
fixture.settle();
let field = fixture.by_label("Notes").expect("the notes row has a field");
fixture.click(&field).settle();
fixture.type_text("a");
fixture.key(Key::Enter, Modifiers::SHIFT).settle();
assert_eq!(answered.borrow().as_ref().and_then(|fields| fields.text("notes").map(str::to_owned)).as_deref(), Some("a"));
}
// Enter in an open select picks the highlighted option; it does not answer OK, and the dialog stays open.
#[trial]
fn an_open_select_takes_enter_and_the_dialog_stays_open() {
let options = vec![("spin".to_owned(), Label::from("Spin")), ("zoom".to_owned(), Label::from("Zoom"))];
let (mut fixture, answered) = single_row(Param::new("method", "Method", ParamKind::choice(options, None)));
fixture.settle();
let select = fixture.by_label("Method").expect("the method row has a select");
fixture.click(&select).settle();
fixture.key(Key::ArrowDown, Modifiers::NONE).settle();
fixture.key(Key::Enter, Modifiers::NONE).settle();
assert!(answered.borrow().is_none(), "Enter in the open select does not answer OK");
assert!(fixture.by_label("Row").is_some(), "the dialog stays open");
fixture.key(Key::Enter, Modifiers::NONE).settle();
assert_eq!(answered.borrow().as_ref().and_then(|fields| fields.text("method").map(str::to_owned)).as_deref(), Some("zoom"), "the pick stood");
}
// A dialog that previews lists its Preview box as the `preview` field, and the field sets it; one that does not
// preview refuses the field as unknown.
#[trial]
fn a_previewing_dialog_takes_preview_as_a_field() {
let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
let mut fixture = host_fixture(&host, &twice);
let ctx = fixture.ctx().clone();
let id = host.borrow_mut().open(HostedParamDialog::new(&ctx, "blur", DialogFields::new(), |fields| blur(fields).previews(true)));
fixture.idle(4);
let preview = |host: &Rc<RefCell<DialogHost>>| {
host.borrow().open_dialogs().into_iter().find(|dialog| dialog.id == id).and_then(|dialog| dialog.fields).map(|fields| fields["preview"].clone())
};
assert_eq!(preview(&host), Some(json!(true)), "the box lists as on");
assert_eq!(host.borrow_mut().set_json_field(&ctx, id, "preview", json!(false)), Ok(()));
assert_eq!(on_dialog(&host, |dialog| dialog.is_previewing()), Some(false), "the field turned the preview off");
assert_eq!(preview(&host), Some(json!(false)));
let plain = host.borrow_mut().open(HostedParamDialog::new(&ctx, "sharpen", DialogFields::new(), sharpen));
fixture.idle(4);
let refused = host.borrow_mut().set_json_field(&ctx, plain, "preview", json!(true));
assert!(refused.is_err(), "a dialog that does not preview has no preview field: {refused:?}");
}
// A refusal the host keeps turns OK off with its reason and survives a changed value until the host withdraws it.
#[trial]
fn a_host_refusal_keeps_ok_off_until_a_value_changes() {
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(fixture.ctx(), "blur", DialogFields::new(), blur));
fixture.idle(6);
let ok_off = |fixture: &Fixture| {
let ok = fixture.by_label("OK").expect("the OK button");
fixture.tree().is_disabled_key(ok.node)
};
on_dialog(&host, |dialog| dialog.refuse(Some(Label::from(REFUSED))));
fixture.idle(4);
assert!(ok_off(&fixture), "the refusal turns OK off");
assert!(fixture.by_label(REFUSED).is_some(), "the reason shows under the rows");
assert_eq!(host.borrow().held_state(dialog_id("blur")), Some(HeldOk::Refused(Label::from(REFUSED))));
let smooth = fixture.by_label("Smooth").expect("the smooth row has a check box");
fixture.click(&smooth).idle(4);
assert!(ok_off(&fixture), "a changed value does not lift the refusal the host keeps");
assert!(fixture.by_label(REFUSED).is_some(), "and the reason stays");
on_dialog(&host, |dialog| dialog.refuse(None));
fixture.idle(4);
assert!(!ok_off(&fixture), "the host withdrew the refusal");
assert!(fixture.by_label(REFUSED).is_none());
}
/// A dialog whose Show Grid row stands in the footer.
fn gridded(fields: &mut DialogFields) -> ParamDialog<'_> {
ParamDialog::new("grid", "Grid", footer_params()).values(Bind::bound(fields))
}
/// The rows of [`gridded`].
fn footer_params() -> Vec<Param> {
vec![
Param::new("radius", "Radius", ParamKind::range(0.0, 100.0, 10.0, Default::default())),
Param::new("grid", "Show Grid", ParamKind::bool(false)).in_footer("Hide Grid"),
]
}
// A footer row is a footer button: a press flips its value and the dialog stays open, its label follows, automation
// sets the value, the remembered values leave it out, and the rows draw no body row for it.
#[trial]
fn a_footer_row_flips_its_value_and_automation_sets_it() {
let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
let mut fixture = host_fixture(&host, &twice);
let ctx = fixture.ctx().clone();
let id = host.borrow_mut().open(HostedParamDialog::new(&ctx, "grid", DialogFields::new(), gridded));
fixture.idle(6);
let grid = || on_dialog(&host, |dialog| dialog.fields().bool("grid")).flatten();
assert_eq!(grid(), Some(false));
assert!(!fixture.by_role(Role::CHECK_BOX).iter().any(|target| fixture.tree().name_of(target.node) == Some("Show Grid")), "no body row");
let button = fixture.by_label("Show Grid").expect("the footer has the row's button");
fixture.click(&button).idle(6);
assert_eq!(grid(), Some(true), "the press flips the value");
assert!(host.borrow().is_open::<HostedParamDialog>(), "the dialog stays open");
assert!(fixture.by_label("Hide Grid").is_some(), "the label follows the value");
assert_eq!(host.borrow_mut().set_json_field(&ctx, id, "grid", json!(false)), Ok(()));
assert_eq!(grid(), Some(false), "automation sets it");
let fields = on_dialog(&host, |dialog| dialog.fields().clone()).expect("open");
assert!(!ParamDialog::remembered(&footer_params(), &fields).contains("grid"), "the footer key is not remembered");
}
// The presets row lists the presets; a pick writes the preset's values as one edit, and a value edited after it
// leaves the values matching no preset.
#[trial]
fn a_preset_row_fills_the_values_and_names_new_presets() {
let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
let mut fixture = host_fixture(&host, &twice);
let ctx = fixture.ctx().clone();
let id = host.borrow_mut().open(HostedParamDialog::new(&ctx, "blur", DialogFields::new(), blur));
let rows = vec![PresetRow::item("soft".to_owned(), "Soft", 0), PresetRow::item("hard".to_owned(), "Hard", 0)];
let values = vec![
("soft".to_owned(), DialogFields::from_pairs([("radius", 2.0)])),
("hard".to_owned(), DialogFields::from_pairs([("radius", 60.0)])),
];
on_dialog(&host, |dialog| dialog.set_presets(rows, values, vec!["soft".to_owned()]));
fixture.idle(6);
let preset = |host: &Rc<RefCell<DialogHost>>| {
host.borrow().open_dialogs().into_iter().find(|dialog| dialog.id == id).and_then(|dialog| dialog.fields).map(|fields| fields["preset"].clone())
};
let picker = fixture.by_label("Preset").expect("the dialog has a presets row");
fixture.click(&picker).idle(4);
let hard = fixture.by_label("Hard").expect("the picker lists the preset");
fixture.click(&hard).idle(6);
assert_eq!(on_dialog(&host, |dialog| dialog.fields().number("radius")).flatten(), Some(60.0), "the pick wrote the preset's values");
assert_eq!(preset(&host), Some(json!("hard")), "the values are the preset's");
assert_eq!(host.borrow_mut().set_json_field(&ctx, id, "radius", json!(5)), Ok(()));
fixture.idle(4);
assert_eq!(preset(&host), Some(json!(null)), "after an edit the values are no preset's");
assert!(on_dialog(&host, HostedParamDialog::take_preset_events).is_some_and(|events| events.is_empty()), "a pick reports no edit of the presets");
}
/// A Blur dialog that keeps its values for the run.
fn run_only(fields: &mut DialogFields) -> ParamDialog<'_> {
blur(fields).remember(SaveKey::new("trial.run-only")).remember_for(Lifetime::Run)
}
// A dialog that remembers for the run reopens with the values the app stored after its command, and nothing reaches
// the saved tier.
#[trial]
fn a_run_only_remember_reopens_with_its_values_and_stores_nothing() {
let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
let mut fixture = host_fixture(&host, &twice);
let ctx = fixture.ctx().clone();
let id = host.borrow_mut().open(HostedParamDialog::new(&ctx, "blur", DialogFields::new(), run_only));
fixture.idle(4);
host.borrow_mut().set_json_field(&ctx, id, "radius", json!(33.0)).expect("the radius row takes a number");
assert!(host.borrow_mut().confirm::<HostedParamDialog>(&ctx), "OK answers");
let result = host.borrow_mut().take_keyed::<HostedParamDialog>().map(|(result, _)| result).and_then(DialogResult::ok).expect("the answer");
result.remember(&ctx);
fixture.idle(2);
host.borrow_mut().open(HostedParamDialog::new(&ctx, "blur", DialogFields::new(), run_only));
fixture.idle(4);
assert_eq!(on_dialog(&host, |dialog| dialog.fields().number("radius")).flatten(), Some(33.0), "the run's values come back");
assert_eq!(saved_value::<Option<DialogFields>>(&ctx, &SaveKey::new("trial.run-only")), None, "a run-only value never reaches the saved tier");
}
// A host's reset restores the opening values with `reset_to` over them, keeps the dialog open and answers false for an
// unknown id.
#[trial]
fn a_hosted_dialogs_reset_through_the_host_restores_the_opening_values() {
let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
let mut fixture = host_fixture(&host, &twice);
let ctx = fixture.ctx().clone();
let id = host.borrow_mut().open(HostedParamDialog::new(&ctx, "blur", DialogFields::new(), |fields| {
blur(fields).reset_to(DialogFields::from_pairs([("smooth", true)]))
}));
fixture.idle(6);
assert!(!host.borrow().can_reset_by_id(id), "nothing changed yet");
host.borrow_mut().set_json_field(&ctx, id, "radius", json!(60.0)).expect("the radius row takes a number");
assert!(host.borrow().can_reset_by_id(id), "an edit can be reset");
assert!(host.borrow_mut().reset_by_id(&ctx, id), "the reset happened");
fixture.idle(4);
let fields = on_dialog(&host, |dialog| dialog.fields().clone()).expect("the dialog stays open");
assert_eq!((fields.number("radius"), fields.bool("smooth")), (Some(10.0), Some(true)), "the opening values with reset_to over them");
assert!(!host.borrow_mut().reset_by_id(&ctx, dialog_id("unknown")), "an unknown id answers false");
}
@@ -3,11 +3,12 @@
use craft_behavior::PixelSize;
use craft_ui::dialog::{DialogHost, DialogResult, HeldOk, StackDialog};
use craft_ui::contract::Bind;
use craft_ui::patterns::form_dialogs::{
AboutInfo, AboutLink, CanvasSize, CanvasSizeValues, Credits, ExportOptions, ExportOptionsKind, FormatOptions, GuideLayoutDialog,
AboutInfo, AboutLink, CanvasSize, CanvasSizeValues, Credits, DialogFields, ExportOptions, ExportOptionsKind, FormatOptions, GuideLayoutDialog,
GuideLayoutValues, GuideRect, GuideUnits, HostedAbout, HostedCanvasSize, HostedExportAs, HostedFormatOptions, HostedGuideLayoutDialog,
HostedImageSize, HostedNewDocument, HostedNewGuideDialog, ImageSize, ImageSizeValues, JpegOptions, NewDocumentDialog, NewGuideDialog,
NewGuideValues,
HostedImageSize, HostedNewDocument, HostedNewGuideDialog, HostedParamDialog, ImageSize, ImageSizeValues, JpegOptions, NewDocumentDialog,
NewGuideDialog, NewGuideValues, Param, ParamDialog, ParamKind,
};
use craft_ui::runtime::env::UnitKind;
use craft_ui::testing::{Fixture, trial};
@@ -464,3 +465,28 @@ fn image_size_alt_digits_pick_resample_without_typing_into_a_field() {
alt_digit(&mut fixture, Key::Num7, "7", alt);
assert_eq!(resample(&host), Some(json!("nearestNeighbor")), "Alt+7 picks a listed method");
}
/// A dialog with one colour row whose dropper opens armed.
fn dropper(fields: &mut DialogFields) -> ParamDialog<'_> {
let tint = Param::new("tint", "Tint", ParamKind::color(Some([0.0, 0.0, 1.0]))).eyedropper().armed(true);
ParamDialog::new("dropper", "Dropper", vec![tint]).values(Bind::bound(fields))
}
// While a colour row samples, Escape ends the sampling and the dialog stays open with its edit; the next Escape cancels.
#[trial]
fn escape_ends_a_sampling_row_before_it_cancels_the_dialog() {
let host = Rc::new(RefCell::new(DialogHost::new()));
let mut fixture = fixture(&host);
host.borrow_mut().open(HostedParamDialog::new(fixture.ctx(), "dropper", DialogFields::new(), dropper));
fixture.idle(10);
let ended = || host.borrow_mut().get_mut::<HostedParamDialog>().is_some_and(HostedParamDialog::take_sampling_ended);
assert!(!ended(), "nothing ended yet");
fixture.key(Key::Escape, Modifiers::NONE).idle(4);
assert!(host.borrow().is_open::<HostedParamDialog>(), "the first Escape leaves the dialog open");
assert!(ended(), "and ends the sampling");
assert!(!ended(), "once");
fixture.key(Key::Escape, Modifiers::NONE).idle(4);
assert!(host.borrow().is_empty(), "the next Escape cancels the dialog");
}
@@ -6,10 +6,13 @@ mod dialog;
mod export;
mod files;
mod hosted;
mod list_manager;
mod new_document;
mod params;
mod password;
mod pdf_export;
mod preview;
mod preview_width;
mod properties;
mod save_for_web;
mod size_model;
@@ -1,17 +1,22 @@
//! The parameter model: the spec-string parser, kinds, defaults and fit rules, and the rows' predicates, read-only
//! text and tooltips.
use craft_behavior::{EditEvent, GesturePhase};
use craft_ui::contract::{Bind, Role};
use craft_ui::dialog::DialogHost;
use craft_ui::patterns::blend_keys::{BlendKeyEntry, BlendShortcut};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, NumberUnit, Param, ParamDialog, ParamKind, ParamRows, set_param_field};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, NumberUnit, Param, ParamDialog, ParamKind, ParamRows, set_param_field};
use craft_ui::patterns::presets::PresetRow;
use craft_ui::runtime::env::{Label, UnitKind};
use craft_ui::testing::relations::{above, left_of};
use craft_ui::testing::{Fixture, trial};
use craft_ui::value_drag::SliderScale;
use egui::{Key, Modifiers, Vec2};
use serde_json::json;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicU8, Ordering};
const SPEC: &str = r#"{"radius":0.1..1000=1,"method":"spin|zoom"="zoom","monochromatic":bool,"seed":u32=0,"cellSize":px=4,"tint":color=#ff8000,"kernel":int[25],"layer":layer id,"curve":json,"note":text} -> {"x":1}"#;
const KERNEL_CELLS: usize = 25;
@@ -96,6 +101,19 @@ fn rows_follow_their_predicates_and_carry_their_tooltip() {
fixture.settle();
assert!(fixture.by_label("Input Folder").is_some(), "shown once the source is a folder");
// A second condition on the same row (`visible_when_in`) narrows it: it shows only while both hold.
let params = vec![
Param::new("source", "Source", ParamKind::choice(vec![("file".into(), "File".into()), ("folder".into(), "Folder".into())], None)),
Param::new("both", "Both", ParamKind::bool(false)),
Param::new("extra", "Extra", ParamKind::text("")).visible_when_in("source", ["file", "folder"]).visible_when("both", true),
];
let narrow = Rc::new(RefCell::new(DialogFields::new()));
let mut narrowed = rows(params, &narrow);
assert!(narrowed.by_label("Extra").is_none(), "hidden while one of its conditions fails");
narrow.borrow_mut().set("both", FieldValue::Bool(true));
narrowed.settle();
assert!(narrowed.by_label("Extra").is_some(), "shown once every condition holds");
// A row enabled for two of three values takes input for both and greys out for the third.
let detail = fixture.by_label("Detail").expect("the detail row");
assert!(!fixture.tree().is_disabled_key(detail.node), "enabled for the folder source");
@@ -325,3 +343,199 @@ fn typing_in_a_freshly_opened_parameter_dialog_replaces_its_first_field() {
fixture.type_text("7").key(Key::Tab, Modifiers::NONE).settle();
assert_eq!(values.borrow().number("radius"), Some(7.0), "typing replaced the radius");
}
/// A fixture showing `params` as rows over `values`, logging the edit events of every pass as `(phase, gesture)`. While
/// `twice` is on, every frame runs a second pass.
fn logged_rows(params: Vec<Param>, values: &Rc<RefCell<DialogFields>>, twice: bool) -> (Fixture, Rc<RefCell<Vec<EditEvent<DialogFields>>>>) {
let (shown, log) = (values.clone(), Rc::new(RefCell::new(Vec::new())));
let out = log.clone();
let mut fixture = Fixture::new(move |ui| {
if twice && ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("a second pass in the frame");
}
let shown = ParamRows::new("Form", &params, Bind::bound(&mut *shown.borrow_mut())).show(ui);
out.borrow_mut().extend(shown.events);
});
fixture.settle();
(fixture, log)
}
// A resettable row's label has a reset dot while the value differs from the default; a double press on the label (the
// dot's gesture) restores the default as one edit, and one on an unchanged row changes nothing.
#[trial]
fn a_resettable_row_shows_its_dot_only_while_changed_and_its_press_restores_the_default() {
let params = vec![Param::new("radius", "Radius", ParamKind::range(0.0, 100.0, 10.0, SliderScale::Linear)).resettable()];
let values = Rc::new(RefCell::new(DialogFields::new()));
let (mut fixture, log) = logged_rows(params, &values, false);
let label_at = |fixture: &Fixture| fixture.texts().iter().find(|text| text.text == "Radius").map(|text| text.rect.center()).expect("the row's label");
let reset = |fixture: &mut Fixture| {
let at = label_at(fixture);
fixture.click_at(at);
fixture.click_at(at).settle();
};
reset(&mut fixture);
assert_eq!(values.borrow().number("radius"), Some(10.0), "a reset of an unchanged row changes nothing");
assert!(log.borrow().is_empty(), "and files no edit");
values.borrow_mut().set("radius", FieldValue::Number(40.0));
fixture.settle();
reset(&mut fixture);
assert_eq!(values.borrow().number("radius"), Some(10.0), "the press restores the default");
assert_eq!(log.borrow().len(), 1, "as one edit: {:?}", log.borrow());
}
/// What a probe row saw: nothing yet, its key unmarked or its key marked mixed.
const UNSEEN: u8 = 0;
const SEEN_PLAIN: u8 = 1;
const SEEN_MIXED: u8 = 2;
/// A custom row that records whether its key was marked mixed when it drew.
fn mixed_probe(seen: &Arc<AtomicU8>) -> Param {
let seen = Arc::clone(seen);
Param::custom("probe", "Probe", move |ui, fields, _| {
seen.store(if fields.is_mixed("probe") { SEEN_MIXED } else { SEEN_PLAIN }, Ordering::Relaxed);
ui.label("probe")
})
}
// A key marked mixed shows blank, stays out of the answer and the opening fill; an edit makes it concrete; Reset marks
// it again; a custom row reads the mark from its fields until an edit.
#[trial]
fn a_mixed_key_shows_mixed_stays_out_of_the_answer_and_a_custom_row_sees_it_until_an_edit() {
let seen = Arc::new(AtomicU8::new(UNSEEN));
let params = vec![
Param::number("width", "Width", 640.0, 1.0, 0),
Param::new("method", "Method", ParamKind::choice(vec![("spin".into(), "Spin".into()), ("zoom".into(), "Zoom".into())], None)),
mixed_probe(&seen),
];
let values = Rc::new(RefCell::new(DialogFields::new()));
for key in ["width", "method", "probe"] {
values.borrow_mut().set_mixed(key);
}
values.borrow_mut().snapshot();
let (mut fixture, _) = logged_rows(params, &values, false);
assert!(["width", "method"].iter().all(|key| !values.borrow().contains(key)), "the opening fill skips a marked key");
assert!(serde_json::to_value(&*values.borrow()).is_ok_and(|answer| answer.as_object().is_some_and(|map| !map.contains_key("width"))), "a marked key is absent from the answer");
assert_eq!(seen.load(Ordering::Relaxed), SEEN_MIXED, "a custom row reads the mark from its fields");
let field = fixture.by_label("Width").expect("the width row");
fixture.click(&field).settle();
fixture.key(Key::A, Modifiers::COMMAND).type_text("5").key(Key::Tab, Modifiers::NONE).settle();
assert_eq!(values.borrow().number("width"), Some(5.0), "an edit makes the key concrete");
assert!(!values.borrow().is_mixed("width"), "and clears its mark");
values.borrow_mut().set("probe", FieldValue::Int(1));
fixture.settle();
assert_eq!(seen.load(Ordering::Relaxed), SEEN_PLAIN, "the custom row sees the mark gone after an edit");
assert!(values.borrow_mut().reset(), "Reset changes the values");
assert!(values.borrow().is_mixed("width") && !values.borrow().contains("width"), "Reset marks the key again");
}
// A drag of a slider is one gesture: one begin, updates and one commit with one gesture id, a second pass of every
// frame lifts nothing new, Escape cancels with the whole values from before, and a typed value is one set.
#[trial]
fn a_row_drag_lifts_to_one_gesture_and_a_typed_value_to_one_set() {
let params = vec![
Param::new("radius", "Radius", ParamKind::range(0.0, 100.0, 10.0, SliderScale::Linear)),
Param::number("width", "Width", 640.0, 1.0, 0),
];
let values = Rc::new(RefCell::new(DialogFields::new()));
let (mut fixture, log) = logged_rows(params, &values, true);
let slider = fixture.by_role(Role::SLIDER).into_iter().next().expect("the radius row has a slider");
fixture.drag(&slider, Vec2::new(60.0, 0.0)).settle();
let phases = |log: &Vec<EditEvent<DialogFields>>| log.iter().filter_map(EditEvent::phase).collect::<Vec<_>>();
let ids: std::collections::BTreeSet<_> = log.borrow().iter().filter_map(|event| event.id().map(|id| id.0)).collect();
let events = log.borrow();
let phases_seen = phases(&events);
let count = |wanted: GesturePhase| phases_seen.iter().filter(|phase| **phase == wanted).count();
assert_eq!((count(GesturePhase::Begin), count(GesturePhase::Commit)), (1, 1), "one begin and one commit: {phases_seen:?}");
assert_eq!(ids.len(), 1, "one gesture id");
assert_ne!(values.borrow().number("radius"), Some(10.0), "the drag moved the radius");
drop(events);
log.borrow_mut().clear();
let before = values.borrow().number("radius");
fixture.drag_hold_at(slider.rect.center(), Vec2::new(-30.0, 0.0));
fixture.key(Key::Escape, Modifiers::NONE).settle();
let cancelled = log.borrow().iter().find(|event| event.phase() == Some(GesturePhase::Cancel)).cloned().expect("Escape cancels the gesture");
assert_eq!(cancelled.landed().and_then(|fields| fields.number("radius")), before, "the cancel carries the whole values from before");
log.borrow_mut().clear();
let field = fixture.by_label("Width").expect("the width row");
fixture.click(&field).settle();
fixture.key(Key::A, Modifiers::COMMAND).type_text("7").key(Key::Enter, Modifiers::NONE).settle();
let sets = log.borrow().iter().filter(|event| event.phase().is_none() && event.value().is_some()).count();
assert_eq!(sets, 1, "a typed value is one set: {:?}", log.borrow());
}
/// The rects of two rows' fields in a form of `params` shown in a room of `room`.
fn placed(params: Vec<Param>, room: Vec2, first: &str, second: &str) -> [egui::Rect; 2] {
let values = Rc::new(RefCell::new(DialogFields::new()));
let mut fixture = rows(params, &values);
fixture.room(room).settle();
let first = fixture.by_label(first).expect("the first row").rect;
let second = fixture.by_label(second).expect("the second row").rect;
[first, second]
}
// A section beside the one before it, and a full-width custom row beside its section's rows, stand side by side with
// room and fall under without it.
#[trial]
fn a_beside_row_sits_beside_its_section_with_room_and_under_it_without() {
let sections = || {
vec![
Param::section("First"),
Param::number("a", "Alpha", 1.0, 1.0, 0),
Param::section("Second").beside(),
Param::number("b", "Beta", 2.0, 1.0, 0),
]
};
let [alpha, beta] = placed(sections(), Vec2::new(1400.0, 600.0), "Alpha", "Beta");
assert!(left_of(alpha, beta), "with room the second section stands beside the first");
let [alpha, beta] = placed(sections(), Vec2::new(300.0, 900.0), "Alpha", "Beta");
assert!(above(alpha, beta), "without room it falls under");
let picture = || {
vec![
Param::section("Size"),
Param::number("a", "Alpha", 1.0, 1.0, 0),
Param::custom("pic", "Pic", |ui, _, _| ui.button("Picture")).beside(),
]
};
let [alpha, pic] = placed(picture(), Vec2::new(1400.0, 600.0), "Alpha", "Picture");
assert!(left_of(alpha, pic), "with room the picture stands beside the rows");
let [alpha, pic] = placed(picture(), Vec2::new(300.0, 900.0), "Alpha", "Picture");
assert!(above(alpha, pic), "without room it falls under");
}
/// A dialog with one colour row.
fn tinted(fields: &mut DialogFields) -> ParamDialog<'_> {
ParamDialog::new("tint", "Tint", vec![Param::new("tint", "Tint", ParamKind::color(None))]).values(Bind::bound(fields))
}
// A colour row's press goes to the host's one routing: the host names the top dialog and the request, and its answer is
// written into the row's key in the next pass.
#[trial]
fn a_hosted_dialogs_colour_request_goes_through_the_host_and_its_answer_comes_back() {
let host = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.room(Vec2::new(1200.0, 900.0));
let id = host.borrow_mut().open(HostedParamDialog::new(fixture.ctx(), "tint", DialogFields::new(), tinted));
fixture.idle(6);
let swatch = fixture.by_label("Tint").expect("the colour row has a swatch");
fixture.click(&swatch).idle(4);
let (named, request) = host.borrow_mut().take_color_request().expect("the press filed a request");
assert_eq!((named, request.key.as_str()), (id, "tint"), "the host names the dialog and the row");
assert!(host.borrow_mut().take_color_request().is_none(), "the request comes once");
host.borrow_mut().answer_color(id, "tint", craft_theme::Srgba::new(1.0, 0.0, 0.0, 1.0));
fixture.idle(4);
assert_eq!(on_fields(&host, |fields| fields.color("tint")), Some([1.0, 0.0, 0.0]), "the answer is written into the row's key");
}
/// `read` of the open hosted dialog's values.
fn on_fields<T>(host: &Rc<RefCell<DialogHost>>, read: impl FnOnce(&DialogFields) -> Option<T>) -> Option<T> {
host.borrow().get::<HostedParamDialog>().and_then(|dialog| read(dialog.fields()))
}