diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index ce954a32cd..3a6dbffa13 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -8,119 +8,256 @@ //! `dimPercent`. OK runs `layer.setProps`, `layer.new` or `layer.newSublayer`. For several rows //! the dialog shows the first row's settings, and OK sends only the ones set in the dialog. +use std::cell::RefCell; + +// PLAN: `craft::color_ui` and `craft::theme` need the `craft` facade (feature `color-ui`) in ui-egui's Cargo.toml, which has only `craft-ui`; the owner of the craft-libs pin adds it. +use craft::color_ui::{ChosenColor, ColorChoice, NamedColor}; +use craft::theme::Srgba; +use craft::theme::variant::Tone; +use craft::ui::choice::Checkbox; +use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; +use craft::ui::display::Text; +use craft::ui::form::Field; +use craft::ui::layout_components::{Row, Stack}; +use craft::ui::patterns::form_dialogs::{FormDialog, ResetFooter, ResetPick}; +use craft::ui::runtime::env::{Label, UnitKind}; +use craft::ui::runtime::overlay::CloseReason; +use craft::ui::runtime::requests::ColorRequest; +use craft::ui::text::{NumberField, TextField}; use serde_json::{Value, json}; use vectorcraft_doc::{LAYER_COLORS, LayerColor, Node, NodeId, NodeKind}; -use super::swatch_options::{grid, label}; -use super::{DialogSpec, form, run_and_close}; -use crate::state::Dialog; -use crate::{VectorcraftApp, widgets}; +use crate::VectorcraftApp; -/// The dialog kind of Layer Options. -pub const KIND: &str = "layerOptions"; +/// The key of the Layer Options dialog. +const KEY: &str = "ui.layerOptions"; -/// The field listing the fields set in the dialog, by its controls or `ui.dialog.set`. -const SET: &str = "__set"; +/// The preset a layer without a colour of its own shows. +const FALLBACK_COLOR: &str = "Light Blue"; -/// The field holding, for several rows, the first row's Template, Lock, Dim Images and its -/// percentage as the dialog opened. -const OPENED: &str = "__opened"; +/// The fields a dialog sets, as `ui.dialog.set` names them. +const FIELDS: [&str; 9] = ["name", "color", "template", "visible", "preview", "locked", "printable", "dimImages", "dimPercent"]; -/// Records that `field` was set. -fn mark(d: &mut Dialog, field: &str) { - match d.fields.get_mut(SET) { - Some(Value::Array(a)) => { - if !a.iter().any(|k| k == field) { - a.push(json!(field)); - } - } - _ => { - d.fields.insert(SET.into(), json!([field])); +/// The first row's Template, Lock, Dim Images and percentage as the dialog opened, for several rows. +#[derive(Clone, Debug, PartialEq)] +struct Opened { + template: bool, + locked: bool, + dim_images: bool, + dim_percent: f64, +} + +/// The settings the dialog edits, with the marks of the ones set in it. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct LayerOptionsValue { + name: String, + color: ChosenColor, + /// The custom colour, once one was picked or the layer has one. + custom: Option, + template: bool, + visible: bool, + preview: bool, + locked: bool, + printable: bool, + dim_images: bool, + dim_percent: f64, + /// The rows are layers (not objects). + layer: bool, + /// More than one row is edited. + many: bool, + /// `edit`, `new` or `newSublayer`. + mode: &'static str, + ids: Vec, + /// The fields set in the dialog, by its controls or `ui.dialog.set`. + set: Vec<&'static str>, + opened: Option, +} + +impl Default for LayerOptionsValue { + fn default() -> Self { + LayerOptionsValue { + name: String::new(), + color: ChosenColor::Named(FALLBACK_COLOR.to_owned()), + custom: None, + template: false, + visible: true, + preview: true, + locked: false, + printable: true, + dim_images: false, + dim_percent: 50.0, + layer: false, + many: false, + mode: "edit", + ids: Vec::new(), + set: Vec::new(), + opened: None, } } } -/// Records that `ui.dialog.set` sets `field` to `value`. Template also sets Lock and Dim Images, -/// as its checkbox does. -pub(super) fn note_set(d: &mut Dialog, field: &str, value: &Value) { - if field.starts_with("__") { - return; - } - match value.as_bool() { - Some(on) if field == "template" && on != d.bool("template") => set_template(d, on), - _ => mark(d, field), - } +/// `rgb` as a colour. +pub(super) fn srgb([r, g, b]: [u8; 3]) -> Srgba { + Srgba::rgb(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0) } -/// Turns Template on or off. A template is locked and dims its images, and turning Template off -/// unlocks it and turns Dim Images off; a Dim Images that was set in the dialog keeps its value. -/// For several rows, OK sends Lock and Dim Images only when they are set in the dialog. `layer.setProps` then locks each row that becomes a template and -/// dims it to 50%, unless a percentage is set in the dialog, so the dialog shows 50%; it unlocks -/// each row that stops being a template and stops dimming it. -/// When Template is set back to the first row's value, Lock and Dim Images that were not set in -/// the dialog show the first row's values again. -fn set_template(d: &mut Dialog, on: bool) { - choose(d, "template", json!(on)); - d.fields.insert("locked".into(), json!(on)); - if !is_set(d, "dimImages") { - d.fields.insert("dimImages".into(), json!(on)); - } - let Some(opened) = d.fields.get(OPENED).cloned() else { - return; - }; - if opened.get("template") == Some(&json!(on)) { - for key in ["locked", "dimImages", "dimPercent"] { - if let Some(v) = opened.get(key).filter(|_| !is_set(d, key)) { - d.fields.insert(key.into(), v.clone()); - } - } - } else if on && !is_set(d, "dimPercent") { - d.fields.insert("dimPercent".into(), json!(50)); - } +/// `color` as 8-bit channels; alpha is dropped. +pub(super) fn rgb8(color: Srgba) -> [u8; 3] { + color.to_rgb_array().map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8) } -/// Whether `field` was set in the dialog. -fn is_set(d: &Dialog, field: &str) -> bool { - d.fields.get(SET).and_then(Value::as_array).is_some_and(|a| a.iter().any(|k| k == field)) +/// `#rrggbb` for `color`, whatever its alpha. +fn hex_of(color: Srgba) -> String { + let [r, g, b] = rgb8(color); + format!("#{r:02x}{g:02x}{b:02x}") } -/// Sets `key` to `value` from one of the dialog's controls. -fn choose(d: &mut Dialog, key: &str, value: Value) { - d.fields.insert(key.into(), value); - mark(d, key); -} - -pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 320.0, ..DialogSpec::FORM }; - -fn heading(d: &Dialog) -> String { - if d.bool("layer") || d.str("mode") != "edit" { tl!("Layer Options").into() } else { tl!("Options").into() } -} - -/// A layer colour as the dialog shows it: a preset's name, else `#rrggbb`. -fn color_field(c: LayerColor) -> String { +/// A layer colour as the dialog holds it: a preset's name, else the custom colour. +fn chosen_of(c: LayerColor) -> (ChosenColor, Option) { match c { - LayerColor::Preset(i) => LAYER_COLORS.get(i as usize).map_or("Light Blue", |(n, _)| *n).to_string(), - LayerColor::Custom([r, g, b]) => format!("#{r:02x}{g:02x}{b:02x}"), + LayerColor::Preset(i) => (ChosenColor::Named(LAYER_COLORS.get(i as usize).map_or(FALLBACK_COLOR, |(n, _)| *n).to_owned()), None), + LayerColor::Custom(rgb) => (ChosenColor::Custom, Some(srgb(rgb))), } } -/// The fields for `n` (a layer or any other row). -/// `xml_id`: Preferences › Units › Identify Objects By › XML ID. -fn fields_of(n: &Node, xml_id: bool) -> serde_json::Map { - let mut f = serde_json::Map::new(); - f.insert("name".into(), json!(n.identify_label(xml_id))); - f.insert("visible".into(), json!(n.visible)); - f.insert("locked".into(), json!(n.locked)); - f.insert("layer".into(), json!(n.is_layer())); - if let NodeKind::Layer { color, template, printable, preview, dim_images, .. } = &n.kind { - f.insert("color".into(), json!(color_field(*color))); - f.insert("template".into(), json!(template)); - f.insert("printable".into(), json!(printable)); - f.insert("preview".into(), json!(preview)); - f.insert("dimImages".into(), json!(dim_images.is_some())); - f.insert("dimPercent".into(), json!(dim_images.unwrap_or(50))); +impl LayerOptionsValue { + /// Records that `field` was set. + fn mark(&mut self, field: &'static str) { + if !self.is_set(field) { + self.set.push(field); + } } - f + + /// Whether `field` was set in the dialog. + fn is_set(&self, field: &str) -> bool { + self.set.iter().any(|set| *set == field) + } + + /// The check box `key` names. + fn flag(&self, key: &str) -> bool { + match key { + "template" => self.template, + "visible" => self.visible, + "preview" => self.preview, + "locked" => self.locked, + "printable" => self.printable, + "dimImages" => self.dim_images, + _ => false, + } + } + + /// Sets the check box `key` as its control does, and records it. Template also sets Lock and Dim Images. + fn set_flag(&mut self, key: &'static str, on: bool) { + match key { + "template" if on != self.template => return self.set_template(on), + "template" => {} + "visible" => self.visible = on, + "preview" => self.preview = on, + "locked" => self.locked = on, + "printable" => self.printable = on, + "dimImages" => self.dim_images = on, + _ => return, + } + self.mark(key); + } + + /// Turns Template on or off. A template is locked and dims its images, and turning Template off + /// unlocks it and turns Dim Images off; a Dim Images that was set in the dialog keeps its value. + /// For several rows, OK sends Lock and Dim Images only when they are set in the dialog. `layer.setProps` then locks each row that + /// becomes a template and dims it to 50%, unless a percentage is set in the dialog, so the dialog shows 50%; it unlocks + /// each row that stops being a template and stops dimming it. + /// When Template is set back to the first row's value, Lock and Dim Images that were not set in + /// the dialog show the first row's values again. + fn set_template(&mut self, on: bool) { + self.template = on; + self.mark("template"); + self.locked = on; + if !self.is_set("dimImages") { + self.dim_images = on; + } + let Some(opened) = self.opened.clone() else { return }; + if opened.template == on { + if !self.is_set("locked") { + self.locked = opened.locked; + } + if !self.is_set("dimImages") { + self.dim_images = opened.dim_images; + } + if !self.is_set("dimPercent") { + self.dim_percent = opened.dim_percent; + } + } else if on && !self.is_set("dimPercent") { + self.dim_percent = 50.0; + } + } + + /// The colour as `layer.setProps` takes it: a preset's name, else `#rrggbb`. + fn color_text(&self) -> String { + match (&self.color, self.custom) { + (ChosenColor::Named(name), _) => name.clone(), + (_, Some(custom)) => hex_of(custom), + _ => FALLBACK_COLOR.to_owned(), + } + } + + /// Sets the colour from a preset's name (any case) or `#rrggbb`; `None` for anything else. + fn set_color_text(&mut self, text: &str) -> Option<()> { + if let Some((name, _)) = LAYER_COLORS.iter().find(|(n, _)| n.eq_ignore_ascii_case(text)) { + self.color = ChosenColor::Named((*name).to_owned()); + } else { + self.custom = Some(Srgba::from_hex(text)?); + self.color = ChosenColor::Custom; + } + self.mark("color"); + Some(()) + } + + /// Whether the row of `key` shows: Name is for one row, the rest of the settings for layers. + fn shows(&self, key: &str) -> bool { + match key { + "name" => !self.many, + "visible" | "locked" => true, + _ => self.layer, + } + } + + /// Whether the row of `key` takes input: a template is locked and printable as it is. + fn takes_input(&self, key: &str) -> bool { + !(self.layer && self.template && matches!(key, "locked" | "printable")) + } + + fn heading(&self) -> &'static str { + if self.layer || self.mode != "edit" { tl!("Layer Options") } else { tl!("Options") } + } +} + +/// The value for `n` (a layer or any other row). +/// `xml_id`: Preferences › Units › Identify Objects By › XML ID. +fn fields_of(n: &Node, xml_id: bool) -> LayerOptionsValue { + let mut v = LayerOptionsValue { + name: n.identify_label(xml_id), + visible: n.visible, + locked: n.locked, + layer: n.is_layer(), + ..Default::default() + }; + if let NodeKind::Layer { color, template, printable, preview, dim_images, .. } = &n.kind { + (v.color, v.custom) = chosen_of(*color); + v.template = *template; + v.printable = *printable; + v.preview = *preview; + v.dim_images = dim_images.is_some(); + v.dim_percent = dim_images.unwrap_or(50) as f64; + } + v +} + +/// Opens the dialog on `value`. +fn open_value(app: &mut VectorcraftApp, value: LayerOptionsValue) -> Result { + let dialogs = app.dialogs().ok_or("no window")?; + dialogs.with(|host| host.open(LayerOptionsDialog::new(value))); + Ok(Value::Null) } /// `ui.layerOptions {ids?|id?}`: open Layer Options for rows (default: the highlighted rows, else @@ -144,16 +281,13 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { }; let first = ids.first().and_then(|id| st.doc.node(*id)).ok_or("no such layer or object")?; let xml_id = app.session.prefs.identify_objects_by == "xmlId"; - let mut f = fields_of(first, xml_id); - if ids.len() > 1 { - let opened: serde_json::Map<_, _> = - ["template", "locked", "dimImages", "dimPercent"].iter().filter_map(|k| Some((k.to_string(), f.get(*k)?.clone()))).collect(); - f.insert(OPENED.into(), Value::Object(opened)); + let mut v = fields_of(first, xml_id); + v.many = ids.len() > 1; + if v.many { + v.opened = Some(Opened { template: v.template, locked: v.locked, dim_images: v.dim_images, dim_percent: v.dim_percent }); } - f.insert("ids".into(), json!(ids.iter().map(|i| i.0).collect::>())); - f.insert("mode".into(), json!("edit")); - app.ui.dialog = Some(Dialog { kind: KIND.into(), fields: f }); - Ok(Value::Null) + v.ids = ids.iter().map(|i| i.0).collect(); + open_value(app, v) } /// `ui.newLayer {sublayer?}`: Layer Options for a new layer (or sublayer), with the name and @@ -175,172 +309,299 @@ pub fn open_new(app: &mut VectorcraftApp, p: &Value) -> Result { while layers.contains(&format!("Layer {i}")) { i += 1; } - let color = LayerColor::Preset((layers.len() % LAYER_COLORS.len()) as u8); let name = format!("Layer {i}"); let name = if app.session.prefs.identify_objects_by == "xmlId" { vectorcraft_doc::xml_id::from_object_name(&name) } else { name }; - let fields = json!({ - "mode": if sublayer { "newSublayer" } else { "new" }, "layer": true, "name": name, "color": color_field(color), - "template": false, "locked": false, "visible": true, "printable": true, "preview": true, "dimImages": false, "dimPercent": 50, - }); - app.ui.dialog = Some(Dialog::new(KIND, fields)); - Ok(Value::Null) + let (color, custom) = chosen_of(LayerColor::Preset((layers.len() % LAYER_COLORS.len()) as u8)); + let v = LayerOptionsValue { name, color, custom, layer: true, mode: if sublayer { "newSublayer" } else { "new" }, ..Default::default() }; + open_value(app, v) } -fn toggle(ui: &mut egui::Ui, d: &mut Dialog, key: &str, text: &str, enabled: bool) -> bool { - let v = d.bool(key); - let changed = widgets::check(ui, text, v, enabled); - if changed { - choose(d, key, json!(!v)); +/// A check box named `text`; the new state in the pass the user changed it. +pub(super) fn check(ui: &mut egui::Ui, text: &'static str, on: bool, enabled: bool) -> Option { + Checkbox::new(Bind::given(on)).label(text).id_salt(text).enabled(enabled).show(ui).value().copied() +} + +/// The check box of `key`. +fn flag_row(ui: &mut egui::Ui, v: &mut LayerOptionsValue, key: &'static str, text: &'static str) { + if let Some(on) = check(ui, text, v.flag(key), v.takes_input(key)) { + v.set_flag(key, on); } - changed } -/// The size of the colour chip before each name in the Color list. -const CHIP: egui::Vec2 = egui::vec2(16.0, 10.0); - -/// The Color list: each preset's name after a chip of its colour, then Custom (no chip, its -/// name aligned with the others). Returns the chosen row; Custom is `LAYER_COLORS.len()`. -fn color_dropdown(ui: &mut egui::Ui, shown: &str) -> Option { - let border = crate::theme::Tokens::get(ui.ctx()).input_border; - let rows = LAYER_COLORS.iter().map(|(n, c)| (*n, Some(*c))).chain([("Custom", None)]); - widgets::combo(ui, "layer-color", tl!(shown), 140.0, |ui| { - let mut chosen = None; - for (i, (name, rgb)) in rows.enumerate() { - let chip = egui::IdSalt::new(("layer-color-chip", i)); - let r = egui::Button::selectable(name == shown, (egui::Atom::custom(chip, CHIP), tl!(name))).atom_ui(ui); - if let (Some(rect), Some([cr, cg, cb])) = (r.rect(chip), rgb) { - ui.painter().rect_filled(rect, 1.0, egui::Color32::from_rgb(cr, cg, cb)); - ui.painter().rect_stroke(rect, 1.0, egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); +/// The dialog's rows; the colour request of Custom… goes to `requested`. +fn body(ui: &mut egui::Ui, v: &mut LayerOptionsValue, requested: &RefCell>) { + if v.shows("name") { + Field::new(tl!("Name:")).id_salt("name").show(ui, |ui, _| { + TextField::new(tl!("Name:"), Bind::bound(&mut v.name)).show(ui); + }); + } + if v.layer { + Field::new(tl!("Color:")).id_salt("color").show(ui, |ui, _| { + let named = LAYER_COLORS.iter().map(|&(n, c)| NamedColor::new(n, tl!(n), Some(srgb(c)))); + let out = ColorChoice::new(tl!("Color:"), &v.color).named(named).custom(v.custom).show(ui); + if let Some(chosen) = out.chosen { + v.color = chosen; + v.mark("color"); } - if r.response.clicked() { - chosen = Some(i); + // A second pass of the frame has no press: only a request keeps what the first pass asked for. + if let Some(request) = out.pick_color { + *requested.borrow_mut() = Some(request); } - } - chosen - }) -} - -fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let layer = d.bool("layer"); - let many = d.fields.get("ids").and_then(Value::as_array).is_some_and(|a| a.len() > 1); - grid(ui, |ui| { - if !many { - label(ui, tl!("Name:")); - form::text(ui, d, "name", 190.0); - ui.end_row(); - } - if layer { - label(ui, tl!("Color:")); - ui.horizontal(|ui| { - let cur = d.str("color"); - let shown = LAYER_COLORS.iter().map(|(n, _)| *n).find(|n| n.eq_ignore_ascii_case(&cur)).unwrap_or("Custom"); - if let Some((n, _)) = color_dropdown(ui, shown).and_then(|i| LAYER_COLORS.get(i)) { - choose(d, "color", json!(n)); - } - let [r, g, b] = LAYER_COLORS - .iter() - .find(|(n, _)| n.eq_ignore_ascii_case(&cur)) - .map(|(_, c)| *c) - .or_else(|| { - vectorcraft_color::Color::from_hex(&cur).map(|c| { - let [r, g, b, _] = c.to_rgba8(1.0); - [r, g, b] - }) - }) - .unwrap_or(LAYER_COLORS[0].1); - let mut rgb = [r, g, b]; - if ui.color_edit_button_srgb(&mut rgb).changed() { - choose(d, "color", json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]))); - } - }); - ui.end_row(); - } - }); - ui.add_space(8.0); - if layer { - ui.horizontal(|ui| { - ui.vertical(|ui| { - let template = d.bool("template"); - if widgets::check(ui, tl!("Template"), template, true) { - set_template(d, !template); - } - toggle(ui, d, "visible", tl!("Show"), true); - toggle(ui, d, "preview", tl!("Preview"), true); - ui.horizontal(|ui| { - toggle(ui, d, "dimImages", tl!("Dim Images to:"), true); - let v = d.f64("dimPercent", 50.0); - let dim = d.bool("dimImages"); - if let Some(v) = ui - .add_enabled_ui(dim, |ui| { - crate::widgets::range_field_named(ui, "dimPercent", Some(tl!("Dim Images to:")), v, 0.0..=100.0, "%", 0, 52.0) - }) - .inner - { - choose(d, "dimPercent", json!(v)); + }); + } + Row::new().show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { + if v.layer { + flag_row(ui, v, "template", tl!("Template")); + } + flag_row(ui, v, "visible", tl!("Show")); + if v.layer { + flag_row(ui, v, "preview", tl!("Preview")); + Row::new().show(ui, |ui, _| { + flag_row(ui, v, "dimImages", tl!("Dim Images to:")); + let field = NumberField::new(tl!("Dim Images to:"), Bind::given(Some(v.dim_percent))) + .range(0.0..=100.0) + .unit_kind(UnitKind::Percent) + .enabled(v.dim_images) + .show(ui); + if let Some(Some(percent)) = field.edit.value().copied() { + v.dim_percent = percent; + v.mark("dimPercent"); } }); - }); - ui.add_space(24.0); - ui.vertical(|ui| { - let template = d.bool("template"); - toggle(ui, d, "locked", tl!("Lock"), !template); - toggle(ui, d, "printable", tl!("Print"), !template); - }); + } }); - } else { - toggle(ui, d, "visible", tl!("Show"), true); - toggle(ui, d, "locked", tl!("Lock"), true); - } - false + Stack::new().show(ui, |ui, _| { + flag_row(ui, v, "locked", tl!("Lock")); + if v.layer { + flag_row(ui, v, "printable", tl!("Print")); + } + }); + }); } /// The command and params OK runs. For several rows only the settings set in the dialog are sent, /// so each row keeps its own values for the rest. -pub(crate) fn params(d: &Dialog) -> (&'static str, Value) { +pub(crate) fn params(v: &LayerOptionsValue) -> (&'static str, Value) { let mut p = serde_json::Map::new(); - let many = d.fields.get("ids").and_then(Value::as_array).is_some_and(|a| a.len() > 1); - if !many { - p.insert("name".into(), json!(d.str("name"))); + if !v.many { + p.insert("name".into(), json!(v.name)); } - p.insert("visible".into(), json!(d.bool("visible"))); - p.insert("locked".into(), json!(d.bool("locked"))); - if d.bool("layer") { - p.insert("color".into(), json!(d.str("color"))); - p.insert("template".into(), json!(d.bool("template"))); - p.insert("printable".into(), json!(d.bool("printable"))); - p.insert("preview".into(), json!(d.bool("preview"))); - p.insert("dimImages".into(), if d.bool("dimImages") { json!(d.f64("dimPercent", 50.0).clamp(0.0, 100.0)) } else { json!(false) }); + p.insert("visible".into(), json!(v.visible)); + p.insert("locked".into(), json!(v.locked)); + if v.layer { + p.insert("color".into(), json!(v.color_text())); + p.insert("template".into(), json!(v.template)); + p.insert("printable".into(), json!(v.printable)); + p.insert("preview".into(), json!(v.preview)); + p.insert("dimImages".into(), if v.dim_images { json!(v.dim_percent.clamp(0.0, 100.0)) } else { json!(false) }); } - if many { + if v.many { // A percentage set in the dialog is sent whenever Dim Images is on, also when Dim Images // was turned on by Template. - let percent = d.bool("dimImages") && is_set(d, "dimPercent"); - p.retain(|k, _| is_set(d, k) || (k == "dimImages" && percent)); + let percent = v.dim_images && v.is_set("dimPercent"); + p.retain(|k, _| v.is_set(k) || (k == "dimImages" && percent)); } - match d.str("mode").as_str() { + match v.mode { "new" => ("layer.new", Value::Object(p)), "newSublayer" => ("layer.newSublayer", Value::Object(p)), _ => { - p.insert("ids".into(), d.fields.get("ids").cloned().unwrap_or(json!([]))); + p.insert("ids".into(), json!(v.ids)); ("layer.setProps", Value::Object(p)) } } } -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let (cmd, p) = params(d); - // Isolation mode can start while the dialog is open. +/// The Layer Options dialog. OK files the value for [`pump`], which runs the command and answers it: a refusal keeps +/// the dialog open with the reason under its rows. +pub(crate) struct LayerOptionsDialog { + id: DialogId, + open: bool, + value: LayerOptionsValue, + held: HeldAnswer, + /// The value the held OK was refused for: the reason shows until it changes. + refused_at: Option, + /// The Custom… press, until the app takes it. + color_request: Option, +} + +impl LayerOptionsDialog { + /// The dialog over `value`. + fn new(value: LayerOptionsValue) -> Self { + LayerOptionsDialog { id: dialog_id(KEY), open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None } + } + + /// The OK filed by the user, once. + fn take_filed(&mut self) -> Option { + self.held.take() + } + + /// The app's answer to the filed OK: `Ok` closes the dialog, `Err` keeps it open with the reason. + fn answer(&mut self, answer: Result<(), Label>) { + if answer.is_err() { + self.refused_at = Some(self.value.clone()); + } + self.held.answer(answer); + } +} + +impl StackDialog for LayerOptionsDialog { + type Result = LayerOptionsValue; + + fn id(&self) -> DialogId { + self.id + } + + fn key(&self) -> Option<&str> { + Some(KEY) + } + + fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option> { + let finish = self.held.is_accepted(); + let refusal = self.held.refusal().map(|(reason, _)| reason.clone()); + let requested = RefCell::new(None); + let latest = RefCell::new(None); + let footer = ResetFooter::new(ui, None, true); + let shown = FormDialog::new(self.value.heading(), Bind::bound(&mut self.value)) + .opened(Bind::bound(&mut self.open)) + .accept_stays_open(true) + .ok_enabled(!self.held.is_waiting()) + .show(ui, |ui, form, v| { + // A measuring run closes nothing: the real run of the same pass makes the close. + if finish && !craft::ui::runtime::measure::active(ui.ctx()) { + form.request_close_as(CloseReason::Activated); + } + body(ui, v, &requested); + if let Some(reason) = &refusal { + Text::new(reason.clone()).tone(Tone::Bad).show(ui); + } + *latest.borrow_mut() = Some(v.clone()); + true + }); + if let Some(request) = requested.into_inner() { + self.color_request = Some(request); + } + if self.refused_at.as_ref().is_some_and(|at| *at != self.value) { + self.refused_at = None; + self.held.clear_refusal(); + } + if finish && matches!(shown.closed, Some(CloseReason::Activated)) { + return Some(self.held.finish().map_or(DialogResult::Cancel, DialogResult::Ok)); + } + // OK (the button, or Enter) files the value; the dialog stays open until the app answers. + let pressed = footer.pick(shown.picked) == Some(ResetPick::Accept); + if let Some(value) = shown.accepted.or_else(|| latest.into_inner().filter(|_| pressed)) { + if !self.held.is_waiting() { + self.held.file(value); + } + self.open = true; + return None; + } + shown.closed.map(|_| DialogResult::Cancel) + } + + fn confirm(&mut self, _: &egui::Context) -> Option { + if self.held.is_accepted() { + return self.held.finish(); + } + if !self.held.is_waiting() { + self.held.file(self.value.clone()); + } + None + } + + fn held_state(&self) -> Option { + self.held.state() + } + + fn json_fields(&self) -> Option { + let v = &self.value; + let mut f = serde_json::Map::new(); + for key in FIELDS.into_iter().filter(|key| v.shows(key)) { + let value = match key { + "name" => json!(v.name), + "color" => json!(v.color_text()), + "dimPercent" => json!(v.dim_percent), + _ => json!(v.flag(key)), + }; + f.insert(key.into(), value); + } + // The name is a field of one row; several rows show none but keep it in their fields. + f.entry("name").or_insert_with(|| json!(v.name)); + f.insert("ids".into(), json!(v.ids)); + f.insert("mode".into(), json!(v.mode)); + f.insert("layer".into(), json!(v.layer)); + Some(Value::Object(f)) + } + + fn set_json_field(&mut self, _: &egui::Context, field: &str, value: Value) -> Result<(), String> { + if matches!(field, "ids" | "mode" | "layer") { + return Err(FieldRefusal::ReadOnly.message(field)); + } + let Some(key) = FIELDS.into_iter().find(|key| *key == field) else { + return Err(FieldRefusal::Unknown.message(field)); + }; + let v = &mut self.value; + if !v.shows(key) || !v.takes_input(key) { + return Err(FieldRefusal::Inactive.message(field)); + } + let rejects = || FieldRefusal::Rejects(&value).message(field); + match key { + "name" => v.name = value.as_str().ok_or_else(rejects)?.to_owned(), + "color" => v.set_color_text(value.as_str().ok_or_else(rejects)?).ok_or_else(rejects)?, + "dimPercent" => { + v.dim_percent = value.as_f64().filter(|p| p.is_finite()).ok_or_else(rejects)?; + v.mark("dimPercent"); + } + _ => v.set_flag(key, value.as_bool().ok_or_else(rejects)?), + } + Ok(()) + } + + fn take_color_request(&mut self) -> Option { + self.color_request.take() + } + + fn answer_color(&mut self, key: &str, color: Srgba) { + if key == ColorChoice::CUSTOM_KEY { + self.value.custom = Some(color); + self.value.color = ChosenColor::Custom; + self.value.mark("color"); + } + } +} + +/// Runs the OK Layer Options filed: the command, once the isolation check passes. A refusal keeps the dialog open; any +/// other command error goes to the status line and closes it. +pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(dialogs) = app.dialogs() else { return }; + // The closed dialog's answer was run when OK was filed. + let _ = dialogs.with(|host| host.take::()); + let Some(value) = dialogs.with(|host| host.get_mut::().and_then(LayerOptionsDialog::take_filed)) else { return }; + let (cmd, p) = params(&value); let sublayer = match cmd { "layer.new" => Some(false), "layer.newSublayer" => Some(true), _ => None, }; - if let Some(sublayer) = sublayer - && app.session.active().is_some_and(|st| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) - { - return Err("exit isolation mode first".into()); - } - run_and_close(app, cmd, p) + // Isolation mode can start while the dialog is open. + let answer = match sublayer { + Some(sublayer) if app.session.active().is_some_and(|st| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => { + Err(Label::from("exit isolation mode first")) + } + _ => { + if let Err(e) = app.run(cmd, p) { + app.status(e); + } + Ok(()) + } + }; + dialogs.with(|host| { + if let Some(dialog) = host.get_mut::() { + dialog.answer(answer); + } + }); + ctx.request_repaint(); } #[cfg(test)] @@ -350,20 +611,45 @@ mod tests { fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(egui::Context::default()); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); app } - fn draw(app: &mut VectorcraftApp) { - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(app, ui.ctx())); - out.textures_delta.clear(); + /// The open dialog's id. + fn open_id(app: &VectorcraftApp) -> DialogId { + app.dialogs().unwrap().with(|host| host.open_dialogs().last().map(|d| d.id)).unwrap() + } + + /// The open dialog's fields. + fn fields(app: &VectorcraftApp) -> Value { + app.dialogs().unwrap().with(|host| host.open_dialogs().last().and_then(|d| d.fields.clone())).unwrap() } /// Sets a field as `ui.dialog.set` does. - fn set(app: &mut VectorcraftApp, k: &str, v: Value) { - super::super::set_field(app.ui.dialog.as_mut().unwrap(), k.into(), v); + fn set(app: &mut VectorcraftApp, field: &str, value: Value) { + try_set(app, field, value).unwrap(); + } + + fn try_set(app: &mut VectorcraftApp, field: &str, value: Value) -> Result<(), String> { + let ctx = app.ui_ctx.clone().unwrap(); + let id = open_id(app); + app.dialogs().unwrap().with(|host| host.set_json_field(&ctx, id, field, value)) + } + + /// The command and params OK would run for the open dialog. + fn current_params(app: &VectorcraftApp) -> Value { + app.dialogs().unwrap().with(|host| params(&host.get::().unwrap().value).1) + } + + /// Presses OK and runs the host pump, which runs the command; the second OK closes an accepted dialog. + fn ok(app: &mut VectorcraftApp) { + let ctx = app.ui_ctx.clone().unwrap(); + let id = open_id(app); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(app, &ctx); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); } /// Explicit object ids must not silently disappear or fall back to the highlighted row. @@ -375,10 +661,10 @@ mod tests { [json!({"ids": [id, "invalid"]}), json!({"ids": [id, 999999]}), json!({"ids": "invalid"}), json!({"id": "invalid"}), json!({"id": null})] { assert!(app.run("ui.layerOptions", params.clone()).is_err(), "accepted {params}"); - assert!(app.ui.dialog.is_none(), "opened partial options for {params}"); + assert!(!app.any_dialog_open(), "opened partial options for {params}"); } app.run("ui.layerOptions", json!({"ids": [id]})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["ids"], json!([id])); + assert_eq!(fields(&app)["ids"], json!([id])); } #[test] @@ -386,17 +672,16 @@ mod tests { let mut app = app(); let layer = app.session.doc().unwrap().doc.layers[0].id; app.run("ui.layerOptions", json!({})).unwrap(); - let d = app.ui.dialog.clone().unwrap(); - assert_eq!((d.kind.as_str(), d.str("name"), d.str("color")), (KIND, "Layer 1".to_string(), "Light Blue".to_string())); - draw(&mut app); + let f = fields(&app); + assert_eq!((f["name"].as_str(), f["color"].as_str()), (Some("Layer 1"), Some("Light Blue"))); set(&mut app, "name", json!("Sky")); set(&mut app, "color", json!("#00ff00")); set(&mut app, "dimImages", json!(true)); set(&mut app, "dimPercent", json!(30)); set(&mut app, "preview", json!(false)); let undo = app.session.doc().unwrap().history.undo.len(); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + ok(&mut app); + assert!(!app.any_dialog_open()); let n = app.session.doc().unwrap().doc.node(layer).unwrap().clone(); assert_eq!(n.display_name(), "Sky"); assert!(matches!(n.kind, NodeKind::Layer { color: LayerColor::Custom([0, 255, 0]), dim_images: Some(30), preview: false, .. })); @@ -410,7 +695,6 @@ mod tests { let p = json!({"color": "#00ff00", "locked": true, "preview": false, "dimImages": 30}); let second = NodeId(app.session.execute("layer.new", &p).unwrap()["id"].as_u64().unwrap()); app.run("ui.layerOptions", json!({"ids": [first.0, second.0]})).unwrap(); - draw(app); (first, second) } @@ -425,9 +709,8 @@ mod tests { let (first, second) = two_layers(&mut app); set(&mut app, "printable", json!(false)); set(&mut app, "color", json!("Light Blue")); - let (_, p) = params(app.ui.dialog.as_ref().unwrap()); - assert_eq!(p, json!({"printable": false, "color": "Light Blue", "ids": [first.0, second.0]})); - super::super::confirm(&mut app).unwrap(); + assert_eq!(current_params(&app), json!({"printable": false, "color": "Light Blue", "ids": [first.0, second.0]})); + ok(&mut app); let (a, b) = (layer(&app, first), layer(&app, second)); assert!(matches!(a.kind, NodeKind::Layer { color: LayerColor::Preset(0), printable: false, preview: true, dim_images: None, .. })); assert!(!a.locked); @@ -444,26 +727,24 @@ mod tests { app.run("layer.setProps", json!({"ids": [second.0], "template": true, "dimImages": 30})).unwrap(); app.run("ui.layerOptions", json!({"ids": [first.0, second.0]})).unwrap(); set(&mut app, "template", json!(true)); - let (_, p) = params(app.ui.dialog.as_ref().unwrap()); - assert_eq!(p, json!({"template": true, "ids": [first.0, second.0]})); - super::super::confirm(&mut app).unwrap(); + assert_eq!(current_params(&app), json!({"template": true, "ids": [first.0, second.0]})); + ok(&mut app); let (a, b) = (layer(&app, first), layer(&app, second)); assert!(a.is_template() && a.locked && matches!(a.kind, NodeKind::Layer { dim_images: Some(50), .. })); assert!(b.is_template() && b.locked && matches!(b.kind, NodeKind::Layer { dim_images: Some(30), .. })); // The first layer is dimmed to 50% now; 50% set again goes to both. app.run("ui.layerOptions", json!({"ids": [first.0, second.0]})).unwrap(); set(&mut app, "dimPercent", json!(50)); - let (_, p) = params(app.ui.dialog.as_ref().unwrap()); - assert_eq!(p, json!({"dimImages": 50.0, "ids": [first.0, second.0]})); - super::super::confirm(&mut app).unwrap(); + assert_eq!(current_params(&app), json!({"dimImages": 50.0, "ids": [first.0, second.0]})); + ok(&mut app); assert!(matches!(layer(&app, second).kind, NodeKind::Layer { dim_images: Some(50), .. })); // A percentage set while Dim Images is off is sent once Dim Images is on. app.run("layer.setProps", json!({"ids": [first.0], "template": false, "dimImages": false})).unwrap(); app.run("ui.layerOptions", json!({"ids": [first.0, second.0]})).unwrap(); set(&mut app, "dimPercent", json!(20)); - assert_eq!(params(app.ui.dialog.as_ref().unwrap()).1, json!({"ids": [first.0, second.0]})); + assert_eq!(current_params(&app), json!({"ids": [first.0, second.0]})); set(&mut app, "dimImages", json!(true)); - assert_eq!(params(app.ui.dialog.as_ref().unwrap()).1, json!({"dimImages": 20.0, "ids": [first.0, second.0]})); + assert_eq!(current_params(&app), json!({"dimImages": 20.0, "ids": [first.0, second.0]})); } /// A percentage set while Dim Images is off is sent when Template turns Dim Images on. @@ -473,56 +754,13 @@ mod tests { let (first, second) = two_layers(&mut app); set(&mut app, "dimPercent", json!(20)); set(&mut app, "template", json!(true)); - let (_, p) = params(app.ui.dialog.as_ref().unwrap()); - assert_eq!(p, json!({"template": true, "dimImages": 20.0, "ids": [first.0, second.0]})); - super::super::confirm(&mut app).unwrap(); + assert_eq!(current_params(&app), json!({"template": true, "dimImages": 20.0, "ids": [first.0, second.0]})); + ok(&mut app); for id in [first, second] { assert!(matches!(layer(&app, id).kind, NodeKind::Layer { template: true, dim_images: Some(20), .. })); } } - /// The open dialog of `app` in a test harness, drawn and ready for clicks. - fn harness(app: VectorcraftApp) -> egui_kittest::Harness<'static, VectorcraftApp> { - let mut fonts = false; - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state( - move |ui, app: &mut VectorcraftApp| { - if !std::mem::replace(&mut fonts, true) { - crate::theme::install_fonts(ui.ctx()); - return; - } - super::super::show(app, ui.ctx()); - }, - app, - ); - h.run_steps(4); - h - } - - /// Clicking Template ticks Lock and Dim Images and leaves them to each layer; clicking Dim - /// Images off afterwards sends that to every layer. - #[test] - fn dim_images_clicked_after_template_goes_to_every_layer() { - use egui_kittest::kittest::Queryable; - let mut app = app(); - let (first, second) = two_layers(&mut app); - let mut h = harness(app); - h.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Template").click(); - h.run_steps(3); - let d = h.state().ui.dialog.as_ref().unwrap(); - assert!(d.bool("template") && d.bool("locked") && d.bool("dimImages")); - assert_eq!(params(d).1, json!({"template": true, "ids": [first.0, second.0]})); - h.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Dim Images to:").click(); - h.run_steps(3); - let (_, p) = params(h.state().ui.dialog.as_ref().unwrap()); - assert_eq!(p, json!({"template": true, "dimImages": false, "ids": [first.0, second.0]})); - let app = h.state_mut(); - super::super::confirm(app).unwrap(); - for id in [first, second] { - let n = layer(app, id); - assert!(n.locked && matches!(n.kind, NodeKind::Layer { template: true, dim_images: None, .. })); - } - } - /// Template set through `ui.dialog.set` locks and dims as its checkbox does, and set back it /// shows the first layer's Lock and Dim Images again and sends neither. #[test] @@ -532,14 +770,14 @@ mod tests { app.run("layer.setProps", json!({"ids": [first.0], "locked": true})).unwrap(); app.run("ui.layerOptions", json!({"ids": [first.0, second.0]})).unwrap(); set(&mut app, "template", json!(true)); - let d = app.ui.dialog.as_ref().unwrap(); - assert!(d.bool("locked") && d.bool("dimImages")); - assert_eq!(params(d).1, json!({"template": true, "ids": [first.0, second.0]})); + let f = fields(&app); + assert!(f["locked"] == json!(true) && f["dimImages"] == json!(true)); + assert_eq!(current_params(&app), json!({"template": true, "ids": [first.0, second.0]})); set(&mut app, "template", json!(false)); - let d = app.ui.dialog.as_ref().unwrap(); - assert!(d.bool("locked") && !d.bool("dimImages")); - assert_eq!(params(d).1, json!({"template": false, "ids": [first.0, second.0]})); - super::super::confirm(&mut app).unwrap(); + let f = fields(&app); + assert!(f["locked"] == json!(true) && f["dimImages"] == json!(false)); + assert_eq!(current_params(&app), json!({"template": false, "ids": [first.0, second.0]})); + ok(&mut app); assert!(layer(&app, first).locked && layer(&app, second).locked); assert!(matches!(layer(&app, second).kind, NodeKind::Layer { dim_images: Some(30), .. })); } @@ -553,52 +791,32 @@ mod tests { app.run("layer.setProps", json!({"ids": [first.0], "dimImages": 30})).unwrap(); app.run("ui.layerOptions", json!({"ids": [first.0, second.0]})).unwrap(); set(&mut app, "template", json!(true)); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.f64("dimPercent", 0.0), 50.0); + assert_eq!(fields(&app)["dimPercent"].as_f64(), Some(50.0)); set(&mut app, "template", json!(false)); - let d = app.ui.dialog.as_ref().unwrap(); - assert!(d.bool("dimImages")); - assert_eq!(d.f64("dimPercent", 0.0), 30.0); - assert_eq!(params(d).1, json!({"template": false, "ids": [first.0, second.0]})); + let f = fields(&app); + assert_eq!(f["dimImages"], json!(true)); + assert_eq!(f["dimPercent"].as_f64(), Some(30.0)); + assert_eq!(current_params(&app), json!({"template": false, "ids": [first.0, second.0]})); set(&mut app, "template", json!(true)); - super::super::confirm(&mut app).unwrap(); + ok(&mut app); assert!(matches!(layer(&app, first).kind, NodeKind::Layer { template: true, dim_images: Some(50), .. })); } - /// Template set through `ui.dialog.set` for one layer locks it and dims its images, as the - /// checkbox does. - #[test] - fn template_set_for_one_layer_locks_and_dims_it() { - let mut app = app(); - let id = app.session.doc().unwrap().doc.layers[0].id; - app.run("ui.layerOptions", json!({"ids": [id.0]})).unwrap(); - set(&mut app, "template", json!(true)); - super::super::confirm(&mut app).unwrap(); - let n = layer(&app, id); - assert!(n.locked && matches!(n.kind, NodeKind::Layer { template: true, dim_images: Some(50), .. })); - } - - /// A percentage typed in while Dim Images is on stays set when Template is then clicked on, + /// A percentage set while Dim Images is on stays sent when Template is then set on and off, /// since Template leaves Dim Images on. #[test] fn a_percentage_typed_before_template_goes_to_every_layer() { - use egui_kittest::kittest::Queryable; let mut app = app(); let (first, second) = two_layers(&mut app); app.run("layer.setProps", json!({"ids": [first.0], "dimImages": 30})).unwrap(); app.run("ui.layerOptions", json!({"ids": [first.0, second.0]})).unwrap(); set(&mut app, "dimPercent", json!(40)); - let mut h = harness(app); - h.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Template").click(); - h.run_steps(3); - let (_, p) = params(h.state().ui.dialog.as_ref().unwrap()); - assert_eq!(p, json!({"template": true, "dimImages": 40.0, "ids": [first.0, second.0]})); + set(&mut app, "template", json!(true)); + assert_eq!(current_params(&app), json!({"template": true, "dimImages": 40.0, "ids": [first.0, second.0]})); // Template off again shows the first layer's Dim Images, on, and the percentage still // goes to every layer. - h.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Template").click(); - h.run_steps(3); - let (_, p) = params(h.state().ui.dialog.as_ref().unwrap()); - assert_eq!(p, json!({"template": false, "dimImages": 40.0, "ids": [first.0, second.0]})); + set(&mut app, "template", json!(false)); + assert_eq!(current_params(&app), json!({"template": false, "dimImages": 40.0, "ids": [first.0, second.0]})); } /// A Dim Images set in the dialog stays as set when Template is set after it, so @@ -615,10 +833,14 @@ mod tests { set(&mut app, "template", json!(true)); set(&mut app, "dimImages", json!(false)); } - let d = app.ui.dialog.as_ref().unwrap(); - assert!(d.bool("template") && d.bool("locked") && !d.bool("dimImages"), "dim first: {dim_first}"); - assert_eq!(params(d).1, json!({"template": true, "dimImages": false, "ids": [first.0, second.0]}), "dim first: {dim_first}"); - super::super::confirm(&mut app).unwrap(); + let f = fields(&app); + assert!(f["template"] == json!(true) && f["locked"] == json!(true) && f["dimImages"] == json!(false), "dim first: {dim_first}"); + assert_eq!( + current_params(&app), + json!({"template": true, "dimImages": false, "ids": [first.0, second.0]}), + "dim first: {dim_first}" + ); + ok(&mut app); for id in [first, second] { let n = layer(&app, id); assert!(n.locked && matches!(n.kind, NodeKind::Layer { template: true, dim_images: None, .. }), "{id:?}, dim first: {dim_first}"); @@ -627,7 +849,7 @@ mod tests { } /// OK in New Layer Options makes no layer outside the isolated art when isolation mode started - /// while the dialog was open. + /// while the dialog was open; the dialog stays open with the reason. #[test] fn new_layer_options_ok_checks_isolation_again() { let mut app = app(); @@ -637,9 +859,12 @@ mod tests { let group = id(app.session.execute("object.group", &json!({})).unwrap()); app.run("ui.newLayer", json!({})).unwrap(); app.session.execute("object.isolate", &json!({"id": group})).unwrap(); - draw(&mut app); - let err = super::super::confirm(&mut app).unwrap_err(); - assert!(err.contains("exit isolation mode first"), "{err}"); + // OK once and the pump's answer; a second OK would file the refused value again. + let (ctx, dialog) = (app.ui_ctx.clone().unwrap(), open_id(&app)); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog)); + crate::dialogs::host::pump(&mut app, &ctx); + let state = app.dialogs().unwrap().with(|host| host.held_state(dialog)); + assert!(matches!(state, Some(HeldOk::Refused(_))), "{state:?}"); assert_eq!(app.session.doc().unwrap().doc.layers.len(), 1); } @@ -647,30 +872,27 @@ mod tests { fn new_layer_options_make_a_layer_and_objects_get_name_show_and_lock() { let mut app = app(); app.run("ui.newLayer", json!({})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("name"), "Layer 2"); + assert_eq!(fields(&app)["name"], json!("Layer 2")); set(&mut app, "name", json!("Ink")); - set(&mut app, "template", json!(true)); + // Template locks the layer and takes Lock out of the dialog's reach. set(&mut app, "locked", json!(true)); - draw(&mut app); - super::super::confirm(&mut app).unwrap(); + set(&mut app, "template", json!(true)); + assert!(try_set(&mut app, "locked", json!(false)).is_err()); + ok(&mut app); let d = &app.session.doc().unwrap().doc; let top = d.layers.last().unwrap(); assert_eq!(top.display_name(), "Ink"); assert!(top.is_template() && top.locked); // An object's row: Name, Show and Lock. - let r = app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})); - assert!(r.is_ok()); app.session.execute("layer.setCurrent", &json!({"id": app.session.doc().unwrap().doc.layers[0].id.0})).unwrap(); let rect = app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); app.run("ui.layerOptions", json!({"id": rect})).unwrap(); - assert!(!app.ui.dialog.as_ref().unwrap().bool("layer")); - draw(&mut app); + assert_eq!(fields(&app)["layer"], json!(false)); + assert!(try_set(&mut app, "template", json!(true)).is_err(), "an object has no Template"); set(&mut app, "name", json!("Box")); set(&mut app, "locked", json!(true)); - let (cmd, p) = params(app.ui.dialog.as_ref().unwrap()); - assert_eq!(cmd, "layer.setProps"); - assert!(p.get("template").is_none()); - super::super::confirm(&mut app).unwrap(); + assert_eq!(current_params(&app)["template"], Value::Null); + ok(&mut app); let n = app.session.doc().unwrap().doc.node(NodeId(rect)).unwrap().clone(); assert_eq!((n.display_name(), n.locked), ("Box".to_string(), true)); } diff --git a/crates/ui-egui/src/dialogs/layers_panel_options.rs b/crates/ui-egui/src/dialogs/layers_panel_options.rs index 72e518fdeb..eaca63ce55 100644 --- a/crates/ui-egui/src/dialogs/layers_panel_options.rs +++ b/crates/ui-egui/src/dialogs/layers_panel_options.rs @@ -1,139 +1,130 @@ //! Layers panel › Panel Options…: Show Layers Only, Locate Selected Objects, the row size and //! which rows show thumbnails. //! -//! Fields: `layersOnly`, `locateSelected`, `rowSize` (`small`, `medium`, `large` or `other`), -//! `otherSize` (points, 12–100, for `other`), `thumbLayers`, `thumbGroups` and `thumbObjects`. OK -//! applies them to the panel (kept with the UI state). +//! Fields: `layersOnly`, `locateSelected`, `rowSize` (`small`, `medium` or `large`), `thumbLayers`, +//! `thumbGroups` and `thumbObjects`. OK applies them to the panel (kept with the UI state). -use serde_json::{Value, json}; +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use serde_json::Value; -use super::DialogSpec; -use super::swatch_options::{grid, label}; -use crate::panels::layers::{PanelOptions, ROW_LARGE, ROW_MEDIUM, ROW_SMALL}; -use crate::state::Dialog; -use crate::{VectorcraftApp, widgets}; +use super::host::open_held; +use crate::VectorcraftApp; +use crate::panels::layers::{PanelOptions, RowSize}; -/// The dialog kind of the Layers Panel Options. -pub const KIND: &str = "layersPanelOptions"; +/// The command Layers Panel Options answers for; the key of its dialog. +const CMD: &str = "ui.layersPanelOptions"; -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("Layers Panel Options").into(), body, confirm, min_width: 300.0, ..DialogSpec::FORM }; +/// The row sizes the dialog offers: the field's value and the size it stands for. +const SIZES: [(&str, RowSize); 3] = [("small", RowSize::Small), ("medium", RowSize::Medium), ("large", RowSize::Large)]; -const SIZES: [(&str, &str, f32); 3] = [("small", "Small", ROW_SMALL), ("medium", "Medium", ROW_MEDIUM), ("large", "Large", ROW_LARGE)]; +/// The dialog's rows. +// PLAN: the sheet names `Param::bool`/`Param::choice`; the framework has `Param::new(key, label, ParamKind::..)` only. +fn rows() -> Vec { + let sizes = [("small", tl!("Small")), ("medium", tl!("Medium")), ("large", tl!("Large"))]; + let sizes = sizes.into_iter().map(|(id, label)| (id.to_owned(), label.into())).collect(); + vec![ + Param::new("layersOnly", tl!("Show Layers Only"), ParamKind::bool(false)), + Param::new("locateSelected", tl!("Locate Selected Objects"), ParamKind::bool(false)), + Param::new("rowSize", tl!("Row Size:"), ParamKind::choice(sizes, Some("medium".to_owned()))), + Param::section(tl!("Thumbnails:")), + Param::new("thumbLayers", tl!("Layers"), ParamKind::bool(true)), + Param::new("thumbGroups", tl!("Group"), ParamKind::bool(true)), + Param::new("thumbObjects", tl!("Object"), ParamKind::bool(true)), + ] +} /// `ui.layersPanelOptions`: open the dialog on the panel's options. pub fn open(app: &mut VectorcraftApp) -> Result { + let ctx = app.ui_ctx.clone().ok_or("no window")?; let o = &app.ui.layers_panel; - let size = SIZES.iter().find(|s| (s.2 - o.row()).abs() < 0.01).map_or("other", |s| s.0); - let fields = json!({ - "layersOnly": o.layers_only, "locateSelected": o.locate_selected, "rowSize": size, "otherSize": o.row(), - "thumbLayers": o.thumb_layers, "thumbGroups": o.thumb_groups, "thumbObjects": o.thumb_objects, + let mut fields = DialogFields::new(); + fields.set("layersOnly", o.layers_only); + fields.set("locateSelected", o.locate_selected); + fields.set("rowSize", SIZES.iter().find(|s| s.1 == o.row_size).map_or("medium", |s| s.0)); + fields.set("thumbLayers", o.thumb_layers); + fields.set("thumbGroups", o.thumb_groups); + fields.set("thumbObjects", o.thumb_objects); + let dialog = HostedParamDialog::command(&ctx, CMD, fields, |fields| { + ParamDialog::command(CMD, tl!("Layers Panel Options"), rows()).values(Bind::bound(fields)) }); - app.ui.dialog = Some(Dialog::new(KIND, fields)); + let ok = |app: &mut VectorcraftApp, result: &ParamResult| { + let f = &result.fields; + let flag = |key: &str| f.bool(key).unwrap_or_default(); + app.ui.layers_panel = PanelOptions { + layers_only: flag("layersOnly"), + locate_selected: flag("locateSelected"), + row_size: SIZES.iter().find(|s| Some(s.0) == f.text("rowSize")).map_or(RowSize::Medium, |s| s.1), + thumb_layers: flag("thumbLayers"), + thumb_groups: flag("thumbGroups"), + thumb_objects: flag("thumbObjects"), + }; + Ok(()) + }; + open_held(app, dialog, ok).ok_or("no window")?; Ok(Value::Null) } -fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, text: &str) { - let v = d.bool(key); - if widgets::check(ui, text, v, true) { - d.fields.insert(key.into(), json!(!v)); - } -} - -fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - check(ui, d, "layersOnly", tl!("Show Layers Only")); - check(ui, d, "locateSelected", tl!("Locate Selected Objects")); - ui.add_space(8.0); - grid(ui, |ui| { - label(ui, tl!("Row Size:")); - ui.horizontal(|ui| { - let cur = d.str("rowSize"); - let labels: Vec<&str> = SIZES.iter().map(|s| s.1).chain(["Other"]).collect(); - let shown = SIZES.iter().find(|s| s.0 == cur).map_or("Other", |s| s.1); - if let Some(i) = widgets::dropdown(ui, "layers-row-size", shown, &labels, 110.0) { - d.fields.insert("rowSize".into(), json!(SIZES.get(i).map_or("other", |s| s.0))); - } - let v = d.f64("otherSize", f64::from(ROW_MEDIUM)); - let other = d.str("rowSize") == "other"; - if let Some(v) = ui.add_enabled_ui(other, |ui| widgets::range_field(ui, "otherSize", v, 12.0..=100.0, " pt", 0, 60.0)).inner { - d.fields.insert("otherSize".into(), json!(v)); - } - }); - ui.end_row(); - }); - ui.add_space(8.0); - label(ui, tl!("Thumbnails:")); - check(ui, d, "thumbLayers", tl!("Layers")); - check(ui, d, "thumbGroups", tl!("Group")); - check(ui, d, "thumbObjects", tl!("Object")); - false -} - -/// The options the fields describe. -pub(crate) fn options(d: &Dialog) -> PanelOptions { - let size = d.str("rowSize"); - let row_size = SIZES.iter().find(|s| s.0 == size).map_or_else(|| (d.f64("otherSize", f64::from(ROW_MEDIUM)) as f32).clamp(12.0, 100.0), |s| s.2); - PanelOptions { - layers_only: d.bool("layersOnly"), - locate_selected: d.bool("locateSelected"), - row_size: if row_size.is_finite() { row_size } else { ROW_MEDIUM }, - thumb_layers: d.bool("thumbLayers"), - thumb_groups: d.bool("thumbGroups"), - thumb_objects: d.bool("thumbObjects"), - } -} - -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - app.ui.layers_panel = options(d); - app.ui.dialog = None; - Ok(serde_json::to_value(&app.ui.layers_panel).unwrap_or_default()) -} - #[cfg(test)] mod tests { use super::*; + use serde_json::json; use vectorcraft_engine::Session; + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(egui::Context::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app + } + + /// The open dialog's id and fields. + fn open_dialog(app: &VectorcraftApp) -> (craft::ui::dialog::DialogId, Value) { + let open = app.dialogs().unwrap().with(|host| host.open_dialogs().into_iter().find(|d| d.key.as_deref() == Some(CMD))).unwrap(); + (open.id, open.fields.unwrap()) + } + + /// Sets `edits` in the open dialog, presses OK and runs the host pump, which runs the held OK. + fn apply(app: &mut VectorcraftApp, edits: &[(&str, Value)]) { + let ctx = app.ui_ctx.clone().unwrap(); + let (id, _) = open_dialog(app); + let dialogs = app.dialogs().unwrap(); + for (field, value) in edits { + dialogs.with(|host| host.set_json_field(&ctx, id, field, value.clone())).unwrap(); + } + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(app, &ctx); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + } + #[test] fn panel_options_round_trip_and_apply() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let mut app = app(); app.run("ui.layersPanelOptions", json!({})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("rowSize"), "medium"); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(&mut app, ui.ctx())); - out.textures_delta.clear(); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("layersOnly".into(), json!(true)); - d.fields.insert("rowSize".into(), json!("other")); - d.fields.insert("otherSize".into(), json!(500)); - d.fields.insert("thumbObjects".into(), json!(false)); - super::super::confirm(&mut app).unwrap(); + assert_eq!(open_dialog(&app).1["rowSize"], json!("medium")); + apply(&mut app, &[("layersOnly", json!(true)), ("rowSize", json!("large")), ("thumbObjects", json!(false))]); let o = &app.ui.layers_panel; assert!(o.layers_only && !o.thumb_objects && o.thumb_layers); - assert_eq!(o.row(), 100.0, "kept to 100 pt"); + assert_eq!(o.row_size, RowSize::Large); app.run("ui.layersPanelOptions", json!({})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("rowSize".into(), json!("large")); - super::super::confirm(&mut app).unwrap(); - assert_eq!(app.ui.layers_panel.row(), ROW_LARGE); + assert_eq!(open_dialog(&app).1["rowSize"], json!("large"), "opens on the saved size"); + // Options saved with a row height in points load as the nearest size. + let old: crate::UiState = serde_json::from_value(json!({"layers_panel": {"rowSize": 500}})).unwrap(); + assert_eq!(old.layers_panel.row_size, RowSize::Large); } /// Locate Selected Objects is off by default and in options saved without it; OK turns it on /// and keeps it with the UI state, and the dialog opens on it again. #[test] fn locate_selected_objects_is_off_by_default_and_kept_with_the_ui_state() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let mut app = app(); app.run("ui.layersPanelOptions", json!({})).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - assert_eq!(d.fields.get("locateSelected"), Some(&json!(false))); - d.fields.insert("locateSelected".into(), json!(true)); - super::super::confirm(&mut app).unwrap(); + assert_eq!(open_dialog(&app).1["locateSelected"], json!(false)); + apply(&mut app, &[("locateSelected", json!(true))]); let back: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); assert!(back.layers_panel.locate_selected, "kept with the UI state"); app.run("ui.layersPanelOptions", json!({})).unwrap(); - assert!(app.ui.dialog.as_ref().unwrap().bool("locateSelected")); + assert_eq!(open_dialog(&app).1["locateSelected"], json!(true)); let old: crate::UiState = serde_json::from_value(json!({"layers_panel": {"layersOnly": true}})).unwrap(); assert!(old.layers_panel.layers_only && !old.layers_panel.locate_selected, "options saved without it"); } diff --git a/crates/ui-egui/src/dialogs/navigator_panel_options.rs b/crates/ui-egui/src/dialogs/navigator_panel_options.rs index c0988ec548..d8cb805e1d 100644 --- a/crates/ui-egui/src/dialogs/navigator_panel_options.rs +++ b/crates/ui-egui/src/dialogs/navigator_panel_options.rs @@ -1,63 +1,162 @@ //! Navigator panel › Panel Options…: the color the view box is drawn in, a preset or a custom //! color, and Draw Dashed Lines as Solid Lines for the thumbnail. //! -//! Fields: `color` (`#rrggbb`, or a preset's name such as "Light Red") and `solidDashes`. OK runs +//! Fields: `color` (`#rrggbb`; a preset's name such as "Light Red" is read too) and `solidDashes`. OK runs //! `ui.navigatorPanelOptions` with them (kept with the UI state). +use std::cell::RefCell; + +use craft::color_ui::{ChosenColor, ColorChoice, NamedColor}; +use craft::theme::Srgba; +use craft::ui::contract::{Bind, ShowContainer as _}; +use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; +use craft::ui::form::Field; +use craft::ui::patterns::form_dialogs::FormDialog; +use craft::ui::runtime::requests::ColorRequest; use serde_json::{Value, json}; use vectorcraft_color::Color; -use super::swatch_options::{grid, label}; -use super::{DialogSpec, run_and_close}; +use super::layer_options::{check, rgb8, srgb}; +use crate::VectorcraftApp; use crate::panels::navigator::{VIEW_BOX_RED, resolve, view_box_colors}; -use crate::state::Dialog; -use crate::{VectorcraftApp, widgets}; -/// The dialog kind of the Navigator Panel Options. -pub const KIND: &str = "navigatorPanelOptions"; +/// The key of the Navigator Panel Options dialog. +const KEY: &str = "ui.navigatorPanelOptions"; -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("Navigator Panel Options").into(), body, confirm, min_width: 300.0, ..DialogSpec::FORM }; +/// The options the dialog edits. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct NavigatorOptionsValue { + /// The view box's colour: a preset's, or any other the Custom row holds. + rgb: [u8; 3], + solid_dashes: bool, +} + +impl NavigatorOptionsValue { + /// The colour as `ui.navigatorPanelOptions` takes it. + fn color_text(&self) -> String { + let [r, g, b] = self.rgb; + Color::rgb8(r, g, b).to_hex() + } +} + +impl Default for NavigatorOptionsValue { + fn default() -> Self { + NavigatorOptionsValue { rgb: VIEW_BOX_RED, solid_dashes: false } + } +} /// `ui.navigatorPanelOptions` without options: open the dialog on the panel's options. pub fn open(app: &mut VectorcraftApp) -> Result { let o = &app.ui.navigator_panel; - app.ui.dialog = Some(Dialog::new(KIND, json!({ "color": o.color, "solidDashes": o.solid_dashes }))); + let value = NavigatorOptionsValue { rgb: resolve(&o.color).unwrap_or(VIEW_BOX_RED), solid_dashes: o.solid_dashes }; + let dialogs = app.dialogs().ok_or("no window")?; + dialogs.with(|host| host.open(NavigatorOptionsDialog::new(value))); Ok(Value::Null) } -fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let [r, g, b] = resolve(&d.str("color")).unwrap_or(VIEW_BOX_RED); - let presets: Vec<(&str, [u8; 3])> = view_box_colors().collect(); - let preset = presets.iter().position(|(_, c)| *c == [r, g, b]); - let names: Vec<&str> = presets.iter().map(|(n, _)| *n).chain(["Custom"]).collect(); - grid(ui, |ui| { - label(ui, tl!("Color:")); - ui.horizontal(|ui| { - if let Some((_, [r, g, b])) = - widgets::dropdown(ui, "navigator-view-box", names[preset.unwrap_or(presets.len())], &names, 140.0).and_then(|i| presets.get(i)) - { - d.fields.insert("color".into(), json!(Color::rgb8(*r, *g, *b).to_hex())); - } - // Any other color (the preset list shows Custom then). - let mut rgb = [r, g, b]; - if ui.color_edit_button_srgb(&mut rgb).changed() { - d.fields.insert("color".into(), json!(Color::rgb8(rgb[0], rgb[1], rgb[2]).to_hex())); - } - }); - ui.end_row(); - }); - ui.add_space(8.0); - let solid = d.bool("solidDashes"); - if widgets::check(ui, tl!("Draw Dashed Lines as Solid Lines"), solid, true) { - d.fields.insert("solidDashes".into(), json!(!solid)); - } - false +/// The Navigator Panel Options dialog; its answer is the options OK confirmed, which [`pump`] applies. +pub(crate) struct NavigatorOptionsDialog { + id: DialogId, + open: bool, + value: NavigatorOptionsValue, + /// The Custom… press, until the app takes it. + color_request: Option, } -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let params = json!({ "color": d.fields.get("color").cloned().unwrap_or(Value::Null), "solidDashes": d.bool("solidDashes") }); - run_and_close(app, "ui.navigatorPanelOptions", params) +impl NavigatorOptionsDialog { + /// The dialog over `value`. + fn new(value: NavigatorOptionsValue) -> Self { + NavigatorOptionsDialog { id: dialog_id(KEY), open: true, value, color_request: None } + } +} + +impl StackDialog for NavigatorOptionsDialog { + type Result = NavigatorOptionsValue; + + fn id(&self) -> DialogId { + self.id + } + + fn key(&self) -> Option<&str> { + Some(KEY) + } + + fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option> { + let requested = RefCell::new(None); + let shown = FormDialog::new(tl!("Navigator Panel Options"), Bind::bound(&mut self.value)).opened(Bind::bound(&mut self.open)).show( + ui, + |ui, _, v| { + Field::new(tl!("Color:")).id_salt("color").show(ui, |ui, _| { + let presets: Vec<(&str, [u8; 3])> = view_box_colors().collect(); + let preset = presets.iter().find(|(_, c)| *c == v.rgb); + let chosen = preset.map_or(ChosenColor::Custom, |(name, _)| ChosenColor::Named((*name).to_owned())); + let named = presets.iter().map(|&(name, c)| NamedColor::new(name, name.to_string(), Some(srgb(c)))); + let custom = preset.is_none().then(|| srgb(v.rgb)); + let out = ColorChoice::new(tl!("Color:"), &chosen).named(named).custom(custom).show(ui); + if let Some(ChosenColor::Named(picked)) = out.chosen + && let Some((_, c)) = presets.iter().find(|(name, _)| *name == picked) + { + v.rgb = *c; + } + // A second pass of the frame has no press: only a request keeps what the first pass asked for. + if let Some(request) = out.pick_color { + *requested.borrow_mut() = Some(request); + } + }); + if let Some(on) = check(ui, tl!("Draw Dashed Lines as Solid Lines"), v.solid_dashes, true) { + v.solid_dashes = on; + } + true + }, + ); + if let Some(request) = requested.into_inner() { + self.color_request = Some(request); + } + match (shown.accepted, shown.closed) { + (Some(value), _) => Some(DialogResult::Ok(value)), + (None, Some(_)) => Some(DialogResult::Cancel), + (None, None) => None, + } + } + + fn confirm(&mut self, _: &egui::Context) -> Option { + Some(self.value.clone()) + } + + fn json_fields(&self) -> Option { + Some(json!({ "color": self.value.color_text(), "solidDashes": self.value.solid_dashes })) + } + + fn set_json_field(&mut self, _: &egui::Context, field: &str, value: Value) -> Result<(), String> { + let rejects = || FieldRefusal::Rejects(&value).message(field); + match field { + "color" => self.value.rgb = value.as_str().and_then(resolve).ok_or_else(rejects)?, + "solidDashes" => self.value.solid_dashes = value.as_bool().ok_or_else(rejects)?, + _ => return Err(FieldRefusal::Unknown.message(field)), + } + Ok(()) + } + + fn take_color_request(&mut self) -> Option { + self.color_request.take() + } + + fn answer_color(&mut self, key: &str, color: Srgba) { + if key == ColorChoice::CUSTOM_KEY { + self.value.rgb = rgb8(color); + } + } +} + +/// Applies the options OK confirmed; an error from the command goes to the status line. +pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(dialogs) = app.dialogs() else { return }; + let Some(DialogResult::Ok(value)) = dialogs.with(|host| host.take::()) else { return }; + let params = json!({ "color": value.color_text(), "solidDashes": value.solid_dashes }); + if let Err(e) = app.run("ui.navigatorPanelOptions", params) { + app.status(e); + } + ctx.request_repaint(); } #[cfg(test)] @@ -65,34 +164,49 @@ mod tests { use super::*; use vectorcraft_engine::Session; + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(egui::Context::default()); + app + } + + /// The open dialog's id and fields. + fn open_dialog(app: &VectorcraftApp) -> (DialogId, Value) { + let open = app.dialogs().unwrap().with(|host| host.open_dialogs().into_iter().find(|d| d.key.as_deref() == Some(KEY))).unwrap(); + (open.id, open.fields.unwrap()) + } + + /// Sets the dialog's `color` and `solidDashes`, presses OK and runs the host pump. + fn apply(app: &mut VectorcraftApp, color: &str, solid: bool) { + let ctx = app.ui_ctx.clone().unwrap(); + let (id, _) = open_dialog(app); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.set_json_field(&ctx, id, "color", json!(color))).unwrap(); + dialogs.with(|host| host.set_json_field(&ctx, id, "solidDashes", json!(solid))).unwrap(); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(app, &ctx); + } + /// The dialog opens on the panel's options (Light Red and solid dashes off by default), and OK /// sets a preset's or a custom color and Draw Dashed Lines as Solid Lines, kept with the UI /// state; a value that is not a color is refused and leaves the options as they were. #[test] fn panel_options_set_the_view_box_color_and_solid_dashes() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = app(); app.run("ui.navigatorPanelOptions", json!({})).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.kind.as_str(), d.str("color"), d.bool("solidDashes")), (KIND, "#ff3030".to_string(), false)); - // Drawn headlessly in the shared frame: the preset's name shows. - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(&mut app, ui.ctx())); - out.textures_delta.clear(); - let set = |app: &mut VectorcraftApp, color: &str, solid: bool| { - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("color".into(), json!(color)); - d.fields.insert("solidDashes".into(), json!(solid)); - super::super::confirm(app) - }; - assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true, "viewArtboardContentsOnly": true})); - assert!(app.ui.dialog.is_none()); + let f = open_dialog(&app).1; + assert_eq!((f["color"].as_str(), f["solidDashes"].as_bool()), (Some("#ff3030"), Some(false))); + apply(&mut app, "Green", true); + assert!(!app.any_dialog_open()); + assert_eq!((app.ui.navigator_panel.color.as_str(), app.ui.navigator_panel.solid_dashes), ("#4fff4f", true)); app.run("ui.navigatorPanelOptions", json!({})).unwrap(); - set(&mut app, "#0000FF", true).unwrap(); + apply(&mut app, "#0000FF", true); assert_eq!(app.ui.navigator_panel.color, "#0000ff"); app.run("ui.navigatorPanelOptions", json!({})).unwrap(); - assert!(set(&mut app, "nope", false).is_err()); - assert!(app.ui.navigator_panel.solid_dashes && app.ui.navigator_panel.color == "#0000ff", "a refused value changes nothing"); + let (ctx, (id, _)) = (app.ui_ctx.clone().unwrap(), open_dialog(&app)); + let refused = app.dialogs().unwrap().with(|host| host.set_json_field(&ctx, id, "color", json!("nope"))); + assert!(refused.is_err()); + assert_eq!(open_dialog(&app).1["color"], json!("#0000ff"), "a refused value changes nothing"); let back: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); assert_eq!(back.navigator_panel, app.ui.navigator_panel, "kept with the UI state"); let old: crate::UiState = serde_json::from_value(json!({})).unwrap(); diff --git a/crates/ui-egui/src/dialogs/rearrange_artboards.rs b/crates/ui-egui/src/dialogs/rearrange_artboards.rs index 6fa90910a4..6dcfe7ab70 100644 --- a/crates/ui-egui/src/dialogs/rearrange_artboards.rs +++ b/crates/ui-egui/src/dialogs/rearrange_artboards.rs @@ -7,121 +7,285 @@ //! Fields: `layout` (`gridByRow` | `gridByColumn` | `row` | `column`), `order` (`leftToRight` | //! `rightToLeft`), `columns` (the rows of a grid by column), `spacing` (pt) and `moveArtwork`. +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; +use craft::ui::display::Text; +use craft::ui::form::Field; +use craft::ui::patterns::form_dialogs::FormDialog; +use craft::ui::primitives::{Glyph, IconSpec}; +use craft::ui::runtime::env::{LengthUnits, UnitKind}; +use craft::ui::style::{TypeRole, UiTokens}; +use craft::ui::text::NumberField; +use craft::ui::choice::Segmented; +use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, vec2}; use serde_json::{Value, json}; +use vectorcraft_doc::Unit; use vectorcraft_engine::cmd::newdoc::ArtboardLayout; -use super::{DialogSpec, form, run_and_close}; -use crate::state::Dialog; -use crate::{VectorcraftApp, widgets}; +use super::layer_options::check; +use crate::VectorcraftApp; -/// The dialog kind of Rearrange All Artboards. -pub const KIND: &str = "rearrangeArtboards"; +/// The command Rearrange All Artboards runs; the key of its dialog. +pub(crate) const CMD: &str = "artboard.rearrange"; -const CMD: &str = "artboard.rearrange"; +/// A layout toggle's picture: small artboards in the grid cells (column, row), tinted, and over them their order as a +/// line from a dot on the first to an arrowhead on the last. +struct CellsGlyph(&'static [(u8, u8)]); -/// Width of the label column. -const LABEL_W: f32 = 96.0; - -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("Rearrange All Artboards").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; - -/// The fields a fresh dialog starts with. -pub fn fields() -> Value { - json!({"layout": "gridByRow", "order": "leftToRight", "columns": 2, "spacing": 20, "moveArtwork": true}) -} - -/// The fields the menu item opens with, retaining the spacing from its last confirmation. -pub fn open_fields(app: &VectorcraftApp) -> Value { - let mut fields = fields(); - if let Some(spacing) = app.ui.rearrange_artboards_spacing.as_f64() { - fields["spacing"] = json!(spacing); - } - fields -} - -/// A layout's toggle: its tooltip and its artboards' cells (column, row) in their order, left to -/// right. -fn layout_glyph(l: ArtboardLayout) -> (&'static str, &'static [(u8, u8)]) { - match l { - ArtboardLayout::GridByRow => (tl!("Grid by Row"), &[(0, 0), (1, 0), (0, 1), (1, 1)]), - ArtboardLayout::GridByColumn => (tl!("Grid by Column"), &[(0, 0), (0, 1), (1, 0), (1, 1)]), - ArtboardLayout::Row => (tl!("Arrange by Row"), &[(0, 0), (1, 0), (2, 0)]), - ArtboardLayout::Column => (tl!("Arrange by Column"), &[(0, 0), (0, 1), (0, 2)]), - } -} - -/// `cells` mirrored left to right when `rtl` (the order the layout toggles preview). -fn mirrored(cells: &[(u8, u8)], rtl: bool) -> Vec<(u8, u8)> { - let last = cells.iter().map(|c| c.0).max().unwrap_or(0); - cells.iter().map(|&(x, y)| (if rtl { last - x } else { x }, y)).collect() -} - -/// `artboard.rearrange` parameters from the fields. -fn params(d: &Dialog) -> Value { - json!({ - "layout": d.str("layout"), "order": d.str("order"), "columns": d.f64("columns", 2.0), - "spacing": d.f64("spacing", 20.0), "moveArtwork": d.bool("moveArtwork"), - }) -} - -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let unit = app.session.general_unit(); - let n = app.session.active().map_or(0, |doc| doc.doc.artboards.len()); - let layout = ArtboardLayout::parse(&d.str("layout")).unwrap_or_default(); - let rtl = d.str("order") == "rightToLeft"; - widgets::label_row(ui, tl!("Layout:"), LABEL_W, |ui| { - ui.spacing_mut().item_spacing.x = 2.0; - for l in ArtboardLayout::ALL { - let (tip, cells) = layout_glyph(l); - if widgets::layout_button(ui, &mirrored(cells, rtl), layout == l, tip) { - d.fields.insert("layout".into(), json!(l.id())); - } +impl Glyph for CellsGlyph { + fn paint(&self, painter: &Painter, _: &UiTokens, rect: Rect, color: Color32, _: bool) { + let tiles = self.0; + // Cells at most half the square a side: a row's artboards stand tall, a column's lie flat. + let side = rect.width().min(rect.height()); + let scale = side / 20.0; + let (cols, rows) = tiles.iter().fold((1u8, 1u8), |(c, r), &(x, y)| (c.max(x.saturating_add(1)), r.max(y.saturating_add(1)))); + let cell = vec2((side / f32::from(cols)).min(side / 2.0), (side / f32::from(rows)).min(side / 2.0)); + let origin = rect.center() - vec2(f32::from(cols) * cell.x, f32::from(rows) * cell.y) / 2.0; + let centre = |&(x, y): &(u8, u8)| origin + vec2((f32::from(x) + 0.5) * cell.x, (f32::from(y) + 0.5) * cell.y); + for tile in tiles { + painter.rect_filled(Rect::from_center_size(centre(tile), cell - vec2(2.0, 2.0) * scale), 1.0, color.gamma_multiply(0.35)); } - }); - ui.add_space(4.0); - widgets::label_row(ui, tl!("Layout Order:"), LABEL_W, |ui| { - ui.spacing_mut().item_spacing.x = 2.0; - // One column reads the same either way. - ui.add_enabled_ui(layout != ArtboardLayout::Column, |ui| { - for (value, cells, tip) in [ - ("leftToRight", [(0, 0), (1, 0)], tl!("Change to Left-to-Right Layout")), - ("rightToLeft", [(1, 0), (0, 0)], tl!("Change to Right-to-Left Layout")), - ] { - if widgets::layout_button(ui, &cells, (value == "rightToLeft") == rtl, tip) { - d.fields.insert("order".into(), json!(value)); - } - } - }); - }); - ui.add_space(4.0); - // The rows of a grid by column; one row or column has no count to set. - let label = if layout == ArtboardLayout::GridByColumn { tl!("Rows:") } else { tl!("Columns:") }; - widgets::label_row(ui, label, LABEL_W, |ui| { - let grid = matches!(layout, ArtboardLayout::GridByRow | ArtboardLayout::GridByColumn); - ui.add_enabled_ui(grid, |ui| { - let most = n.max(1) as f64; - if let Some(v) = widgets::spin_plain(ui, "rearrange-columns", d.f64("columns", 2.0), "", 0, 76.0, 1.0, 1.0, &[]) { - d.fields.insert("columns".into(), json!(v.round().clamp(1.0, most))); - } - }); - }); - ui.add_space(4.0); - widgets::label_row(ui, tl!("Spacing:"), LABEL_W, |ui| { - form::length(ui, d, "spacing", unit, 100.0); - }); - ui.add_space(4.0); - widgets::label_row(ui, tl!("Options:"), LABEL_W, |ui| { - form::check(ui, d, "moveArtwork", tl!("Move Artwork with Artboard")); - }); - ui.add_space(8.0); - widgets::dim_label(ui, &crate::i18n::fmt(tl!("Artboards: {n}"), &[("n", &n.to_string())])); - false + let path: Vec = tiles.iter().map(centre).collect(); + if let ([first, ..], [.., from, to]) = (path.as_slice(), path.as_slice()) { + let (first, from, to) = (*first, *from, *to); + let dir = (to - from).normalized(); + let wing = dir.rot90() * 2.5 * scale; + let head = vec![to + dir * 1.5 * scale, to - dir * 2.5 * scale + wing, to - dir * 2.5 * scale - wing]; + painter.circle_filled(first, 1.6 * scale, color); + painter.add(Shape::line(path, Stroke::new(1.2 * scale, color))); + painter.add(Shape::convex_polygon(head, color, Stroke::NONE)); + } + } } -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let result = run_and_close(app, CMD, params(d))?; - app.ui.rearrange_artboards_spacing = json!(d.f64("spacing", 20.0)); - Ok(result) +static GRID_BY_ROW: CellsGlyph = CellsGlyph(&[(0, 0), (1, 0), (0, 1), (1, 1)]); +static GRID_BY_ROW_RTL: CellsGlyph = CellsGlyph(&[(1, 0), (0, 0), (1, 1), (0, 1)]); +static GRID_BY_COLUMN: CellsGlyph = CellsGlyph(&[(0, 0), (0, 1), (1, 0), (1, 1)]); +static GRID_BY_COLUMN_RTL: CellsGlyph = CellsGlyph(&[(1, 0), (1, 1), (0, 0), (0, 1)]); +static ROW: CellsGlyph = CellsGlyph(&[(0, 0), (1, 0), (2, 0)]); +static ROW_RTL: CellsGlyph = CellsGlyph(&[(2, 0), (1, 0), (0, 0)]); +/// One column reads the same either way. +static COLUMN: CellsGlyph = CellsGlyph(&[(0, 0), (0, 1), (0, 2)]); +static LEFT_TO_RIGHT: CellsGlyph = CellsGlyph(&[(0, 0), (1, 0)]); +static RIGHT_TO_LEFT: CellsGlyph = CellsGlyph(&[(1, 0), (0, 0)]); + +/// A layout's toggle: its tooltip and its picture in the order the toggles preview (`rtl`: right to left). +fn layout_glyph(l: ArtboardLayout, rtl: bool) -> (&'static str, &'static CellsGlyph) { + match (l, rtl) { + (ArtboardLayout::GridByRow, false) => (tl!("Grid by Row"), &GRID_BY_ROW), + (ArtboardLayout::GridByRow, true) => (tl!("Grid by Row"), &GRID_BY_ROW_RTL), + (ArtboardLayout::GridByColumn, false) => (tl!("Grid by Column"), &GRID_BY_COLUMN), + (ArtboardLayout::GridByColumn, true) => (tl!("Grid by Column"), &GRID_BY_COLUMN_RTL), + (ArtboardLayout::Row, false) => (tl!("Arrange by Row"), &ROW), + (ArtboardLayout::Row, true) => (tl!("Arrange by Row"), &ROW_RTL), + (ArtboardLayout::Column, _) => (tl!("Arrange by Column"), &COLUMN), + } +} + +/// The settings the dialog edits. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct RearrangeValues { + layout: ArtboardLayout, + /// Layout Order is right to left. + rtl: bool, + columns: f64, + spacing: f64, + move_artwork: bool, +} + +impl Default for RearrangeValues { + fn default() -> Self { + RearrangeValues { layout: ArtboardLayout::GridByRow, rtl: false, columns: 2.0, spacing: 20.0, move_artwork: true } + } +} + +impl RearrangeValues { + /// `artboard.rearrange` parameters. + fn params(&self) -> Value { + json!({ + "layout": self.layout.id(), "order": self.order(), "columns": self.columns, + "spacing": self.spacing, "moveArtwork": self.move_artwork, + }) + } + + fn order(&self) -> &'static str { + if self.rtl { "rightToLeft" } else { "leftToRight" } + } + + /// A grid has a count to set; one row or column has none. + fn is_grid(&self) -> bool { + matches!(self.layout, ArtboardLayout::GridByRow | ArtboardLayout::GridByColumn) + } + + /// One column reads the same either way, so its order is not a choice. + fn has_order(&self) -> bool { + self.layout != ArtboardLayout::Column + } +} + +/// The length unit a document unit shows as. +fn length_kind(unit: Unit) -> UnitKind { + match unit { + Unit::Picas => UnitKind::Picas, + Unit::Inches => UnitKind::Inches, + Unit::Millimeters => UnitKind::Millimetres, + Unit::Centimeters => UnitKind::Centimetres, + Unit::Pixels => UnitKind::Pixels, + Unit::Meters => UnitKind::Metres, + Unit::Yards => UnitKind::Yards, + Unit::Feet | Unit::FeetInches => UnitKind::Feet, + _ => UnitKind::Points, + } +} + +/// `ui.menuDialog` for Rearrange All Artboards: opens the dialog on the spacing of its last OK. +pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + let mut values = RearrangeValues::default(); + if let Some(spacing) = app.ui.rearrange_artboards_spacing.as_f64() { + values.spacing = spacing; + } + let artboards = app.session.active().map_or(0, |doc| doc.doc.artboards.len()); + let unit = app.session.general_unit(); + let dialogs = app.dialogs().ok_or("no window")?; + dialogs.with(|host| host.open(RearrangeArtboardsDialog { id: dialog_id(CMD), open: true, values, artboards, unit })); + Ok(Value::Null) +} + +/// The Rearrange All Artboards dialog; its answer is the settings OK confirmed, which [`pump`] runs. +pub(crate) struct RearrangeArtboardsDialog { + id: DialogId, + open: bool, + values: RearrangeValues, + /// The document's artboard count, which bounds Columns. + artboards: usize, + /// The unit Spacing shows in. + unit: Unit, +} + +/// The rows of the dialog for a document of `artboards` artboards, Spacing shown in `unit`. +fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, unit: Unit) { + Field::new(tl!("Layout:")).id_salt("layout").show(ui, |ui, _| { + let entries: Vec> = ArtboardLayout::ALL + .into_iter() + .map(|l| { + let (tip, glyph) = layout_glyph(l, v.rtl); + Entry::new(l, tip).icon(IconSpec::glyph(glyph)) + }) + .collect(); + if let Some(l) = Segmented::new(tl!("Layout:"), Bind::given(v.layout), &entries).show(ui).value().copied() { + v.layout = l; + } + }); + Field::new(tl!("Layout Order:")).id_salt("order").enabled(v.has_order()).show(ui, |ui, _| { + let entries = [ + Entry::new(false, tl!("Change to Left-to-Right Layout")).icon(IconSpec::glyph(&LEFT_TO_RIGHT)), + Entry::new(true, tl!("Change to Right-to-Left Layout")).icon(IconSpec::glyph(&RIGHT_TO_LEFT)), + ]; + if let Some(rtl) = Segmented::new(tl!("Layout Order:"), Bind::given(v.rtl), &entries).show(ui).value().copied() { + v.rtl = rtl; + } + }); + // The rows of a grid by column. + let count = if v.layout == ArtboardLayout::GridByColumn { tl!("Rows:") } else { tl!("Columns:") }; + Field::new(count).id_salt("columns").enabled(v.is_grid()).show(ui, |ui, _| { + let most = artboards.max(1) as f64; + let field = NumberField::new(count, Bind::given(Some(v.columns))).range(1.0..=most).step(1.0).show(ui); + if let Some(Some(columns)) = field.edit.value().copied() { + v.columns = columns.round().clamp(1.0, most); + } + }); + Field::new(tl!("Spacing:")).id_salt("spacing").show(ui, |ui, _| { + let units = LengthUnits::new(UnitKind::Points, length_kind(unit), 72.0); + let field = NumberField::length(tl!("Spacing:"), Bind::given(Some(v.spacing)), units).show(ui); + if let Some(Some(spacing)) = field.edit.value().copied() { + v.spacing = spacing; + } + }); + Field::new(tl!("Options:")).id_salt("options").show(ui, |ui, _| { + if let Some(on) = check(ui, tl!("Move Artwork with Artboard"), v.move_artwork, true) { + v.move_artwork = on; + } + }); + Text::new(crate::i18n::fmt(tl!("Artboards: {n}"), &[("n", &artboards.to_string())])).role(TypeRole::Caption).show(ui); +} + +impl StackDialog for RearrangeArtboardsDialog { + type Result = RearrangeValues; + + fn id(&self) -> DialogId { + self.id + } + + fn key(&self) -> Option<&str> { + Some(CMD) + } + + fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option> { + let (artboards, unit) = (self.artboards, self.unit); + let shown = FormDialog::new(tl!("Rearrange All Artboards"), Bind::bound(&mut self.values)).opened(Bind::bound(&mut self.open)).show( + ui, + |ui, _, v| { + body(ui, v, artboards, unit); + true + }, + ); + match (shown.accepted, shown.closed) { + (Some(value), _) => Some(DialogResult::Ok(value)), + (None, Some(_)) => Some(DialogResult::Cancel), + (None, None) => None, + } + } + + fn confirm(&mut self, _: &egui::Context) -> Option { + Some(self.values.clone()) + } + + fn json_fields(&self) -> Option { + let v = &self.values; + Some(json!({"layout": v.layout.id(), "order": v.order(), "columns": v.columns, "spacing": v.spacing, "moveArtwork": v.move_artwork})) + } + + fn set_json_field(&mut self, _: &egui::Context, field: &str, value: Value) -> Result<(), String> { + let rejects = || FieldRefusal::Rejects(&value).message(field); + let inactive = || FieldRefusal::Inactive.message(field); + let v = &mut self.values; + match field { + "layout" => v.layout = value.as_str().and_then(ArtboardLayout::parse).ok_or_else(rejects)?, + "order" => { + let rtl = match value.as_str() { + Some("leftToRight") => false, + Some("rightToLeft") => true, + _ => return Err(rejects()), + }; + if !v.has_order() { + return Err(inactive()); + } + v.rtl = rtl; + } + "columns" => { + let columns = value.as_f64().filter(|c| c.is_finite()).ok_or_else(rejects)?; + if !v.is_grid() { + return Err(inactive()); + } + v.columns = columns.round().clamp(1.0, self.artboards.max(1) as f64); + } + "spacing" => v.spacing = value.as_f64().filter(|s| s.is_finite()).ok_or_else(rejects)?, + "moveArtwork" => v.move_artwork = value.as_bool().ok_or_else(rejects)?, + _ => return Err(FieldRefusal::Unknown.message(field)), + } + Ok(()) + } +} + +/// Runs `artboard.rearrange` for the settings OK confirmed, and remembers the spacing of a successful one. +pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(dialogs) = app.dialogs() else { return }; + let Some(DialogResult::Ok(values)) = dialogs.with(|host| host.take::()) else { return }; + match app.run(CMD, values.params()) { + Ok(_) => app.ui.rearrange_artboards_spacing = json!(values.spacing), + Err(e) => app.status(e), + } + ctx.request_repaint(); } #[cfg(test)] @@ -129,104 +293,80 @@ mod tests { use super::*; use vectorcraft_engine::Session; - /// A frame of the open dialog with `events` → the texts painted. The dialog measures itself on - /// its first frame, so a fresh context needs two. - fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { - let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); - out.textures_delta.clear(); - out.shapes.iter().filter_map(|s| if let egui::epaint::Shape::Text(t) = &s.shape { Some(t.galley.text().to_string()) } else { None }).collect() - } - - fn context() -> egui::Context { - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - ctx + fn app(artboards: u32) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(egui::Context::default()); + app.run("file.new", json!({"width": 100, "height": 50, "artboards": artboards})).unwrap(); + app } fn origins(app: &VectorcraftApp) -> Vec<(f64, f64)> { app.session.active().unwrap().doc.artboards.iter().map(|a| (a.rect.x0, a.rect.y0)).collect() } - /// #681: the menu item opens the dialog with the artboard count; Columns reads Rows for a grid - /// by column; OK lays the artboards out right to left, as one undo step. - #[test] - fn opens_from_the_menu_and_rearranges_by_layout_and_order() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); - // The menu item has no params of its own: it opens this dialog, not the generic one. + /// Opens the dialog as the menu item does. + fn open_from_menu(app: &mut VectorcraftApp) { let (id, p) = crate::menus::click_target("Rearrange All Artboards…", CMD, &Value::Null); - crate::menus::invoke(&mut app, &id, p); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); - let ctx = context(); - frame(&mut app, &ctx, vec![]); - let texts = frame(&mut app, &ctx, vec![]); - for want in ["Rearrange All Artboards", "Layout:", "Layout Order:", "Columns:", "Spacing:", "Move Artwork with Artboard", "Artboards: 3"] { - assert!(texts.iter().any(|t| t == want), "{want:?} in {texts:?}"); + crate::menus::invoke(app, &id, p); + } + + fn open_id(app: &VectorcraftApp) -> DialogId { + app.dialogs().unwrap().with(|host| host.open_dialogs().last().map(|d| d.id)).unwrap() + } + + /// Sets `edits` in the open dialog in order; the first refusal is returned. + fn set(app: &VectorcraftApp, edits: &[(&str, Value)]) -> Result<(), String> { + let (ctx, id) = (app.ui_ctx.clone().unwrap(), open_id(app)); + edits.iter().try_for_each(|(field, value)| app.dialogs().unwrap().with(|host| host.set_json_field(&ctx, id, field, value.clone()))) + } + + /// Presses OK and runs the host pump, which runs the command. + fn ok(app: &mut VectorcraftApp) { + let (ctx, id) = (app.ui_ctx.clone().unwrap(), open_id(app)); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(app, &ctx); + } + + /// #681: the menu item opens the dialog; each setting reaches `artboard.rearrange`, as one undo step; a + /// setting the layout makes meaningless is refused. + #[test] + fn rearrange_fields_reach_the_command() { + let cases: [(u32, &[(&str, Value)], &[(f64, f64)]); 2] = [ + (3, &[("layout", json!("row")), ("order", json!("rightToLeft")), ("spacing", json!(10))], &[(220.0, 0.0), (110.0, 0.0), (0.0, 0.0)]), + ( + 4, + &[("layout", json!("gridByColumn")), ("order", json!("rightToLeft")), ("columns", json!(2))], + &[(120.0, 0.0), (120.0, 70.0), (0.0, 0.0), (0.0, 70.0)], + ), + ]; + for (artboards, edits, want) in cases { + let mut app = app(artboards); + open_from_menu(&mut app); + set(&app, edits).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + ok(&mut app); + assert!(!app.any_dialog_open()); + assert_eq!(origins(&app), want); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); } - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("layout".into(), json!("gridByColumn")); - let texts = frame(&mut app, &ctx, vec![]); - assert!(texts.iter().any(|t| t == "Rows:") && !texts.iter().any(|t| t == "Columns:"), "{texts:?}"); - // One row, right to left, 10 pt apart. - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("layout".into(), json!("row")); - d.fields.insert("order".into(), json!("rightToLeft")); - d.fields.insert("spacing".into(), json!(10)); - frame(&mut app, &ctx, vec![]); - let undo = app.session.doc().unwrap().history.undo.len(); - crate::dialogs::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); - assert_eq!(origins(&app), [(220.0, 0.0), (110.0, 0.0), (0.0, 0.0)]); - assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + let mut app = app(3); + open_from_menu(&mut app); + assert!(set(&app, &[("layout", json!("column")), ("order", json!("rightToLeft"))]).is_err(), "one column has no order"); + assert!(set(&app, &[("layout", json!("column")), ("columns", json!(2))]).is_err(), "one column has no count"); + assert!(set(&app, &[("layout", json!("row")), ("columns", json!(2))]).is_err(), "one row has no count"); + assert!(set(&app, &[("layout", json!("gridByRow")), ("columns", json!(2))]).is_ok()); } /// The spacing confirmed last is the one the dialog opens with next time (#4558). #[test] fn keeps_spacing_when_reopening_after_rearranging() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); + let mut app = app(3); app.run("ui.menuDialog", json!({"command": CMD})).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("spacing".into(), json!(37)); - crate::dialogs::confirm(&mut app).unwrap(); + set(&app, &[("spacing", json!(37))]).unwrap(); + ok(&mut app); app.run("ui.menuDialog", json!({"command": CMD})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().f64("spacing", 20.0), 37.0); - } - - /// Clicking the layout and order toggles sets the fields (the toggles' rects from the frame). - #[test] - fn the_toggles_set_layout_and_order() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.run("file.new", json!({"width": 100, "height": 50, "artboards": 4})).unwrap(); - app.run("ui.menuDialog", json!({ "command": CMD })).unwrap(); - let ctx = context(); - frame(&mut app, &ctx, vec![]); - frame(&mut app, &ctx, vec![]); - // The 26-point toggles, left to right then top to bottom: four layouts, then two orders. - let toggles: Vec = ctx.viewport(|vp| { - let mut r: Vec = vp - .prev_pass - .widgets - .layers() - .flat_map(|(_, w)| w.iter()) - .filter(|w| w.sense.senses_click() && w.rect.width() == 26.0 && w.rect.height() == 26.0) - .map(|w| w.rect) - .collect(); - r.sort_by(|a, b| a.top().total_cmp(&b.top()).then(a.left().total_cmp(&b.left()))); - r - }); - assert_eq!(toggles.len(), 6, "{toggles:?}"); - for (i, key, want) in [(3, "layout", "column"), (1, "layout", "gridByColumn"), (5, "order", "rightToLeft")] { - let at = toggles[i].center(); - let b = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), b(true)]); - frame(&mut app, &ctx, vec![b(false)]); - assert_eq!(app.ui.dialog.as_ref().unwrap().str(key), want); - // A frame for the order toggles to follow the layout (one column greys them). - frame(&mut app, &ctx, vec![]); - } - crate::dialogs::confirm(&mut app).unwrap(); - // Two rows (Columns 2 reads Rows for a grid by column), the first column at the right. - assert_eq!(origins(&app), [(120.0, 0.0), (120.0, 70.0), (0.0, 0.0), (0.0, 70.0)]); + let fields = app.dialogs().unwrap().with(|host| host.open_dialogs().last().and_then(|d| d.fields.clone())).unwrap(); + assert_eq!(fields["spacing"].as_f64(), Some(37.0)); } } diff --git a/crates/ui-egui/src/dialogs/rename_artboards.rs b/crates/ui-egui/src/dialogs/rename_artboards.rs index bd621ebdbe..3873160c01 100644 --- a/crates/ui-egui/src/dialogs/rename_artboards.rs +++ b/crates/ui-egui/src/dialogs/rename_artboards.rs @@ -2,52 +2,50 @@ //! for the selected artboards. OK runs //! `artboard.rename` as one undo step; with several artboards the name is numbered. //! -//! Fields: `name` (the artboard's name with one artboard, empty with several) and `indices` (the -//! artboards the dialog opened on). +//! Fields: `name` (the artboard's name with one artboard, empty with several). The artboards the +//! dialog opened on are held by its OK. +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use serde_json::{Value, json}; -use super::{DialogResult, DialogSpec, form, run_and_close}; -use crate::state::Dialog; -use crate::{VectorcraftApp, widgets}; +use super::host::open_held; +use crate::VectorcraftApp; -/// The dialog kind of the artboard Rename dialog. -pub const KIND: &str = "renameArtboards"; +/// The command Rename answers for; the key of its dialog. +pub(crate) const CMD: &str = "artboard.rename"; -const CMD: &str = "artboard.rename"; - -pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Rename").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; - -/// The fields the menu item opens with, for the selected artboards. -pub fn open_fields(app: &VectorcraftApp) -> Value { - let Some(st) = app.session.active() else { return json!({"name": "", "indices": []}) }; - let indices = crate::panels::artboards::picked(app, st.doc.artboards.len()); - let name = match indices.as_slice() { - [one] => st.doc.artboards.get(*one).map_or("", |a| a.name.as_str()), - _ => "", - }; - json!({ "name": name, "indices": indices }) -} - -fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - widgets::label_row(ui, tl!("Name:"), 56.0, |ui| { - let r = form::text_edit_named(ui, d, "name", tl!("Name:"), 220.0); - if ui.memory(|m| m.focused().is_none()) { - r.request_focus(); - } +/// `artboard.rename` for the selected artboards: opens the dialog on the one artboard's name, or on an empty name +/// for several. +pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + let ctx = app.ui_ctx.clone().ok_or("no window")?; + let (indices, name) = app.session.active().map_or((vec![], String::new()), |st| { + let indices = crate::panels::artboards::picked(app, st.doc.artboards.len()); + let name = match indices.as_slice() { + [one] => st.doc.artboards.get(*one).map_or("", |a| a.name.as_str()), + _ => "", + }; + (indices, name.to_owned()) }); - false -} - -/// An empty name keeps the names as they are, as the Artboards panel's name field does. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { - let name = d.str("name"); - if name.trim().is_empty() { - app.ui.dialog = None; - return Ok(Value::Null); - } - let indices = d.fields.get("indices").cloned().unwrap_or(Value::Null); - run_and_close(app, CMD, json!({ "indices": indices, "name": name })) + let mut fields = DialogFields::new(); + fields.set("name", name); + let dialog = HostedParamDialog::command(&ctx, CMD, fields, |fields| { + let rows = vec![Param::new("name", tl!("Name:"), ParamKind::text(""))]; + ParamDialog::command(CMD, tl!("Rename"), rows).values(Bind::bound(fields)) + }); + let ok = move |app: &mut VectorcraftApp, result: &ParamResult| { + let name = result.fields.text("name").unwrap_or_default(); + // An empty name keeps the names as they are, as the Artboards panel's name field does. + if name.trim().is_empty() { + return Ok(()); + } + if let Err(e) = app.run(CMD, json!({ "indices": indices, "name": name })) { + app.status(e); + } + Ok(()) + }; + open_held(app, dialog, ok).ok_or("no window")?; + Ok(Value::Null) } #[cfg(test)] @@ -57,6 +55,7 @@ mod tests { fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(egui::Context::default()); app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); app.select_tool("artboard"); app @@ -66,24 +65,41 @@ mod tests { app.session.active().unwrap().doc.artboards.iter().map(|a| a.name.clone()).collect() } + /// The open Rename dialog: its id and fields. + fn open_rename(app: &VectorcraftApp) -> (craft::ui::dialog::DialogId, Value) { + let dialogs = app.dialogs().unwrap(); + let open = dialogs.with(|host| host.open_dialogs().into_iter().find(|d| d.key.as_deref() == Some(CMD))).unwrap(); + (open.id, open.fields.unwrap()) + } + + /// Sets `name` in the open dialog, presses OK and runs the host pump, which runs the held OK. + fn rename(app: &mut VectorcraftApp, name: &str) { + let ctx = app.ui_ctx.clone().unwrap(); + let (id, _) = open_rename(app); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.set_json_field(&ctx, id, "name", json!(name))).unwrap(); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(app, &ctx); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + } + /// With one artboard the field starts on its name; with several it starts empty, and OK numbers /// the name in one undo step. #[test] fn the_menu_item_renames_the_selected_artboards() { let mut app = app(); crate::menus::invoke(&mut app, CMD, json!({})); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.kind, KIND); - assert_eq!(d.str("name"), "Artboard 1"); - app.ui.dialog = None; + assert_eq!(open_rename(&app).1["name"], json!("Artboard 1")); + let ctx = app.ui_ctx.clone().unwrap(); + let (id, _) = open_rename(&app); + app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id)); app.session.set_tool_option("selected", &json!([2, 0])); crate::menus::invoke(&mut app, CMD, json!({})); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("name"), ""); - app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!(" Page ")); + assert_eq!(open_rename(&app).1["name"], json!("")); let steps = app.session.active().unwrap().history.undo.len(); - crate::dialogs::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + rename(&mut app, " Page "); + assert!(!app.any_dialog_open()); assert_eq!(names(&app), ["Page-1", "Artboard 2", "Page-2"]); assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step"); } @@ -95,9 +111,8 @@ mod tests { let steps = app.session.active().unwrap().history.undo.len(); for name in [" ", "Artboard 1"] { crate::menus::invoke(&mut app, CMD, json!({})); - app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!(name)); - crate::dialogs::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + rename(&mut app, name); + assert!(!app.any_dialog_open()); } assert_eq!(names(&app), ["Artboard 1", "Artboard 2", "Artboard 3"]); assert_eq!(app.session.active().unwrap().history.undo.len(), steps);