From ee9b2cfd03d328543c04acf12e08169477d5b4fc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 14:17:19 -0800 Subject: [PATCH 1/2] Dialogs: rows of controls in dialogs and add-ons are framework Rows and Stacks, so a dialog takes the width of its rows A dialog's custom row drawn as a raw egui layout measured as wide as the room it was offered, so DXF Options, New Swatch, PNG and JPEG Options and Radial Blur opened at the window's full width. The rows in the export options, Save Options, Document Setup, Swatch Options, the effect rows, the Clean Up and color add-ons, the edit toolbar, Edit Original and the preferences file buttons now use Row and Stack. A framework container may run its body more than once in a pass. Presses and picks inside a body are kept in locals and applied after it: the HP-GL pen rows apply Add, Remove and the Pen Table switch once, and the legacy board picker toggles a board once. --- crates/ui-egui/src/addons/cleanup.rs | 7 +- crates/ui-egui/src/addons/color.rs | 12 ++- crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/dialogs/document_setup.rs | 38 ++++---- crates/ui-egui/src/dialogs/dxf_options.rs | 9 +- crates/ui-egui/src/dialogs/effect_rows.rs | 30 +++--- crates/ui-egui/src/dialogs/eps_options.rs | 19 ++-- crates/ui-egui/src/dialogs/hpgl_options.rs | 95 +++++++++++++------ crates/ui-egui/src/dialogs/png_options.rs | 74 ++++++++------- crates/ui-egui/src/dialogs/save_options.rs | 13 ++- crates/ui-egui/src/dialogs/swatch_options.rs | 23 +++-- .../ui-egui/src/dialogs/tests_custom_rows.rs | 73 ++++++++++++++ crates/ui-egui/src/dialogs/tests_hpgl.rs | 18 ++++ crates/ui-egui/src/edit_toolbar.rs | 5 +- crates/ui-egui/src/original_editor.rs | 25 ++--- crates/ui-egui/src/prefs_dialog/model.rs | 8 +- 16 files changed, 308 insertions(+), 143 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/tests_custom_rows.rs diff --git a/crates/ui-egui/src/addons/cleanup.rs b/crates/ui-egui/src/addons/cleanup.rs index fe68a96d79..8ce1aa6812 100644 --- a/crates/ui-egui/src/addons/cleanup.rs +++ b/crates/ui-egui/src/addons/cleanup.rs @@ -10,6 +10,7 @@ use craft::menu::Node; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Props as _, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::display::{Divider, Text}; +use craft::ui::layout_components::Row; use craft::ui::list::{List, ListRow}; use craft::ui::sections::Section; use egui::Ui; @@ -304,8 +305,8 @@ fn text_tools(ui: &mut Ui, selected: bool, editing: bool, action: &mut Option) { if !r.status.is_empty() { Text::new(r.status.clone()).show(ui); } - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { let picked = r.picked_kinds(); let show = push(ui, tl!("Show"), picked.len() == 1, None).is_some(); if show && let [kind] = picked.as_slice() { diff --git a/crates/ui-egui/src/addons/color.rs b/crates/ui-egui/src/addons/color.rs index ec86efd95c..aca41a2620 100644 --- a/crates/ui-egui/src/addons/color.rs +++ b/crates/ui-egui/src/addons/color.rs @@ -14,6 +14,7 @@ use craft::menu::Node; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; use craft::ui::form::{Field, FieldGroup}; +use craft::ui::layout_components::Row; use craft::ui::pickers::Select; use egui::Ui; use serde_json::{Map, Value, json}; @@ -178,18 +179,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } let (id, params) = st.params(); - let mut command = None; - ui.horizontal(|ui| { + let (mut command, mut reset) = (None, false); + Row::new().show(ui, |ui, _| { if Button::new(tl!("Add as Effect").to_string()).show(ui).clicked() { command = Some("effect.apply"); } if Button::new(tl!("Apply as Filter").to_string()).show(ui).clicked() { command = Some("addon.color.filter"); } - if Button::new(tl!("Reset").to_string()).show(ui).clicked() { - st.values.remove(id); - } + reset = Button::new(tl!("Reset").to_string()).show(ui).clicked(); }); + if reset { + st.values.remove(id); + } // Inks: Duotone's and Print Ink Fixes' dialogs, as their menu items open them. let mut ink = None; crate::panels::section(tl!("Inks").to_string()).show(ui, |ui, _| { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1aae334de1..7ce5c83baa 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -213,6 +213,8 @@ mod tests_raster_formats; #[cfg(test)] mod tests_raster_supplied_options; +#[cfg(test)] +mod tests_custom_rows; #[cfg(test)] mod tests_dxf; #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 17c3b500a6..913d04ca3e 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -20,9 +20,10 @@ use craft::color_ui::display::DisplayTransform; use craft::theme::{Rgba, Srgba}; use craft::ui::buttons::Button; use craft::ui::choice::Swatch; -use craft::ui::contract::{Bind, Entry, Show as _, clicked}; +use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _, clicked}; use craft::ui::dialog::dialog_id; use craft::ui::display::Picture; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::ThumbAspect; use craft::ui::patterns::form_dialogs::{ CustomContext, DialogFields, FieldValue, HostedPropertiesDialog, Param, ParamKind, PropertiesDialog, PropertiesTab, PropertyRow, @@ -382,27 +383,32 @@ fn grid_colors_row(setup: DocSetup) -> Param { let resolved = grid_colors(&json_map(fields), &setup); let menu: Vec> = GRID_COLOR_PRESETS.iter().map(|(n, _)| *n).chain(["Custom"]).map(|n| Entry::new(n.to_string(), n.to_string())).collect(); - ui.vertical(|ui| { - let picked = Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).value().cloned(); - if let Some((_, pair)) = picked.and_then(|n| GRID_COLOR_PRESETS.iter().find(|(p, _)| *p == n)) { - fields.set("gridColors", entries_value(*pair)); - } - ui.horizontal(|ui| { + let mut picked = None; + let (mut wells, mut edits) = ([None; 2], [None; 2]); + let shown = Stack::new().show(ui, |ui, _| { + picked = Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).value().cloned(); + Row::new().show(ui, |ui, _| { for (i, color) in resolved.iter().enumerate() { let name = format!("{} {}", tl!("Grid Colors:"), i + 1); let [r, g, b, _] = color.to_rgba8(1.0); let srgb = Srgba::rgb(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0); - if Swatch::new(name.clone(), srgb).well().show(ui).clicked { - cx.pick_color(GRID_KEYS[i], srgb); - } - let edited = HexField::hex(name, Bind::given(Rgba::rgb(r, g, b))).show(ui).value().copied(); - if let Some(Rgba([r, g, b, _])) = edited { - set_grid_entry(fields, &setup, i, &Color::rgb8(r, g, b)); - } + wells[i] = Swatch::new(name.clone(), srgb).well().show(ui).clicked.then_some(srgb); + edits[i] = HexField::hex(name, Bind::given(Rgba::rgb(r, g, b))).show(ui).value().copied(); } }); - }) - .response + }); + if let Some((_, pair)) = picked.and_then(|n| GRID_COLOR_PRESETS.iter().find(|(p, _)| *p == n)) { + fields.set("gridColors", entries_value(*pair)); + } + for (i, (well, edit)) in wells.into_iter().zip(edits).enumerate() { + if let Some(srgb) = well { + cx.pick_color(GRID_KEYS[i], srgb); + } + if let Some(Rgba([r, g, b, _])) = edit { + set_grid_entry(fields, &setup, i, &Color::rgb8(r, g, b)); + } + } + shown.output }) } diff --git a/crates/ui-egui/src/dialogs/dxf_options.rs b/crates/ui-egui/src/dialogs/dxf_options.rs index 4f8218172c..d1a66945ff 100644 --- a/crates/ui-egui/src/dialogs/dxf_options.rs +++ b/crates/ui-egui/src/dialogs/dxf_options.rs @@ -8,7 +8,8 @@ //! options of `document.exportDxf`. OK remembers the options for next time and writes the file //! (asking where when there is no path); bad options keep the dialog open. -use craft::ui::contract::{Bind, Entry, Show as _}; +use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::pickers::Select; use craft::ui::text::NumberField; @@ -142,15 +143,15 @@ pub(crate) fn scale_param(disabled_when: Option<(&str, FieldValue)>) -> Param { let mut unit = fields.text("unit").map_or_else(|| Unit::Millimeters.label().to_string(), str::to_string); let mut scale = Some(fields.number("scale").unwrap_or(1.0)); let (lo, hi) = (*vectorcraft_cad::SCALE_RANGE.start(), *vectorcraft_cad::SCALE_RANGE.end()); - let shown = ui - .horizontal(|ui| { + let shown = Row::new() + .show(ui, |ui, _| { ui.label("1"); Select::new(tl!("Unit"), Bind::bound(&mut unit), &units).show(ui); ui.label("="); NumberField::new(tl!("Scale"), Bind::bound(&mut scale)).range(lo..=hi).show(ui); ui.label(tl!("Units")); }) - .response; + .output; let scale = scale.unwrap_or(1.0); if fields.text("unit") != Some(unit.as_str()) { fields.set("unit", unit); diff --git a/crates/ui-egui/src/dialogs/effect_rows.rs b/crates/ui-egui/src/dialogs/effect_rows.rs index f4e27e317b..580036d430 100644 --- a/crates/ui-egui/src/dialogs/effect_rows.rs +++ b/crates/ui-egui/src/dialogs/effect_rows.rs @@ -6,7 +6,8 @@ use std::ops::RangeInclusive; use craft::behavior::Mixed; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind}; use craft::ui::pickers::Select; use craft::ui::primitives::ContentPainterCx; @@ -198,19 +199,20 @@ pub(super) fn textured(cx: &EffectCx, fields: &DialogFields) -> Vec { let entries: Vec> = table.iter().map(|(label, value)| Entry::new((*value).to_owned(), data_label(label))).collect(); let current = fields.text("texture").unwrap_or_default(); let current = table.iter().find(|(_, value)| value.eq_ignore_ascii_case(current)).map_or("", |(_, value)| *value).to_owned(); - ui.horizontal(|ui| { - let picked = Select::new(lbl!("Texture"), Bind::given(current), &entries).show(ui); - if let Some(id) = picked.value().cloned() { - fields.set("texture", id); - } - // The pick is an edit of the rows, which the Appearance panel's editor applies. - cx.gesture(&picked.events); + let mut picked = None; + let shown = Row::new().show(ui, |ui, _| { + picked = Some(Select::new(lbl!("Texture"), Bind::given(current.clone()), &entries).show(ui)); if let Some((w, h)) = size { craft::ui::display::Text::new(format!("{w} × {h} px")).show(ui); } - picked.response - }) - .inner + }); + let Some(picked) = picked else { return shown.output }; + if let Some(id) = picked.value().cloned() { + fields.set("texture", id); + } + // The pick is an edit of the rows, which the Appearance panel's editor applies. + cx.gesture(&picked.events); + picked.response }) .companions([TEXTURE_IMAGE]); let own = ["texture", "texturePath", TEXTURE_IMAGE]; @@ -270,7 +272,7 @@ pub(super) fn radial_blur(cx: &EffectCx, fields: &DialogFields) -> Vec { let zoom = fields.text("method").is_some_and(|m| m.eq_ignore_ascii_case("zoom")); let mut next = c; let unit: RangeInclusive = 0.0..=1.0; - let row = ui.horizontal(|ui| { + let row = Row::new().show(ui, |ui, _| { let picker = PointPicker::new(Bind::given([Mixed::Same(c[0]), Mixed::Same(c[1])]), unit.clone(), unit.clone()) .label(lbl!("Blur Center")) .id_salt("point") @@ -279,7 +281,7 @@ pub(super) fn radial_blur(cx: &EffectCx, fields: &DialogFields) -> Vec { if let Some([Mixed::Same(x), Mixed::Same(y)]) = picker.value().cloned() { next = [x, y]; } - ui.vertical(|ui| { + Stack::new().show(ui, |ui, _| { for (axis, label) in [lbl!("Horizontal"), lbl!("Vertical")].into_iter().enumerate() { let shown = NumberField::new(label, Bind::given(Some(c[axis] * 100.0))) .unit("%") @@ -297,7 +299,7 @@ pub(super) fn radial_blur(cx: &EffectCx, fields: &DialogFields) -> Vec { fields.set("centerX", center_round(next[0].clamp(0.0, 1.0))); fields.set("centerY", center_round(next[1].clamp(0.0, 1.0))); } - row.response + row.output }) .companions(["centerX", "centerY"]); let rows = generic(cx, fields).into_iter().filter(|p| !matches!(p.key.as_str(), "centerX" | "centerY")); diff --git a/crates/ui-egui/src/dialogs/eps_options.rs b/crates/ui-egui/src/dialogs/eps_options.rs index 5c8a86007d..2a1ee5ec8b 100644 --- a/crates/ui-egui/src/dialogs/eps_options.rs +++ b/crates/ui-egui/src/dialogs/eps_options.rs @@ -15,8 +15,9 @@ use std::sync::Arc; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Show as _, TooltipSpec}; +use craft::ui::contract::{Bind, Show as _, ShowContainer as _, TooltipSpec}; use craft::ui::dialog::DialogId; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use serde_json::{Map, Value, json}; use vectorcraft_engine::cmd::{FlattenOptions, FlattenerPreset, fileio}; @@ -76,14 +77,16 @@ fn rows(presets: &Arc<[(String, String)]>) -> Vec { Param::section(tl!("Transparency")), choice_param("overprints", tl!("Overprints:"), Overprint::ALL.iter().map(|o| (o.id(), o.label()))), Param::custom("flattenerPreset", tl!("Preset:"), move |ui, fields, cx| { - ui.horizontal(|ui| { - let custom = fields.contains("flattener"); + let custom = fields.contains("flattener"); + let mut pressed = false; + let shown = Row::new().show(ui, |ui, _| { flatten::preset_picker(ui, fields, "flattenerPreset", &presets, custom); - if Button::new(tl!("Custom…")).show(ui).clicks > 0 { - cx.request_action("custom"); - } - }) - .response + pressed = Button::new(tl!("Custom…")).show(ui).clicks > 0; + }); + if pressed { + cx.request_action("custom"); + } + shown.output }) .resets(["flattener"]), Param::section(tl!("Fonts")), diff --git a/crates/ui-egui/src/dialogs/hpgl_options.rs b/crates/ui-egui/src/dialogs/hpgl_options.rs index 3998523a57..3cfe0ecdfc 100644 --- a/crates/ui-egui/src/dialogs/hpgl_options.rs +++ b/crates/ui-egui/src/dialogs/hpgl_options.rs @@ -17,7 +17,7 @@ use craft::ui::buttons::{Button, IconButton}; use craft::ui::choice::{Radio, RadioGroup, Swatch}; use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _}; use craft::ui::dialog::DialogId; -use craft::ui::layout_components::Stack; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog}; use craft::ui::runtime::env::Env; use craft::ui::style::rgba_color; @@ -141,52 +141,88 @@ fn pen_key(i: usize) -> String { /// Pens: One Pen per Color (`pens` null) or Pen Table (`pens` the colors, pen 1's first), with a /// row per pen (its number, color and a Remove button) and Add. fn pens_param() -> Param { - Param::custom("pens", tl!("Pens:"), |ui, fields, cx| ui.vertical(|ui| pens_ui(ui, fields, cx)).response) - .companions([SET_ASIDE, PEN_ERROR]) - .full_width() + Param::custom("pens", tl!("Pens:"), |ui, fields, cx| { + take_picked_pens(fields); + // The rows draw from the values as they stand here and the edits apply after them: the stack's body may run + // twice in a pass. + let mut drawn = fields.clone(); + let mut asked = PensAsked::default(); + let shown = Stack::new().show(ui, |ui, _| { + asked = pens_ui(ui, &drawn, cx); + if let Some(p) = &asked.pens { + drawn.set("pens", FieldValue::Json(Value::Array(p.clone()))); + } + }); + // An edit of the rows in any run of the body is in `drawn`; a switch of Pen Table drops it. + let edited = table(&drawn).filter(|p| asked.table.is_none() && table(fields).as_ref() != Some(p)); + match asked.table { + Some(true) => cx.request_action("penTable"), + Some(false) => { + let _ = set_pen_table(fields, false, || Ok(Vec::new())); + fields.remove(PEN_ERROR); + } + None => {} + } + if let Some(pens) = edited { + fields.set("pens", FieldValue::Json(Value::Array(pens))); + } + shown.output + }) + .companions([SET_ASIDE, PEN_ERROR]) + .full_width() +} + +/// What the pens rows asked for in one run. +#[derive(Default)] +struct PensAsked { + /// Pen Table was turned on (`true`) or off. + table: Option, + /// The pen table after an edit of its rows. + pens: Option>, +} + +/// Writes the colors the picker answered into the pen table. +fn take_picked_pens(fields: &mut DialogFields) { + let Some(mut pens) = table(fields).filter(|a| a.len() <= MAX_PENS) else { return }; + let mut changed = false; + for (i, pen) in pens.iter_mut().enumerate() { + if let Some([r, g, b]) = fields.color(&pen_key(i)) { + let byte = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8; + *pen = json!(format!("#{:02x}{:02x}{:02x}", byte(r), byte(g), byte(b))); + fields.remove(&pen_key(i)); + changed = true; + } + } + if changed { + fields.set("pens", FieldValue::Json(Value::Array(pens))); + } } /// The pens row. Switching to Pen Table asks the host (`penTable`): the table starts from the document's pens, which /// this draw cannot reach. -fn pens_ui(ui: &mut egui::Ui, fields: &mut DialogFields, cx: &mut CustomContext) { - let mut list = table(fields); - let mut changed = false; - // Colours the picker answered. - if let Some(pens) = list.as_mut() { - for (i, pen) in pens.iter_mut().enumerate() { - if let Some([r, g, b]) = fields.color(&pen_key(i)) { - let byte = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8; - *pen = json!(format!("#{:02x}{:02x}{:02x}", byte(r), byte(g), byte(b))); - fields.remove(&pen_key(i)); - changed = true; - } - } - } +fn pens_ui(ui: &mut egui::Ui, fields: &DialogFields, cx: &mut CustomContext) -> PensAsked { + let mut asked = PensAsked::default(); + let list = table(fields); let mut on = list.is_some(); RadioGroup::new(tl!("Pens:"), Bind::bound(&mut on)).show(ui, |ui, _| { Radio::new(false).label(tl!("One Pen per Color")).show(ui); Radio::new(true).label(tl!("Pen Table")).show(ui); }); if on != list.is_some() { - if on { - cx.request_action("penTable"); - } else { - let _ = set_pen_table(fields, false, || Ok(Vec::new())); - fields.remove(PEN_ERROR); - list = None; - } + asked.table = Some(on); } - if let Some(e) = fields.text(PEN_ERROR) { + if let Some(e) = fields.text(PEN_ERROR).filter(|_| asked.table != Some(false)) { let error = rgba_color(Env::of(ui).tokens.tokens().color.status.bad.fg); ui.colored_label(error, crate::i18n::message(crate::i18n::current(), e)); } // A table longer than a plot takes (set through `ui.dialog.set`) draws no rows: OK refuses it. - let Some(mut pens) = list.filter(|a| a.len() <= MAX_PENS) else { return }; + let Some(mut pens) = list.filter(|a| asked.table.is_none() && a.len() <= MAX_PENS) else { return asked }; + let mut changed = false; let n = pens.len(); let mut remove = None; Stack::new().scroll(Scroll::vertical()).room_height(180.0).show(ui, |ui, _| { for (i, pen) in pens.iter_mut().enumerate() { - ui.horizontal(|ui| { + Row::new().id_salt(("hpgl-pen-row", i)).show(ui, |ui, _| { ui.label((i + 1).to_string()); let mut color = pen.as_str().and_then(Rgba::from_hex).unwrap_or(Rgba::rgb(0, 0, 0)); if Swatch::new(tl!("Pen color"), Srgba::from(color)).show(ui).clicked { @@ -216,8 +252,9 @@ fn pens_ui(ui: &mut egui::Ui, fields: &mut DialogFields, cx: &mut CustomContext) changed = true; } if changed { - fields.set("pens", FieldValue::Json(Value::Array(pens))); + asked.pens = Some(pens); } + asked } /// Starts Pen Table for dialog `id`: the table the export would give the art, or the reason it cannot. It runs from diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 00151a7f2c..8bf05fe7d8 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -8,9 +8,10 @@ use craft::theme::{Rgba, Srgba}; use craft::ui::choice::Swatch; -use craft::ui::contract::{Bind, Entry, Show as _}; +use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; use craft::ui::display::Text; use craft::ui::form::SliderField; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::pickers::Select; use craft::ui::runtime::env::UnitKind; @@ -216,25 +217,28 @@ fn resolution_row() -> Param { let preset = RESOLUTIONS.iter().position(|p| *p == ppi).filter(|_| fields.bool("__otherPpi") != Some(true)); let other = RESOLUTION_LABELS.len() - 1; let entries: Vec> = RESOLUTION_LABELS.iter().enumerate().map(|(i, label)| Entry::new(i, tl!(*label))).collect(); - ui.horizontal(|ui| { - if let Some(i) = Select::new(tl!("Resolution:"), Bind::given(preset.unwrap_or(other)), &entries).show(ui).value().copied() { - if let Some(p) = RESOLUTIONS.get(i) { - fields.set("ppi", *p); - } - fields.set("__otherPpi", i == other); - } + let (mut picked, mut typed) = (None, None); + let shown = Row::new().show(ui, |ui, _| { + picked = Select::new(tl!("Resolution:"), Bind::given(preset.unwrap_or(other)), &entries).show(ui).value().copied(); if preset.is_none() { let field = NumberField::new(tl!("Resolution:"), Bind::given(Some(ppi))) .range(1.0..=4608.0) .step(1.0) .unit_kind(UnitKind::PixelsPerInch) .show(ui); - if let Some(Some(v)) = field.edit.value().copied() { - fields.set("ppi", v); - } + typed = field.edit.value().copied().flatten(); } - }) - .response + }); + if let Some(i) = picked { + if let Some(p) = RESOLUTIONS.get(i) { + fields.set("ppi", *p); + } + fields.set("__otherPpi", i == other); + } + if let Some(v) = typed { + fields.set("ppi", v); + } + shown.output }) .companions(["__otherPpi"]) .opens_with(72.0) @@ -263,18 +267,21 @@ fn color_choice( let at = ids.iter().position(|v| current.eq_ignore_ascii_case(v)).unwrap_or(ids.len()); let start = first(fields); let entries: Vec> = labels.iter().enumerate().skip(start).map(|(i, l)| Entry::new(i, tl!(*l))).collect(); - ui.horizontal(|ui| { - if let Some(i) = Select::new(tl!(label), Bind::given(at.max(start)), &entries).show(ui).value().copied() { - fields.set(key, ids.get(i).copied().unwrap_or(OTHER_COLOR)); + let color = (at == ids.len()).then(|| Srgba::from(Rgba::from_hex(¤t).unwrap_or(Rgba::rgb(128, 128, 128)))); + let (mut picked, mut pick_color) = (None, false); + let shown = Row::new().show(ui, |ui, _| { + picked = Select::new(tl!(label), Bind::given(at.max(start)), &entries).show(ui).value().copied(); + if let Some(color) = color { + pick_color = Swatch::new(tl!(label), color).show(ui).clicked; } - if at == ids.len() { - let color = Srgba::from(Rgba::from_hex(¤t).unwrap_or(Rgba::rgb(128, 128, 128))); - if Swatch::new(tl!(label), color).show(ui).clicked { - cx.pick_color(key, color); - } - } - }) - .response + }); + if let Some(i) = picked { + fields.set(key, ids.get(i).copied().unwrap_or(OTHER_COLOR)); + } + if let Some(color) = color.filter(|_| pick_color) { + cx.pick_color(key, color); + } + shown.output }) } @@ -310,18 +317,17 @@ fn jpeg_rows(screens: bool) -> Vec { fn quality_row() -> Param { Param::custom("quality", tl!("Quality:"), |ui, fields, _| { let q = (fields.number("quality").unwrap_or(90.0) / 10.0).round().clamp(0.0, 10.0); - ui.horizontal(|ui| { + let mut slid = None; + let shown = Row::new().show(ui, |ui, _| { let out = SliderField::new(tl!("Quality:"), Bind::given(q), 0.0..=10.0).step(1.0).show(ui); - let q = match out.edit.value() { - Some(v) => { - fields.set("quality", v.round() * 10.0); - v.round() - } - None => q, - }; + slid = out.edit.value().map(|v| v.round()); + let q = slid.unwrap_or(q); Text::new(tl!(QUALITY_BANDS.get(q as usize).copied().unwrap_or_default())).show(ui); - }) - .response + }); + if let Some(v) = slid { + fields.set("quality", v * 10.0); + } + shown.output }) .opens_with(90.0) } diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index 921dd8d37f..b65a1f40cb 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -35,7 +35,8 @@ use vectorcraft_eps::{Level, Overprint, Preview}; use craft::theme::variant::Tone; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, CollectionEvent, Show as _, ShowCollection as _, TooltipSpec}; +use craft::ui::contract::{Bind, CollectionEvent, Show as _, ShowCollection as _, ShowContainer as _, TooltipSpec}; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{ThumbAspect, ToggleState}; use craft::ui::notices::Notice; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; @@ -399,10 +400,12 @@ fn boards_picker(ui: &mut egui::Ui, fields: &mut DialogFields, menus: &Menus) -> let mut boards = picked_boards(fields, n); let before = boards.clone(); let files = board_files(menus.doc.as_deref(), fields.text("path").unwrap_or_default(), &boards); - let response = ui - .vertical(|ui| { + let response = Stack::new() + .show(ui, |ui, _| { + // Each run of the body starts from the checks as they stood: a check flips them, and the body may run twice. + boards.clone_from(&before); ui.label(tl!("A legacy .ai file holds one artboard: each artboard you check is saved as a separate file.")); - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { if Button::new(tl!("Select All")).show(ui).clicks > 0 { boards.iter_mut().for_each(|b| *b = true); } @@ -444,7 +447,7 @@ fn boards_picker(ui: &mut egui::Ui, fields: &mut DialogFields, menus: &Menus) -> } } }) - .response; + .output; if boards != before || boards_in(fields).is_none() { fields.set("boards", FieldValue::Json(json!(boards))); } diff --git a/crates/ui-egui/src/dialogs/swatch_options.rs b/crates/ui-egui/src/dialogs/swatch_options.rs index cb848e5c85..6def4534d4 100644 --- a/crates/ui-egui/src/dialogs/swatch_options.rs +++ b/crates/ui-egui/src/dialogs/swatch_options.rs @@ -23,6 +23,7 @@ use craft::ui::choice::Swatch; use craft::ui::contract::{Bind, Show as _, ShowContainer as _}; use craft::ui::dialog::DialogId; use craft::ui::form::Field; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::Label; use craft::ui::text::HexField; @@ -207,10 +208,8 @@ pub(super) fn colour_rows(gamut: Gamut<'static>) -> Vec { // Spot colours are always global. Param::new("global", tl!("Global").to_owned(), ParamKind::bool(false)).enabled_when("type", "process").disabled_value(true), Param::new("mode", field_label(tl!("Color Mode:")), ParamKind::choice(modes, Some("rgb".to_owned()))), - Param::custom("color", tl!("Color").to_owned(), move |ui, fields, context| { - ui.vertical(|ui| edit_colour(ui, fields, &gamut, context)).response - }) - .companions(["hex", "hsb"]), + Param::custom("color", tl!("Color").to_owned(), move |ui, fields, context| edit_colour(ui, fields, &gamut, context)) + .companions(["hex", "hsb"]), ] } @@ -412,7 +411,7 @@ pub(super) fn correct(app: &mut VectorcraftApp, id: DialogId) { /// The colour row: one slider and value field per component of the dialog's mode, the hex field (RGB, HSB and /// Web), a chip of the colour and under it the mode's warnings. The colour follows the mode: a colour in another /// model is converted when the mode changes. -fn edit_colour(ui: &mut egui::Ui, fields: &mut DialogFields, gamut: &Gamut<'static>, context: &mut CustomContext) { +fn edit_colour(ui: &mut egui::Ui, fields: &mut DialogFields, gamut: &Gamut<'static>, context: &mut CustomContext) -> egui::Response { // A hex colour set from outside the row (automation) replaces the colour once. if let Some(hex) = fields.text("hex").map(str::to_owned) { fields.remove("hex"); @@ -439,8 +438,9 @@ fn edit_colour(ui: &mut egui::Ui, fields: &mut DialogFields, gamut: &Gamut<'stat warnings.push((Warning::Web, ColorWarning::web_colors(tl!("Out of Web Color Warning").to_owned(), Srgba::rgb(r, g, b)))); } let mut edit: Option<(Color, Option)> = None; - ui.horizontal_top(|ui| { - ui.vertical(|ui| { + let mut actions = Vec::new(); + let shown = Row::new().show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { for (i, ch) in model.channels().iter().enumerate() { let mut rule = ChannelRule::of(ch); if web { @@ -478,21 +478,26 @@ fn edit_colour(ui: &mut egui::Ui, fields: &mut DialogFields, gamut: &Gamut<'stat } } }); - ui.vertical(|ui| { + Stack::new().show(ui, |ui, _| { Swatch::new(tl!("Color").to_owned(), near).show(ui); + actions.clear(); for (warning, chip) in &warnings { if ColorWarningChip::new(chip).show(ui).clicked { - context.request_action(warning.action()); + actions.push(warning.action()); } } }); }); + for action in actions { + context.request_action(action); + } if let Some((c, kept)) = edit { set_color(fields, c); if let Some(k) = kept.filter(|k| k.model == HsbModel.id()) { fields.set("hsb", FieldValue::Json(json!([k.values[0], k.values[1], k.values[2]]))); } } + shown.output } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/tests_custom_rows.rs b/crates/ui-egui/src/dialogs/tests_custom_rows.rs new file mode 100644 index 0000000000..a7bae37aea --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_custom_rows.rs @@ -0,0 +1,73 @@ +//! Dialogs whose custom rows lay out several controls side by side or one under another take the width of their rows, +//! read from the access tree of the window. + +use egui::accesskit::Role; +use serde_json::{Value, json}; +use vectorcraft_engine::cmd::fileio::FORMATS; + +use super::tests::{SCREEN, app, frame, settle}; +use crate::VectorcraftApp; + +/// The width of the dialog named `title` once it has settled. +fn dialog_width(app: &mut VectorcraftApp, title: &str) -> f32 { + settle(app); + let out = frame(app, vec![]); + let update = out.platform_output.accesskit_update.expect("an accessibility tree"); + let dialog = update.nodes.iter().find(|(_, node)| node.role() == Role::Dialog && node.label() == Some(title)); + let bounds = dialog.and_then(|(_, node)| node.bounds()).unwrap_or_else(|| panic!("the {title} dialog is open")); + (bounds.x1 - bounds.x0) as f32 +} + +/// Writes `value` into `key` of the top dialog, as automation does. +fn set(app: &VectorcraftApp, key: &str, value: Value) { + let ctx = app.ui_ctx.clone().expect("a window app"); + let host = app.dialogs().expect("a dialog host"); + host.with(|h| { + let id = h.open_dialogs().last().map(|d| d.id).expect("an open dialog"); + h.set_json_field(&ctx, id, key, value) + }) + .unwrap(); +} + +/// Opens the options of raster format `id` for an export. +fn raster_options(app: &mut VectorcraftApp, id: &str) { + let f = FORMATS.iter().find(|f| f.id == id).expect("a raster format"); + super::png_options::open(app, f, json!({"format": id, "path": format!("/out/a.{id}")})); +} + +/// A custom row drawn as an egui layout measured as wide as the room the dialog offered it, so the dialog took the +/// window's whole width. Each dialog here holds such a row and stays well inside the window. +#[test] +fn dialogs_with_custom_rows_take_the_width_of_their_rows() { + let half = SCREEN.x / 2.0; + + let mut a = app(); + crate::menus::invoke(&mut a, "ui.dxfOptionsDialog", json!({})); + let dxf = dialog_width(&mut a, "DXF Options"); + + let mut a = app(); + crate::menus::invoke(&mut a, "ui.newSwatch", json!({})); + let swatch = dialog_width(&mut a, "New Swatch"); + + let mut a = app(); + raster_options(&mut a, "png"); + settle(&mut a); + set(&a, "ppi", json!(100)); + set(&a, "__otherPpi", json!(true)); + set(&a, "background", json!("#336699")); + let png = dialog_width(&mut a, "PNG Options"); + + let mut a = app(); + raster_options(&mut a, "jpg"); + let jpeg = dialog_width(&mut a, "JPEG Options"); + + let mut a = app(); + a.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 120, "height": 80})).unwrap(); + a.run("select.all", json!({})).unwrap(); + super::effect::open(&mut a, &json!({"effect": "blur.radial"})).unwrap(); + let blur = dialog_width(&mut a, "Radial Blur"); + + for (name, width) in [("DXF Options", dxf), ("New Swatch", swatch), ("PNG Options", png), ("JPEG Options", jpeg), ("Radial Blur", blur)] { + assert!(width < half, "{name} is {width} pt wide in a {} pt window", SCREEN.x); + } +} diff --git a/crates/ui-egui/src/dialogs/tests_hpgl.rs b/crates/ui-egui/src/dialogs/tests_hpgl.rs index 600e1d8fa2..dab1dbe8c6 100644 --- a/crates/ui-egui/src/dialogs/tests_hpgl.rs +++ b/crates/ui-egui/src/dialogs/tests_hpgl.rs @@ -160,6 +160,24 @@ fn pen_table_starts_from_the_art_s_pens_and_comes_back() { assert_eq!(pens(&fields(&app)), json!(automatic)); } +/// A press of Add adds one pen and a press of One Pen per Color sets the table aside, though the rows' body may run +/// twice in the pass that reads the press. +#[test] +fn pen_rows_apply_each_press_once() { + let (mut app, _) = app(1); + app.run("ui.hpglOptionsDialog", json!({})).unwrap(); + set(&mut app, "pens", json!(["#ff0000", "#000000"])); + frame(&mut app); + press_control(&mut app, json!({"name": "Add", "role": "Button"})); + frame(&mut app); + assert_eq!(pens(&fields(&app)), json!(["#ff0000", "#000000", "#000000"])); + press_control(&mut app, json!({"name": "One Pen per Color", "role": "RadioButton"})); + frame(&mut app); + let d = fields(&app); + assert!(pens(&d).is_null()); + assert_eq!(serde_json::to_value(d.get("__pens")).unwrap(), json!(["#ff0000", "#000000", "#000000"])); +} + /// Pen Table with options the export refuses keeps One Pen per Color and says why, rather than /// starting from one black pen that the corrected options would keep. #[test] diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index 3150baae30..c9fbd71eb0 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -22,7 +22,8 @@ use std::sync::OnceLock; use craft::behavior::IconId; use craft::behavior::overlay::Side; use craft::ui::buttons::ToggleButton; -use craft::ui::contract::{Bind, Outcome as _, Show as _}; +use craft::ui::contract::{Bind, Outcome as _, Show as _, ShowContainer as _}; +use craft::ui::layout_components::Row; use craft::ui::menu::PanelRow; use craft::ui::primitives::IconSpec; use craft::ui::rails::{DrawerGroup, DropAt, SlotId, ToolRailOutput, ToolSlot, ToolbarDrawer, ToolbarEdit}; @@ -456,7 +457,7 @@ pub(crate) fn drawer(app: &mut VectorcraftApp, ui: &mut Ui, rail_out: &ToolRailO if target.is_some() { return; } - ui.horizontal(|ui| { + Row::new().show(ui, |ui, _| { for (name, label, icon) in crate::state::ToolbarShow::CONTROLS { let on = shown.get(name); let button = ToggleButton::new(tl!(label), Bind::given(on)).icon(IconSpec::svg(IconId::new(icon))).icon_only(); diff --git a/crates/ui-egui/src/original_editor.rs b/crates/ui-egui/src/original_editor.rs index 5888f2fa26..9089ede4f2 100644 --- a/crates/ui-egui/src/original_editor.rs +++ b/crates/ui-egui/src/original_editor.rs @@ -5,8 +5,9 @@ use std::path::Path; use craft::host::{Host, PickId, PickRequest}; use craft::ui::buttons::Button; -use craft::ui::contract::{Props as _, Show as _}; +use craft::ui::contract::{Props as _, Show as _, ShowContainer as _}; use craft::ui::display::Text; +use craft::ui::layout_components::Row; use serde::{Deserialize, Serialize}; use crate::VectorcraftApp; @@ -118,19 +119,21 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, enabled: bool) { { app.status(e); } - ui.horizontal_wrapped(|ui| { + let chosen = app.original_editor.choice.path.clone(); + let (mut choose, mut default) = (false, false); + Row::new().wrap(true).show(ui, |ui, _| { Text::new(tl!("Edit Original with:")).show(ui); - let name = app.original_editor.choice.path.as_deref().and_then(|p| Path::new(p).file_name()); + let name = chosen.as_deref().and_then(|p| Path::new(p).file_name()); Text::new(name.map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "PhotoCraft".into())).show(ui); - if Button::new(tl!("Choose…")).enabled(enabled).show(ui).clicked() - && let Err(e) = pick(app) - { - app.status(e); - } - if app.original_editor.choice.path.is_some() && Button::new("PhotoCraft").enabled(enabled).show(ui).clicked() { - reset(app); - } + choose = Button::new(tl!("Choose…")).enabled(enabled).show(ui).clicked(); + default = chosen.is_some() && Button::new("PhotoCraft").enabled(enabled).show(ui).clicked(); }); + if choose && let Err(e) = pick(app) { + app.status(e); + } + if default { + reset(app); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/prefs_dialog/model.rs b/crates/ui-egui/src/prefs_dialog/model.rs index 72c5ec628c..b4693d5830 100644 --- a/crates/ui-egui/src/prefs_dialog/model.rs +++ b/crates/ui-egui/src/prefs_dialog/model.rs @@ -8,8 +8,9 @@ use std::sync::{Mutex, PoisonError}; use craft::host::{PickKind, PickRequest}; use craft::theme::Rgba; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Entry, Show as _}; +use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; use craft::ui::form::{SliderField, SliderFieldLayout}; +use craft::ui::layout_components::Row; use craft::ui::patterns::preferences::{GroupSpec, PageSpec, PathSetting, PrefValue, PreferencesDraft, PreferencesModel, RowKind, RowSpec}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; use serde_json::{Map, Value, json}; @@ -350,10 +351,11 @@ impl PreferencesModel for Live<'_> { } "prefsFile" => { let (mut export, mut import, mut reset) = (false, false, false); - ui.horizontal_wrapped(|ui| { + let web = crate::io::is_web(self.app); + Row::new().wrap(true).show(ui, |ui, _| { export = Button::new(tl!("Export Preferences…")).show(ui).clicked(); // Not on the web, whose open dialog answers with the file's contents, not a path to import. - if !crate::io::is_web(self.app) { + if !web { import = Button::new(tl!("Import Preferences…")).show(ui).clicked(); } reset = Button::new(tl!("Reset Preferences")).show(ui).clicked(); From bd6d7c9117cd0f17d613cb40a31e027b6d93f08b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 16:58:01 -0800 Subject: [PATCH 2/2] Dialogs: rows of controls in the 3D, Character Style, Adjust Colors and Color Guide dialogs are framework Rows and Stacks, and presses inside a row apply after it A framework container may run its body more than once in a pass. The HP-GL pen rows now draw from the dialog's values on every run and report a typed color, Remove, Add and a swatch press, which apply once after the rows; the picker opens after them. A picked pen color is no longer left unread when the table is longer than a plot takes. The classic 3D surface navigator and Map Art buttons, Bevel Shape, the light's Add and Delete buttons and its color row, Stylistic Sets, the Adjust Colors channels and the Color Guide Options sliders use Row and Stack the same way. A Stack's measuring run no longer writes the values the Adjust Colors and Color Guide Options rows edit. --- .../ui-egui/src/dialogs/char_style_options.rs | 9 +- crates/ui-egui/src/dialogs/color_balance.rs | 3 +- .../src/dialogs/color_guide_options.rs | 3 +- crates/ui-egui/src/dialogs/form.rs | 23 ++++- crates/ui-egui/src/dialogs/hpgl_options.rs | 49 +++++----- crates/ui-egui/src/dialogs/revolve.rs | 96 ++++++++++--------- crates/ui-egui/src/dialogs/tests_hpgl.rs | 20 +++- crates/ui-egui/src/dialogs/three_d_classic.rs | 41 ++++---- 8 files changed, 150 insertions(+), 94 deletions(-) diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 9fcb532c33..25c7891020 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -8,8 +8,9 @@ use std::sync::Arc; use craft::behavior::Mixed; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Entry, Outcome as _, Props as _, Show as _}; +use craft::ui::contract::{Bind, Entry, Outcome as _, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogResult, FieldRefusal}; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{ DialogFields, FieldValue, HostedPropertiesDialog, Param, ParamKind, PropertiesDialog, PropertiesTab, PropertyRow, TabLayout, }; @@ -843,7 +844,9 @@ fn sets_row() -> Param { .and_then(|v| v.as_array().map(|tags| tags.iter().filter_map(Value::as_str).map(str::to_string).collect())) .unwrap_or_default(); let mut clicked = None; - let line = ui.horizontal_wrapped(|ui| { + let line = Row::new().wrap(true).show(ui, |ui, _| { + // The row's body may run more than once in a pass: the last run's click applies. + clicked = None; for set in &vectorcraft_text::EXTRA_FEATURES[..20] { let current = listed.iter().find(|t| bare(t) == *set).map(|t| !t.starts_with('-')); if let (_, Some(next)) = tri_box(ui, current, Some(Label::from(set.to_string())), set) { @@ -864,7 +867,7 @@ fn sets_row() -> Param { fields.set("ot_sets", FieldValue::Json(json!(listed))); } } - line.response + line.output }) } diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index 5dfeb4e018..c82918426b 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -199,12 +199,11 @@ fn track(key: &str, x: f32) -> Srgba { /// The channel rows of the current mode. fn channels(ui: &mut egui::Ui, fields: &mut DialogFields, _cx: &mut CustomContext) -> egui::Response { - ui.vertical(|ui| { + super::form::stacked(ui, fields, |ui, fields| { for (key, label) in mode(fields).channels { percent_row(ui, fields, key, label, |x| track(key, x)); } }) - .response } fn rows() -> Vec { diff --git a/crates/ui-egui/src/dialogs/color_guide_options.rs b/crates/ui-egui/src/dialogs/color_guide_options.rs index 37836565e4..721064005b 100644 --- a/crates/ui-egui/src/dialogs/color_guide_options.rs +++ b/crates/ui-egui/src/dialogs/color_guide_options.rs @@ -32,12 +32,11 @@ pub fn open(app: &mut VectorcraftApp) { fields.set("steps", f64::from(current.steps)); fields.set("amount", f64::from(current.amount)); let steps = Param::custom("steps", field_label(tl!("Steps:")), |ui, fields, _| { - ui.vertical(|ui| { + super::form::stacked(ui, fields, |ui, fields| { slider(ui, fields, "steps", tl!("Steps:"), 1.0..=f64::from(GuideOptions::MAX_STEPS), None); let ends = [(0.0, tl!("Less").to_owned()), (100.0, tl!("More").to_owned())]; slider(ui, fields, "amount", tl!("Variation:"), 0.0..=100.0, Some(ends)); }) - .response }) .companions(["amount"]); let variations = Param::custom("variations", field_label(tl!("Variations:")), move |ui, fields, _| { diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 538141fc11..6d81d18214 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -4,9 +4,11 @@ use std::collections::HashMap; -use craft::ui::contract::{Bind, Show as _}; +use craft::ui::contract::{Bind, Show as _, ShowContainer as _}; +use craft::ui::layout_components::Stack; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind, encode}; use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; +use craft::ui::runtime::measure; use craft::ui::text::TextField; use craft::ui::value_drag::SliderScale; use serde_json::{Map, Value, json}; @@ -200,6 +202,25 @@ pub(crate) fn fields_of(params: &[Param], json: &Map) -> DialogFi fields } +/// Shows `body` in a `Stack` as rows of a custom dialog row that edit `fields`. The stack may run its body more than +/// once in a pass: every run edits a copy of the values as they stand here, and the copy of the run that is not a +/// measuring run replaces them after the stack. +pub(super) fn stacked(ui: &mut egui::Ui, fields: &mut DialogFields, mut body: impl FnMut(&mut egui::Ui, &mut DialogFields)) -> egui::Response { + let before = fields.clone(); + let mut edited = None; + let shown = Stack::new().show(ui, |ui, _| { + let mut run = before.clone(); + body(ui, &mut run); + if measure::effect(ui.ctx(), "dialog rows edit their values") { + edited = Some(run); + } + }); + if let Some(edited) = edited { + *fields = edited; + } + shown.output +} + /// The command or effect parameters of the dialog values `fields`: the UI-only keys (`__*`, `preview`) are dropped. pub(crate) fn json_of(params: &[Param], fields: &DialogFields) -> Map { fields diff --git a/crates/ui-egui/src/dialogs/hpgl_options.rs b/crates/ui-egui/src/dialogs/hpgl_options.rs index 3cfe0ecdfc..50eab143f5 100644 --- a/crates/ui-egui/src/dialogs/hpgl_options.rs +++ b/crates/ui-egui/src/dialogs/hpgl_options.rs @@ -18,7 +18,7 @@ use craft::ui::choice::{Radio, RadioGroup, Swatch}; use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _}; use craft::ui::dialog::DialogId; use craft::ui::layout_components::{Row, Stack}; -use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog}; use craft::ui::runtime::env::Env; use craft::ui::style::rgba_color; use craft::ui::text::TextField; @@ -143,18 +143,13 @@ fn pen_key(i: usize) -> String { fn pens_param() -> Param { Param::custom("pens", tl!("Pens:"), |ui, fields, cx| { take_picked_pens(fields); - // The rows draw from the values as they stand here and the edits apply after them: the stack's body may run - // twice in a pass. - let mut drawn = fields.clone(); + // The stack's body may run more than once in a pass: every run draws from the values as they stand here, and + // what the last run asked for applies after the stack. let mut asked = PensAsked::default(); - let shown = Stack::new().show(ui, |ui, _| { - asked = pens_ui(ui, &drawn, cx); - if let Some(p) = &asked.pens { - drawn.set("pens", FieldValue::Json(Value::Array(p.clone()))); - } - }); - // An edit of the rows in any run of the body is in `drawn`; a switch of Pen Table drops it. - let edited = table(&drawn).filter(|p| asked.table.is_none() && table(fields).as_ref() != Some(p)); + let shown = Stack::new().show(ui, |ui, _| asked = pens_ui(ui, fields)); + if let Some((i, color)) = asked.pick { + cx.pick_color(&pen_key(i), color); + } match asked.table { Some(true) => cx.request_action("penTable"), Some(false) => { @@ -163,7 +158,7 @@ fn pens_param() -> Param { } None => {} } - if let Some(pens) = edited { + if let Some(pens) = asked.pens { fields.set("pens", FieldValue::Json(Value::Array(pens))); } shown.output @@ -179,11 +174,13 @@ struct PensAsked { table: Option, /// The pen table after an edit of its rows. pens: Option>, + /// The pen whose swatch was pressed, with its color: the picker opens on it. + pick: Option<(usize, Srgba)>, } /// Writes the colors the picker answered into the pen table. fn take_picked_pens(fields: &mut DialogFields) { - let Some(mut pens) = table(fields).filter(|a| a.len() <= MAX_PENS) else { return }; + let Some(mut pens) = table(fields) else { return }; let mut changed = false; for (i, pen) in pens.iter_mut().enumerate() { if let Some([r, g, b]) = fields.color(&pen_key(i)) { @@ -200,7 +197,7 @@ fn take_picked_pens(fields: &mut DialogFields) { /// The pens row. Switching to Pen Table asks the host (`penTable`): the table starts from the document's pens, which /// this draw cannot reach. -fn pens_ui(ui: &mut egui::Ui, fields: &DialogFields, cx: &mut CustomContext) -> PensAsked { +fn pens_ui(ui: &mut egui::Ui, fields: &DialogFields) -> PensAsked { let mut asked = PensAsked::default(); let list = table(fields); let mut on = list.is_some(); @@ -219,29 +216,35 @@ fn pens_ui(ui: &mut egui::Ui, fields: &DialogFields, cx: &mut CustomContext) -> let Some(mut pens) = list.filter(|a| asked.table.is_none() && a.len() <= MAX_PENS) else { return asked }; let mut changed = false; let n = pens.len(); + // What the rows asked for: a typed color per pen, the pen whose swatch or Remove was pressed. Each run of the + // stack's body starts them afresh from the same pens. + let mut typed: Vec> = vec![None; n]; let mut remove = None; Stack::new().scroll(Scroll::vertical()).room_height(180.0).show(ui, |ui, _| { - for (i, pen) in pens.iter_mut().enumerate() { + typed.iter_mut().for_each(|t| *t = None); + (remove, asked.pick) = (None, None); + for (i, pen) in pens.iter().enumerate() { Row::new().id_salt(("hpgl-pen-row", i)).show(ui, |ui, _| { ui.label((i + 1).to_string()); let mut color = pen.as_str().and_then(Rgba::from_hex).unwrap_or(Rgba::rgb(0, 0, 0)); if Swatch::new(tl!("Pen color"), Srgba::from(color)).show(ui).clicked { - cx.pick_color(&pen_key(i), Srgba::from(color)); + asked.pick = Some((i, Srgba::from(color))); } let before = color; TextField::hex(tl!("Pen color"), Bind::bound(&mut color)).id_salt(("hpgl-pen", i)).show(ui); - if color != before - && let Some(typed) = pen_color(&color.to_hex()) - { - *pen = json!(typed); - changed = true; - } + typed[i] = (color != before).then(|| pen_color(&color.to_hex())).flatten(); if IconButton::new(IconId::new("trash")).label(tl!("Remove")).enabled(n > 1).show(ui).clicks > 0 { remove = Some(i); } }); } }); + for (pen, typed) in pens.iter_mut().zip(typed) { + if let Some(typed) = typed { + *pen = json!(typed); + changed = true; + } + } if Button::new(tl!("Add")).enabled(n < MAX_PENS).show(ui).clicks > 0 { // A new pen starts as the last one's color, ready to be changed. pens.push(pens.last().cloned().unwrap_or_else(|| json!("#000000"))); diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 3804c4ea3a..a61190970e 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -9,7 +9,8 @@ use craft::behavior::{DisplayOrder, ItemSource, SelectionChange}; use craft::theme::Srgba; use craft::ui::buttons::Button; use craft::ui::contract::Entry; -use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, clicked}; +use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _, clicked}; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamKind, ParamRows}; use craft::ui::pickers::Select; use craft::ui::runtime::env::LengthUnits; @@ -369,19 +370,23 @@ pub(crate) fn bevel_row(data: &Data, effect: &str, place: Place) -> Param { }; let default_at = options[..builtin].iter().position(|(_, v, _)| *v == default); let titles: Vec = options.iter().map(|(l, _, _)| l.clone()).collect(); - ui.horizontal(|ui| { - if let Some((_, v, c)) = pick(ui, c3("Bevel Shape"), &titles, current, default_at).and_then(|i| options.get(i)) { - set_value(fields, "bevel", v); - if let Some((n, p)) = c { - set_value(fields, BEVEL_NAME, &json!(n)); - set_value(fields, BEVEL_PROFILE, p); - } + // The row's body may run more than once in a pass: it reports the pick and the press, which apply after it. + let (mut picked, mut edit) = (None, false); + let row = Row::new().show(ui, |ui, _| { + picked = pick(ui, c3("Bevel Shape"), &titles, current, default_at); + edit = place == Place::Panel && pressed(ui, tl!("Edit Bevels…"), file, None); + }); + if let Some((_, v, c)) = picked.and_then(|i| options.get(i)) { + set_value(fields, "bevel", v); + if let Some((n, p)) = c { + set_value(fields, BEVEL_NAME, &json!(n)); + set_value(fields, BEVEL_PROFILE, p); } - if place == Place::Panel && pressed(ui, tl!("Edit Bevels…"), file, None) { - fields.set("__editBevels", true); - } - }) - .response + } + if edit { + fields.set("__editBevels", true); + } + row.output }) .companions([BEVEL_NAME, BEVEL_PROFILE, "__editBevels"]) } @@ -675,12 +680,13 @@ fn light_color_row() -> Param { Param::custom("lightColor", tl!("Color"), |ui, fields, cx| { let hex = fields.text("lightColor").unwrap_or("#ffffff").to_owned(); let color = Srgba::from_hex(&hex).unwrap_or(Srgba::rgb(1.0, 1.0, 1.0)); - ui.horizontal(|ui| { - if pressed(ui, &hex.to_uppercase(), true, Some(tl!("Color"))) { - cx.pick_color("__lightPick", color); - } - }) - .response + // The row's body may run more than once in a pass: the picker opens after it. + let mut ask = false; + let row = Row::new().show(ui, |ui, _| ask = pressed(ui, &hex.to_uppercase(), true, Some(tl!("Color")))); + if ask { + cx.pick_color("__lightPick", color); + } + row.output }) .opens_with("#ffffff") } @@ -711,11 +717,11 @@ pub(crate) fn light_editor(_data: &Data, place: Place, classic: bool) -> Param { // The classic effects' lights have no colour. let settings: Vec = settings.into_iter().filter(|p| !(classic && p.key == "lightColor")).collect(); Param::custom("lights", tl!("Lights"), move |ui, fields, cx| { + if let Some(Value::String(hex)) = fields.color("__lightPick").map(|c| json!(Srgba::from_rgb_array(c).to_hex())) { + fields.remove("__lightPick"); + set_light_value(fields, "lightColor", json!(hex)); + } ui.vertical(|ui| { - if let Some(Value::String(hex)) = fields.color("__lightPick").map(|c| json!(Srgba::from_rgb_array(c).to_hex())) { - fields.remove("__lightPick"); - set_light_value(fields, "lightColor", json!(hex)); - } let mut list = explicit_lights(fields).unwrap_or_else(|| vec![light_record(fields)]); let mut index = light_index(fields, list.len()); let titles: Vec = (1..=list.len()).map(|i| format!("{} {i}", c3("Light"))).collect(); @@ -724,27 +730,31 @@ pub(crate) fn light_editor(_data: &Data, place: Place, classic: bool) -> Param { } // Add Light is off while a setting of the single light is mixed. let mixed = explicit_lights(fields).is_none() && LIGHT_KEYS.iter().any(|(_, key)| fields.is_mixed(key)); - ui.horizontal(|ui| { - if pressed(ui, tl!("Add Light"), list.len() < vectorcraft_three_d::MAX_LIGHTS && !mixed, None) { - let mut added = selected_light(fields); - let defaults = vectorcraft_effects::default_params(fields.text("__effect").unwrap_or_default()).unwrap_or(json!({})); - for (_, key) in LIGHT_KEYS { - if let Some(value) = defaults.get(key) { - set_value(&mut added, key, value); - } - } - set_value(&mut added, "lightRotation", &json!(0.0)); - set_value(&mut added, "lightHeight", &json!(90.0)); - list.push(light_record(&added)); - index = list.len() - 1; - fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); - } - if pressed(ui, tl!("Delete Light"), list.len() > 1, None) && index < list.len() { - list.remove(index); - index = index.min(list.len().saturating_sub(1)); - fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); - } + // The row's body may run more than once in a pass: it reports the presses, which apply after it. + let (mut add, mut delete) = (false, false); + Row::new().show(ui, |ui, _| { + add = pressed(ui, tl!("Add Light"), list.len() < vectorcraft_three_d::MAX_LIGHTS && !mixed, None); + delete = pressed(ui, tl!("Delete Light"), list.len() > 1, None); }); + if add { + let mut added = selected_light(fields); + let defaults = vectorcraft_effects::default_params(fields.text("__effect").unwrap_or_default()).unwrap_or(json!({})); + for (_, key) in LIGHT_KEYS { + if let Some(value) = defaults.get(key) { + set_value(&mut added, key, value); + } + } + set_value(&mut added, "lightRotation", &json!(0.0)); + set_value(&mut added, "lightHeight", &json!(90.0)); + list.push(light_record(&added)); + index = list.len() - 1; + fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); + } + if delete && index < list.len() { + list.remove(index); + index = index.min(list.len().saturating_sub(1)); + fields.set("lights", FieldValue::Json(Value::Array(list.clone()))); + } fields.set("__light", i64::try_from(index).unwrap_or(0)); if place == Place::Panel || classic { super::revolve_lights::sphere(ui, fields, cx, classic); diff --git a/crates/ui-egui/src/dialogs/tests_hpgl.rs b/crates/ui-egui/src/dialogs/tests_hpgl.rs index dab1dbe8c6..0330cd7521 100644 --- a/crates/ui-egui/src/dialogs/tests_hpgl.rs +++ b/crates/ui-egui/src/dialogs/tests_hpgl.rs @@ -160,8 +160,9 @@ fn pen_table_starts_from_the_art_s_pens_and_comes_back() { assert_eq!(pens(&fields(&app)), json!(automatic)); } -/// A press of Add adds one pen and a press of One Pen per Color sets the table aside, though the rows' body may run -/// twice in the pass that reads the press. +/// A press of Add adds one pen, a press of a pen's Remove removes that pen, a press of a pen's swatch opens one picker +/// whose color that pen takes, and a press of One Pen per Color sets the table aside, though the rows' bodies run more +/// than once in the pass that reads the press. #[test] fn pen_rows_apply_each_press_once() { let (mut app, _) = app(1); @@ -171,11 +172,24 @@ fn pen_rows_apply_each_press_once() { press_control(&mut app, json!({"name": "Add", "role": "Button"})); frame(&mut app); assert_eq!(pens(&fields(&app)), json!(["#ff0000", "#000000", "#000000"])); + press_control(&mut app, json!({"name": "Remove", "role": "Button", "index": 0})); + frame(&mut app); + assert_eq!(pens(&fields(&app)), json!(["#000000", "#000000"])); + // The second pen's swatch opens the picker over the dialog; its OK colors that pen alone. + press_control(&mut app, json!({"name": "Pen color", "role": "ColorWell", "index": 1})); + frame(&mut app); + let open = |app: &VectorcraftApp| app.dialogs().map_or(0, |d| d.with(|h| h.open_dialogs().len())); + assert_eq!(open(&app), 2, "one picker opens on the dialog"); + set(&mut app, "color", json!("#00ff00")); + confirm(&mut app); + frame(&mut app); + assert_eq!((open(&app), kind(&app).as_deref()), (1, Some("hpglOptions"))); + assert_eq!(pens(&fields(&app)), json!(["#000000", "#00ff00"])); press_control(&mut app, json!({"name": "One Pen per Color", "role": "RadioButton"})); frame(&mut app); let d = fields(&app); assert!(pens(&d).is_null()); - assert_eq!(serde_json::to_value(d.get("__pens")).unwrap(), json!(["#ff0000", "#000000", "#000000"])); + assert_eq!(serde_json::to_value(d.get("__pens")).unwrap(), json!(["#000000", "#00ff00"])); } /// Pen Table with options the export refuses keeps One Pen per Color and says why, rather than diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 390c536503..70fc5871ed 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -14,6 +14,7 @@ use craft::ui::canvas::{CanvasSpace, canvas_space}; use craft::ui::canvas_controls::SelectionOutline; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; use craft::ui::display::Picture; +use craft::ui::layout_components::Row; use craft::ui::list::ThumbAspect; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind}; use craft::ui::pickers::Select; @@ -288,7 +289,9 @@ fn navigator(count: usize, seen: Vec) -> Param { Param::custom(MAP_SURFACE, tl!("Surface"), move |ui, fields, _| { let current = shown_surface(fields, count); let mut next = None; - let row = ui.horizontal(|ui| { + let row = Row::new().show(ui, |ui, _| { + // The row's body may run more than once in a pass: the last run's step applies. + next = None; for (icon, tip, target, enabled) in [ ("chevrons_left", tl!("First Surface"), 1, current > 1), ("chevron_left", tl!("Previous Surface"), current.saturating_sub(1), current > 1), @@ -318,7 +321,7 @@ fn navigator(count: usize, seen: Vec) -> Param { if fields.number(MAP_SURFACE) != Some(shown as f64) { fields.set(MAP_SURFACE, shown as f64); } - row.response + row.output }) } @@ -428,21 +431,25 @@ fn map_actions(flat: Flat, has_map: bool, any_map: bool) -> Param { Param::custom("__mapActions", "", move |ui, fields, _| { let surface = surface_number(fields); let map = maps_of(fields).into_iter().find(|m| m.surface == surface); - ui.horizontal(|ui| { - let fit = Button::new(tl!("Scale to Fit")).enabled(has_map && flat.art.is_some()).show(ui); - if let (true, Some(m), Some(art)) = (fit.clicked(), map.as_ref(), flat.art) { - let art = vectorcraft_geom::Rect::new(0.0, 0.0, art.0, art.1); - let (scale_x, scale_y) = m.fitting_scales(art, (flat.width, flat.height)).unwrap_or((m.scale_x, m.scale_y)); - store_map(fields, surface, Some(&SurfaceMap { x: 0.0, y: 0.0, scale_x, scale_y, ..m.clone() })); - } - if Button::new(tl!("Clear")).enabled(has_map).show(ui).clicked() { - store_map(fields, surface, None); - } - if Button::new(tl!("Clear All")).enabled(any_map).show(ui).clicked() { - fields.set(MAP_ART, FieldValue::Json(json!([]))); - } - }) - .response + // The row's body may run more than once in a pass: it reports the presses, which apply after it. + let (mut fit, mut clear, mut clear_all) = (false, false, false); + let row = Row::new().show(ui, |ui, _| { + fit = Button::new(tl!("Scale to Fit")).enabled(has_map && flat.art.is_some()).show(ui).clicked(); + clear = Button::new(tl!("Clear")).enabled(has_map).show(ui).clicked(); + clear_all = Button::new(tl!("Clear All")).enabled(any_map).show(ui).clicked(); + }); + if let (true, Some(m), Some(art)) = (fit, map.as_ref(), flat.art) { + let art = vectorcraft_geom::Rect::new(0.0, 0.0, art.0, art.1); + let (scale_x, scale_y) = m.fitting_scales(art, (flat.width, flat.height)).unwrap_or((m.scale_x, m.scale_y)); + store_map(fields, surface, Some(&SurfaceMap { x: 0.0, y: 0.0, scale_x, scale_y, ..m.clone() })); + } + if clear { + store_map(fields, surface, None); + } + if clear_all { + fields.set(MAP_ART, FieldValue::Json(json!([]))); + } + row.output }) .full_width() // The page's maps: automation sets them whole, as the rows above edit them one surface at a time.