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();