diff --git a/crates/ui-egui/src/dialogs/dxf_options.rs b/crates/ui-egui/src/dialogs/dxf_options.rs index 2e0aefc54c..85edcd2254 100644 --- a/crates/ui-egui/src/dialogs/dxf_options.rs +++ b/crates/ui-egui/src/dialogs/dxf_options.rs @@ -8,36 +8,26 @@ //! options of `document.exportDxf`. OK remembers the options for next time and writes the file //! (asking where when there is no path); bad options keep the dialog open. +use craft_ui::contract::{Bind, Entry, Show as _}; +use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft_ui::pickers::Select; +use craft_ui::text::NumberField; use serde_json::{Map, Value, json}; use vectorcraft_cad::{ColorDepth, DxfPreset, DxfVersion, Preserve, RasterFormat}; use vectorcraft_doc::Unit; use vectorcraft_engine::cmd::fileio; -use super::DialogSpec; -use super::document_setup::{LABEL, check, choice}; -use crate::state::Dialog; -use crate::{VectorcraftApp, io, widgets}; +use super::export_host::{self, After, Export, Open}; +use super::form; +use crate::{VectorcraftApp, io}; pub(super) const KIND: &str = "dxfOptions"; -pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |_| tl!("DXF Options").into(), - body, - confirm, - ok: Some("Export"), - min_width: 420.0, - max_width: Some(460.0), - inputs: |_| &["path"], - ..DialogSpec::FORM -}; - /// Fields that are not remembered between exports (they belong to one export). const PER_EXPORT: [&str; 7] = ["format", "path", "useArtboards", "range", "artboard", "artboards", "selectedOnly"]; /// The preset field (the `dxfPreset` param). const PRESET: &str = "dxfPreset"; -/// The preset the fields were last set from or matched (a change of [`PRESET`] sets its fields). -const SHOWN_PRESET: &str = "__shownPreset"; /// The options a first DXF Options dialog starts from (the export's defaults). fn defaults() -> Map { @@ -69,41 +59,127 @@ fn preset_fields(preset: DxfPreset) -> Map { m } -/// Show the preset the fields match: CNC / CAM while every field it sets is as it sets it, else -/// Custom. An unknown preset stays as it is, for OK to refuse. -fn show_matching_preset(d: &mut Dialog) { - if DxfPreset::from_id(&d.str(PRESET)).is_none() { - return; - } - let preset = fileio::dxf::options(&super::form::params(d)).map_or(DxfPreset::Custom, |o| DxfPreset::of(&o)); - d.fields.insert(PRESET.into(), json!(preset.id())); - d.fields.insert(SHOWN_PRESET.into(), json!(preset.id())); +/// `map` as the dialog's values. +fn dialog_fields(map: &Map) -> DialogFields { + form::fields_of(&kinds(), map) } -/// A preset picked since the fields were last matched, or any preset when `force` is set, sets -/// its fields; Custom puts back the export's defaults. -fn apply_picked_preset(d: &mut Dialog, force: bool) { - if (force || !d.str(PRESET).eq_ignore_ascii_case(&d.str(SHOWN_PRESET))) - && let Some(p) = DxfPreset::from_id(&d.str(PRESET)) - { - d.fields.extend(preset_fields(p)); - } +/// The rows as far as their kinds go, for reading values to and from JSON. +fn kinds() -> Vec { + params(false, false, false) } -/// `field` was set (`ui.dialog.set`): a preset sets its fields now, even the one shown, so fields -/// set after it keep their values, and any other field shows the preset the fields then match, as -/// drawing does. -pub(super) fn note_set(d: &mut Dialog, field: &str) { - if field == PRESET { - apply_picked_preset(d, true); +/// Gives the dialog the fields the current preset sets and the others have lost (a change of the preset row removes +/// them), then shows the preset the fields match: CNC / CAM while every field it sets is as it sets it, else Custom. +/// An unknown preset stays as it is, for OK to refuse. +fn settle(fields: &mut DialogFields) { + let Some(preset) = fields.text(PRESET).and_then(DxfPreset::from_id) else { return }; + for (key, value) in dialog_fields(&preset_fields(preset)).iter() { + if !fields.contains(key) { + fields.set(key, value.clone()); + } + } + let shown = fileio::dxf::options(&Value::Object(form::json_of(&kinds(), fields))).map_or(DxfPreset::Custom, |o| DxfPreset::of(&o)); + fields.set(PRESET, shown.id()); +} + +/// A choice row over `rows` (id, label). +pub(super) fn choice_param<'a>(key: &str, label: &str, rows: impl IntoIterator) -> Param { + let options = rows.into_iter().map(|(id, name)| (id.to_string(), tl!(name).into())).collect(); + Param::new(key, label, ParamKind::choice(options, None)) +} + +/// A radio row over `rows` (id, label). +pub(super) fn radio_param<'a>(key: &str, label: &str, rows: impl IntoIterator) -> Param { + let options = rows.into_iter().map(|(id, name)| (id.to_string(), tl!(name).into())).collect(); + Param::new(key, label, ParamKind::radio(options, None)) +} + +/// A check box row. +pub(super) fn check_param(key: &str, label: &str) -> Param { + Param::new(key, label, ParamKind::bool(false)) +} + +/// The rows. Export Selection leaves Export Selected Art Only out, as it writes the selected art alone; +/// without a selection that row is off. `note` shows the true-colour note. +fn params(selection: bool, has_selection: bool, note: bool) -> Vec { + let keys: Vec = preset_fields(DxfPreset::Custom).keys().cloned().collect(); + let mut rows = vec![ + choice_param(PRESET, tl!("Preset:"), DxfPreset::ALL.iter().map(|p| (p.id(), p.label()))).resets(keys), + choice_param("version", tl!("Version:"), DxfVersion::ALL.iter().map(|v| (v.id(), v.label()))), + scale_param(None), + check_param("scaleLineweights", tl!("Scale Lineweights")), + choice_param("colors", tl!("Number of Colors:"), ColorDepth::ALL.iter().map(|c| (c.id(), c.label()))), + ]; + if note { + rows.push(Param::read_only_text( + "__colorNote", + "", + tl!("True colour needs version 2004 or later: the nearest of 256 colours is written."), + )); + } + rows.extend([ + choice_param("rasterFormat", tl!("Raster File Format:"), RasterFormat::ALL.iter().map(|r| (r.id(), r.label()))), + check_param("includeImages", tl!("Include Placed Images")), + Param::section(tl!("Export Option")), + radio_param("preserve", "", Preserve::ALL.iter().map(|p| (p.id(), p.label()))), + ]); + if !selection { + let row = check_param("selectedOnly", tl!("Export Selected Art Only")); + rows.push(if has_selection { row } else { row.enabled_when_in("selectedOnly", std::iter::empty::()) }); + } + rows.extend([ + check_param("alterPaths", tl!("Alter Paths for Appearance")), + // Preserve Appearance always outlines type. + check_param("outlineText", tl!("Outline Text")).enabled_when("preserve", FieldValue::Text(Preserve::Editability.id().into())), + check_param("includeHatches", tl!("Include Fill Hatches")), + ]); + rows +} + +/// Scale: 1 [unit] = [scale] Units (the `unit` and `scale` fields; DXF import reads them too). The row is disabled +/// while the check box `disabled_when` names holds the value it gives. +pub(crate) fn scale_param(disabled_when: Option<(&str, FieldValue)>) -> Param { + let row = Param::custom("scale", tl!("Scale:"), |ui, fields, _| { + let units: Vec> = + Unit::ALL.iter().filter(|u| **u != Unit::FeetInches).map(|u| Entry::new(u.label().to_string(), u.label())).collect(); + let mut unit = fields.text("unit").map_or_else(|| Unit::Millimeters.label().to_string(), str::to_string); + let mut scale = Some(fields.number("scale").unwrap_or(1.0)); + let (lo, hi) = (*vectorcraft_cad::SCALE_RANGE.start(), *vectorcraft_cad::SCALE_RANGE.end()); + let shown = ui + .horizontal(|ui| { + ui.label("1"); + Select::new(tl!("Unit"), Bind::bound(&mut unit), &units).show(ui); + ui.label("="); + NumberField::new(tl!("Scale"), Bind::bound(&mut scale)).range(lo..=hi).show(ui); + ui.label(tl!("Units")); + }) + .response; + let scale = scale.unwrap_or(1.0); + if fields.text("unit") != Some(unit.as_str()) { + fields.set("unit", unit); + } + if fields.number("scale") != Some(scale) { + fields.set("scale", scale); + } + shown + }) + .companions(["unit"]); + match disabled_when { + Some((key, FieldValue::Bool(v))) => row.enabled_when(key, FieldValue::Bool(!v)), + _ => row, } - show_matching_preset(d); } /// Open DXF Options for an export whose params (path, artboard choice, any DXF option) are /// `params`, over the options used last. A `dxfPreset` in `params` sets its fields under the /// options `params` gives. pub fn open(app: &mut VectorcraftApp, params: &Value) { + open_with(app, params, false); +} + +/// [`open`] for Export Selection when `selection` is set: the options then write the selected art alone. +pub fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) { let mut fields = defaults(); if let Some(o) = app.ui.dxf_options.as_object() { fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))); @@ -115,120 +191,44 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) { fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))); } fields.insert("format".into(), json!("dxf")); - let mut d = Dialog::new(KIND, Value::Object(fields)); - show_matching_preset(&mut d); - app.ui.dialog = Some(d); -} - -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let presets: Vec<(&str, &str)> = DxfPreset::ALL.iter().map(|p| (p.id(), p.label())).collect(); - choice(ui, d, PRESET, tl!("Preset:"), &presets); - apply_picked_preset(d, false); - ui.add_space(4.0); - let versions: Vec<(&str, &str)> = DxfVersion::ALL.iter().map(|v| (v.id(), v.label())).collect(); - choice(ui, d, "version", tl!("Version:"), &versions); - ui.add_space(4.0); - scale_row(ui, d); - ui.horizontal(|ui| { - ui.add_space(LABEL + 8.0); - check(ui, d, "scaleLineweights", tl!("Scale Lineweights")); - }); - ui.add_space(4.0); - let depths: Vec<(&str, &str)> = ColorDepth::ALL.iter().map(|c| (c.id(), c.label())).collect(); - choice(ui, d, "colors", tl!("Number of Colors:"), &depths); - let version = DxfVersion::from_id(&d.str("version")).unwrap_or_default(); - if ColorDepth::from_id(&d.str("colors")) == Some(ColorDepth::True) && version < DxfVersion::R2004 { - note(ui, tl!("True colour needs version 2004 or later: the nearest of 256 colours is written.")); - } - let rasters: Vec<(&str, &str)> = RasterFormat::ALL.iter().map(|r| (r.id(), r.label())).collect(); - choice(ui, d, "rasterFormat", tl!("Raster File Format:"), &rasters); - ui.horizontal(|ui| { - ui.add_space(LABEL + 8.0); - check(ui, d, "includeImages", tl!("Include Placed Images")); - }); - ui.add_space(10.0); - widgets::subheader(ui, tl!("Export Option")); - let preserve = Preserve::from_id(&d.str("preserve")).unwrap_or_default(); - ui.horizontal(|ui| { - for p in Preserve::ALL { - if widgets::radio(ui, p.label(), p == preserve, true) { - d.fields.insert("preserve".into(), json!(p.id())); - } - ui.add_space(12.0); - } - }); - ui.add_space(4.0); - // Hidden for Export Selection, which writes the selected art alone. - let selection = app.session.active().is_some_and(|st| !st.selection.is_empty()); - if !d.bool(super::export_as::SELECTION_FIELD) - && widgets::check(ui, tl!("Export Selected Art Only"), d.bool("selectedOnly") && selection, selection) - { - d.fields.insert("selectedOnly".into(), json!(!d.bool("selectedOnly"))); - } - check(ui, d, "alterPaths", tl!("Alter Paths for Appearance")); - // Preserve Appearance always outlines type. - let appearance = preserve == Preserve::Appearance; - if widgets::check(ui, tl!("Outline Text"), appearance || d.bool("outlineText"), !appearance) { - d.fields.insert("outlineText".into(), json!(!d.bool("outlineText"))); - } - check(ui, d, "includeHatches", tl!("Include Fill Hatches")); - ui.add_space(8.0); - super::form::caption( - ui, - match preserve { - Preserve::Appearance => tl!("Type becomes outlines, and strokes a CAD line can't draw become filled shapes."), - Preserve::Editability => tl!("Type stays text, and every stroke is a line with its lineweight and dashes."), - }, - ); - show_matching_preset(d); - false -} - -/// Scale: 1 [unit] = [scale] Units (the `unit` and `scale` fields; DXF import reads them too). -pub(super) fn scale_row(ui: &mut egui::Ui, d: &mut Dialog) { - let t = crate::theme::Tokens::get(ui.ctx()); - let units: Vec<&str> = Unit::ALL.iter().filter(|u| **u != Unit::FeetInches).map(|u| u.label()).collect(); - let unit = Unit::named(&d.str("unit")).unwrap_or(Unit::Millimeters); - widgets::label_row(ui, tl!("Scale:"), LABEL, |ui| { - ui.label(egui::RichText::new("1").color(t.text)); - if let Some(u) = widgets::dropdown(ui, "dxf-unit", unit.label(), &units, 120.0).and_then(|i| units.get(i)) { - d.fields.insert("unit".into(), json!(u)); - } - ui.label(egui::RichText::new("=").color(t.text)); - let scale = d.f64("scale", 1.0); - if let Some(v) = widgets::plain_field(ui, "dxf-scale", scale, "", 3, 64.0) { - let (lo, hi) = (*vectorcraft_cad::SCALE_RANGE.start(), *vectorcraft_cad::SCALE_RANGE.end()); - d.fields.insert("scale".into(), json!(v.clamp(lo, hi))); - } - ui.label(egui::RichText::new(tl!("Units")).color(t.text)); - }); -} - -/// A dim line under a field. -fn note(ui: &mut egui::Ui, text: &str) { - ui.horizontal(|ui| { - ui.add_space(LABEL + 8.0); - super::form::caption(ui, text); + let mut values = dialog_fields(&fields); + settle(&mut values); + let has_selection = app.session.active().is_some_and(|st| !st.selection.is_empty()); + // PLAN: assumed `app.ui_ctx: Option` is set whenever a window is shown. + let ctx = app.ui_ctx.clone().unwrap_or_default(); + let dialog = HostedParamDialog::new(&ctx, KIND, values, move |fields| { + settle(fields); + let note = fields.text("colors").and_then(ColorDepth::from_id) == Some(ColorDepth::True) + && fields.text("version").and_then(DxfVersion::from_id).unwrap_or_default() < DxfVersion::R2004; + ParamDialog::new(KIND, tl!("DXF Options"), params(selection, has_selection, note)) + .values(Bind::bound(fields)) + // PLAN: assumed `ok_label` takes a `Label`. + .ok_label(tl!("Export").into()) + .below(|ui, fields| { + ui.weak(match fields.text("preserve").and_then(Preserve::from_id).unwrap_or_default() { + Preserve::Appearance => tl!("Type becomes outlines, and strokes a CAD line can't draw become filled shapes."), + Preserve::Editability => tl!("Type stays text, and every stroke is a line with its lineweight and dashes."), + }); + }) }); + export_host::open(app, Export::Dxf, selection, dialog); } /// Check the options, remember them, and write the file(s). -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { +pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result { // A preset or field set since the dialog last drew (the control channel sets fields without // drawing) counts as drawn. - let mut d = d.clone(); - apply_picked_preset(&mut d, false); - show_matching_preset(&mut d); - let d = &d; - let params = super::form::params(d); + let mut fields = fields.clone(); + settle(&mut fields); + let map = form::json_of(¶ms(open.selection, true, false), &fields); + let params = Value::Object(map.clone()); fileio::dxf::check(¶ms)?; // Nothing selected keeps the dialog open too. if let Some(st) = app.session.active() { fileio::export_source(st, ¶ms).map_err(|e| e.to_string())?; } - let remembered = params.as_object().map(|o| o.iter().filter(|(k, _)| !PER_EXPORT.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone()))); - app.ui.dxf_options = Value::Object(remembered.into_iter().flatten().collect()); - app.ui.dialog = None; - let path = d.fields.get("path").and_then(Value::as_str).map(str::to_string); - io::export(app, Some("dxf"), path, &super::export_as::exported(d, params)) + app.ui.dxf_options = Value::Object(map.into_iter().filter(|(k, _)| !PER_EXPORT.contains(&k.as_str())).collect()); + let path = fields.text("path").map(str::to_string); + // PLAN: assumed `After` is an `Option` of the step to run once the dialog closed. + io::export(app, Some("dxf"), path, &super::export_as::exported(open.selection, params)).map(|_| None) } diff --git a/crates/ui-egui/src/dialogs/eps_options.rs b/crates/ui-egui/src/dialogs/eps_options.rs index 40c5f728f9..ab691ce523 100644 --- a/crates/ui-egui/src/dialogs/eps_options.rs +++ b/crates/ui-egui/src/dialogs/eps_options.rs @@ -12,42 +12,33 @@ //! goes back to EPS Options; Cancel goes back with the options as they were. Choosing a preset //! drops the custom options. +use std::sync::Arc; + +use craft_ui::buttons::Button; +use craft_ui::contract::{Bind, Show as _, TooltipSpec}; +use craft_ui::dialog::DialogId; +use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft_ui::patterns::presets::PresetRow; use serde_json::{Map, Value, json}; use vectorcraft_engine::cmd::{FlattenOptions, FlattenerPreset, fileio}; use vectorcraft_eps::{Level, Overprint, Preview}; -use super::DialogSpec; -use super::document_setup::{LABEL, check, choice}; -use crate::state::Dialog; -use crate::theme::Tokens; -use crate::{VectorcraftApp, io, widgets}; +use super::dxf_options::{check_param, choice_param}; +use super::export_host::{self, After, Export, Open}; +use super::{flatten, form}; +use crate::{VectorcraftApp, io}; pub(super) const KIND: &str = "epsOptions"; -pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |_| tl!("EPS Options").into(), - body, - confirm, - ok: Some("Export"), - min_width: 420.0, - max_width: Some(460.0), - inputs: |_| &["path", "flattener"], - ..DialogSpec::FORM -}; - /// Custom Transparency Flattener Options, opened over EPS Options by Custom…. pub(super) const CUSTOM_KIND: &str = "epsFlattenerOptions"; -pub(super) const CUSTOM_SPEC: DialogSpec = DialogSpec { - heading: |_| tl!("Custom Transparency Flattener Options").into(), - body: custom_body, - confirm: custom_confirm, - min_width: 420.0, - ..DialogSpec::FORM -}; +/// The flattener rows the format fixes, and why. +const FIXED: [&str; 2] = ["preserveAlpha", "preserveOverprints"]; +const FIXED_REASON: &str = "EPS has no alpha transparency, and Overprints sets whether overprints are kept."; /// Fields that are not remembered between exports (they belong to one export). -const PER_EXPORT: [&str; 8] = ["format", "path", "useArtboards", "range", "artboard", "artboards", "selectedOnly", super::export_as::SELECTION_FIELD]; +const PER_EXPORT: [&str; 7] = ["format", "path", "useArtboards", "range", "artboard", "artboards", "selectedOnly"]; /// The options a first EPS Options dialog starts from (the export's defaults). fn defaults() -> Map { @@ -69,9 +60,64 @@ fn defaults() -> Map { m } +/// The rows, with `presets` in the flattener picker. +fn params(presets: &Arc<[PresetRow]>) -> Vec { + let presets = Arc::clone(presets); + // PLAN: assumed ids "true" and "false" for the two-id radio that holds a JSON bool (wg.S12). + let transparency = Param::new( + "transparentPreview", + "", + ParamKind::radio(vec![("true".into(), tl!("Transparent").into()), ("false".into(), tl!("Opaque").into())], None), + ); + vec![ + Param::section(tl!("Preview")), + choice_param("previewFormat", tl!("Format:"), Preview::ALL.iter().map(|p| (p.id(), p.label()))), + // Only the colour preview can keep transparency. + transparency.enabled_when("previewFormat", FieldValue::Text(Preview::TiffColor.id().into())), + Param::section(tl!("Transparency")), + choice_param("overprints", tl!("Overprints:"), Overprint::ALL.iter().map(|o| (o.id(), o.label()))), + Param::custom("flattenerPreset", tl!("Preset:"), move |ui, fields, cx| { + ui.horizontal(|ui| { + let custom = fields.contains("flattener"); + flatten::preset_picker(ui, fields, "flattenerPreset", &presets, custom); + if Button::new(tl!("Custom…")).show(ui).clicks > 0 { + cx.request_action("custom"); + } + }) + .response + }) + .resets(["flattener"]), + Param::section(tl!("Fonts")), + // Type is written as glyph outlines, which need no fonts. + check_param("__embedFonts", tl!("Embed Fonts (for other applications)")) + .opens_with(true) + .enabled_when_in("__embedFonts", std::iter::empty::()) + .tooltip( + TooltipSpec::new(tl!("Type is written as glyph outlines, which need no fonts.")) + .disabled_text(tl!("Type is written as glyph outlines, which need no fonts.")), + ), + Param::section(tl!("Options")), + check_param("includeLinkedFiles", tl!("Include Linked Files")), + check_param("thumbnails", tl!("Include Document Thumbnails")), + check_param("cmykPostScript", tl!("Include CMYK PostScript in RGB Files")), + check_param("compatibleGradients", tl!("Compatible Gradient and Gradient Mesh Printing")), + choice_param("level", tl!("PostScript:"), Level::ALL.iter().map(|l| (l.id(), l.label()))), + ] +} + +/// The rows as far as their kinds go, for reading values to and from JSON. +fn kinds() -> Vec { + params(&Arc::from(Vec::new())) +} + /// Open EPS Options for an export whose params (path, artboard choice, any EPS option) are /// `params`, over the options used last. pub fn open(app: &mut VectorcraftApp, params: &Value) { + open_with(app, params, false); +} + +/// [`open`] for Export Selection when `selection` is set: the options then write the selected art alone. +pub fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) { let mut fields = defaults(); for given in [&app.ui.eps_options, params] { if let Some(o) = given.as_object() { @@ -83,159 +129,110 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) { fields.remove("flattener"); } fields.insert("format".into(), json!("eps")); - builtin_label(&mut fields); - app.ui.dialog = Some(Dialog::new(KIND, Value::Object(fields))); -} - -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - widgets::subheader(ui, tl!("Preview")); - let previews: Vec<(&str, &str)> = Preview::ALL.iter().map(|p| (p.id(), p.label())).collect(); - choice(ui, d, "previewFormat", tl!("Format:"), &previews); - // Only the colour preview can keep transparency. - let color = Preview::from_id(&d.str("previewFormat")) == Some(Preview::TiffColor); - let transparent = d.bool("transparentPreview"); - ui.horizontal(|ui| { - ui.add_space(LABEL + 8.0); - for (label, on) in [(tl!("Transparent"), true), (tl!("Opaque"), false)] { - if widgets::radio(ui, label, color && transparent == on, color) { - d.fields.insert("transparentPreview".into(), json!(on)); - } - ui.add_space(12.0); - } + let mut values = form::fields_of(&kinds(), &fields); + builtin_label(&mut values); + let (rows, _, _) = flatten::preset_rows(app); + let presets: Arc<[PresetRow]> = rows.into(); + // PLAN: assumed `app.ui_ctx: Option` is set whenever a window is shown. + let ctx = app.ui_ctx.clone().unwrap_or_default(); + let dialog = HostedParamDialog::new(&ctx, KIND, values, move |fields| { + builtin_label(fields); + normalise_level(fields); + ParamDialog::new(KIND, tl!("EPS Options"), params(&presets)) + .values(Bind::bound(fields)) + // PLAN: assumed `ok_label` takes a `Label`. + .ok_label(tl!("Export").into()) + .below(|ui, fields| { + ui.weak(if fields.text("level").and_then(Level::from_id) == Some(Level::Two) || fields.bool("compatibleGradients") == Some(true) { + tl!("Transparency is flattened with the preset. Type is written as outlines; gradients as bands of colour.") + } else { + tl!("Transparency is flattened with the preset. Type is written as outlines; gradients stay smooth.") + }); + }) }); - ui.add_space(8.0); - widgets::subheader(ui, tl!("Transparency")); - let overprints: Vec<(&str, &str)> = Overprint::ALL.iter().map(|o| (o.id(), o.label())).collect(); - choice(ui, d, "overprints", tl!("Overprints:"), &overprints); - let presets = app.session.flattener_presets(); - let current = flattener(d, &app.session.prefs.flattener_presets).ok(); - let mut custom = false; - widgets::label_row(ui, tl!("Preset:"), LABEL, |ui| { - if let Some(p) = super::flatten::preset_dropdown(ui, "eps-flattener-preset", &presets, &d.str("flattenerPreset"), current.as_ref(), 180.0) { - d.fields.insert("flattenerPreset".into(), json!(p.name)); - d.fields.remove("flattener"); - } - custom = widgets::flat_button_fit(ui, tl!("Custom…"), 72.0).clicked(); - }); - if custom { - *d = over(d, &app.session.prefs.flattener_presets); - return false; - } - ui.add_space(8.0); - widgets::subheader(ui, tl!("Fonts")); - // Type is written as glyph outlines, which need no fonts. - widgets::check(ui, tl!("Embed Fonts (for other applications)"), true, false); - ui.add_space(8.0); - widgets::subheader(ui, tl!("Options")); - check(ui, d, "includeLinkedFiles", tl!("Include Linked Files")); - check(ui, d, "thumbnails", tl!("Include Document Thumbnails")); - check(ui, d, "cmykPostScript", tl!("Include CMYK PostScript in RGB Files")); - check(ui, d, "compatibleGradients", tl!("Compatible Gradient and Gradient Mesh Printing")); - ui.add_space(4.0); - let levels: Vec<(&str, &str)> = Level::ALL.iter().map(|l| (l.id(), l.label())).collect(); - // A level set as a number (`level: 2`) reads as its id. - if let Some(Value::Number(n)) = d.fields.get("level") { - let id = n.to_string(); - d.fields.insert("level".into(), json!(id)); - } - choice(ui, d, "level", tl!("PostScript:"), &levels); - ui.add_space(8.0); - super::form::caption( - ui, - if Level::from_id(&d.str("level")) == Some(Level::Two) || d.bool("compatibleGradients") { - tl!("Transparency is flattened with the preset. Type is written as outlines; gradients as bands of colour.") - } else { - tl!("Transparency is flattened with the preset. Type is written as outlines; gradients stay smooth.") - }, - ); - false + export_host::open(app, Export::Eps, selection, dialog); } -/// `ui.dialog.set` changed `field` of EPS Options `d`: a preset set there drops the Custom… -/// options, as choosing it in the dropdown does, and a built-in one named by id shows as its name. -pub(super) fn field_set(d: &mut Dialog, field: &str) { - if field == "flattenerPreset" { - d.fields.remove("flattener"); - builtin_label(&mut d.fields); +/// A level set as a number (`level: 2`) reads as its id. +fn normalise_level(fields: &mut DialogFields) { + let id = match fields.get("level") { + Some(FieldValue::Int(n)) => n.to_string(), + Some(FieldValue::Number(n)) if n.is_finite() => format!("{n}"), + _ => return, + }; + fields.set("level", id); +} + +/// A built-in preset named by id (`medium`) in `fields` shows as its name. It runs where the values are built and +/// where the build runs each pass, so a preset set from outside shows as its name too. +fn builtin_label(fields: &mut DialogFields) { + let label = fields.text("flattenerPreset").and_then(|p| FlattenOptions::preset_label(&p.to_ascii_lowercase()).map(|l| l.to_string())); + if let Some(label) = label { + fields.set("flattenerPreset", label); } } -/// A built-in preset named by id (`medium`) in `fields` shows as its name. -fn builtin_label(fields: &mut Map) { - if let Some(label) = fields.get("flattenerPreset").and_then(Value::as_str).and_then(|p| FlattenOptions::preset_label(&p.to_ascii_lowercase())) { - fields.insert("flattenerPreset".into(), json!(label)); +/// The custom options `fields` hold, as JSON. +fn custom_value(fields: &DialogFields) -> Option { + match fields.get("flattener")? { + FieldValue::Json(v) => Some(v.clone()), + other => serde_json::to_value(other).ok(), } } -/// The flattener options EPS Options `d` exports with: its preset, with the Custom… options over it. -fn flattener(d: &Dialog, saved: &[FlattenerPreset]) -> Result { - FlattenOptions::for_export(d.fields.get("flattenerPreset").and_then(Value::as_str), d.fields.get("flattener"), saved) +/// The flattener options EPS Options `fields` export with: its preset, with the Custom… options over it. +fn flattener(fields: &DialogFields, saved: &[FlattenerPreset]) -> Result { + FlattenOptions::for_export(fields.text("flattenerPreset"), custom_value(fields).as_ref(), saved) } -/// Custom Transparency Flattener Options over EPS Options `parent`, on the options it exports with -/// (the default preset's while those are not valid), without alpha: EPS has none. -pub(super) fn over(parent: &Dialog, saved: &[FlattenerPreset]) -> Dialog { - let mut o = flattener(parent, saved).unwrap_or_default(); +/// The options Custom Transparency Flattener Options `fields` hold. +fn custom_options(fields: &DialogFields) -> Result { + let rows = flatten::option_params(&FIXED, FIXED_REASON); + FlattenOptions::from_params_with(&Value::Object(form::json_of(&rows, fields)), &[]) +} + +/// Custom Transparency Flattener Options over EPS Options `parent` (whose values are `fields`), on the options it +/// exports with (the default preset's while those are not valid), without alpha: EPS has none. +pub(super) fn custom_dialog(app: &VectorcraftApp, parent: DialogId, fields: &DialogFields) -> HostedParamDialog { + let _ = parent; // the host keeps the parent; `Export::EpsCustom` names it + let mut o = flattener(fields, &app.session.prefs.flattener_presets).unwrap_or_default(); o.preserve_alpha = false; - let mut d = Dialog::new(CUSTOM_KIND, json!({})); - super::flatten::put_options(&mut d.fields, &o); - d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default()); - d + let mut start = DialogFields::new(); + flatten::put_options(&mut start, &o); + // PLAN: assumed `app.ui_ctx: Option` is set whenever a window is shown. + let ctx = app.ui_ctx.clone().unwrap_or_default(); + HostedParamDialog::new(&ctx, CUSTOM_KIND, start, |fields| { + ParamDialog::new(CUSTOM_KIND, tl!("Custom Transparency Flattener Options"), flatten::option_params(&FIXED, FIXED_REASON)) + .values(Bind::bound(fields)) + .below(|ui, _| { + ui.weak(tl!("EPS has no alpha transparency, and Overprints sets whether overprints are kept.")); + }) + }) } -/// The options Custom Transparency Flattener Options `d` holds. -fn custom_options(d: &Dialog) -> Result { - FlattenOptions::from_params_with(&Value::Object(d.fields.clone()), &[]) -} - -/// Whether the EPS Options under `d` keep overprints (Overprints: Preserve). -fn overprints_kept(d: &Dialog) -> bool { - super::parent(d).is_none_or(|p| Overprint::from_id(&p.str("overprints")) != Some(Overprint::Discard)) -} - -/// The flattener options; the two Preserve switches show what the export does and are set by the -/// format (no alpha) and by EPS Options' Overprints. -fn custom_body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let current = custom_options(d); - // Values refused stay as entered, so that changing another option keeps them. The Preserve - // switches can't be set here, so the fields keep their own values of them. - let (mut o, unread) = super::flatten::shown_options(&d.fields, ¤t); +/// OK of the custom options: EPS Options `parent` again, exporting with these options (a built-in preset under them, +/// so that deleting a saved preset leaves them whole); bad options keep the dialog open. +pub(super) fn custom_ok(_app: &VectorcraftApp, parent: &mut DialogFields, fields: &DialogFields) -> Result<(), String> { + let mut o = custom_options(fields)?; o.preserve_alpha = false; - o.preserve_overprints &= overprints_kept(d); - super::flatten::fields_editor(ui, "eps-flattener", &mut d.fields, &mut o, &unread, &["preserveAlpha", "preserveOverprints"]); - if let Err(e) = ¤t { - ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim).size(11.5)); - } - ui.add_space(8.0); - super::form::caption(ui, tl!("EPS has no alpha transparency, and Overprints sets whether overprints are kept.")); - false -} - -/// OK: EPS Options again, exporting with these options (a built-in preset under them, so that -/// deleting a saved preset leaves them whole); bad options keep the dialog open. -fn custom_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let mut o = custom_options(d)?; - o.preserve_alpha = false; - let mut parent = super::parent(d).ok_or("the dialog it was opened over is no longer open")?; - if FlattenOptions::preset(&parent.str("flattenerPreset")).is_none() { + if FlattenOptions::preset(parent.text("flattenerPreset").unwrap_or_default()).is_none() { let medium = FlattenOptions::preset_label(FlattenOptions::PRESETS[1]).unwrap_or_default(); - parent.fields.insert("flattenerPreset".into(), json!(medium)); + parent.set("flattenerPreset", medium.to_string()); } - parent.fields.insert("flattener".into(), serde_json::to_value(&o).map_err(|e| e.to_string())?); - app.ui.dialog = Some(parent); - Ok(Value::Null) + parent.set("flattener", FieldValue::Json(serde_json::to_value(&o).map_err(|e| e.to_string())?)); + Ok(()) } /// Check the options, remember them, and write the file(s). -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let params = fileio::eps::resolve(&super::form::params(d), &app.session.prefs.flattener_presets)?; +pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result { + let map = form::json_of(&kinds(), fields); + let params = fileio::eps::resolve(&Value::Object(map.clone()), &app.session.prefs.flattener_presets)?; // Nothing selected keeps the dialog open too. if let Some(st) = app.session.active() { fileio::export_source(st, ¶ms).map_err(|e| e.to_string())?; } - app.ui.eps_options = - Value::Object(d.fields.iter().filter(|(k, _)| !PER_EXPORT.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect()); - app.ui.dialog = None; - let path = d.fields.get("path").and_then(Value::as_str).map(str::to_string); - io::export(app, Some("eps"), path, &super::export_as::exported(d, params)) + app.ui.eps_options = Value::Object(map.into_iter().filter(|(k, _)| !PER_EXPORT.contains(&k.as_str())).collect()); + let path = fields.text("path").map(str::to_string); + // PLAN: assumed `After` is an `Option` of the step to run once the dialog closed. + io::export(app, Some("eps"), path, &super::export_as::exported(open.selection, params)).map(|_| None) } diff --git a/crates/ui-egui/src/dialogs/hpgl_options.rs b/crates/ui-egui/src/dialogs/hpgl_options.rs index cf2e578855..10343585b5 100644 --- a/crates/ui-egui/src/dialogs/hpgl_options.rs +++ b/crates/ui-egui/src/dialogs/hpgl_options.rs @@ -11,31 +11,28 @@ //! to 10 points. OK after another document has become the active one closes the dialog and writes //! nothing. +use craft::behavior::IconId; +use craft_ui::buttons::{Button, IconButton}; +use craft_ui::choice::{Radio, RadioGroup, Swatch}; +use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; +use craft_ui::dialog::DialogId; +use craft_ui::layout_components::Stack; +use craft_ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog}; +use craft_ui::text::HexField; use serde_json::{Map, Value, json}; use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE}; use vectorcraft_cad::hpgl::{Origin, Version}; use vectorcraft_engine::cmd::fileio; -use super::DialogSpec; -use super::document_setup::{LABEL, check, choice}; -use crate::state::Dialog; -use crate::{VectorcraftApp, io, widgets}; +use super::dxf_options::{check_param, choice_param}; +use super::export_host::{self, After, Export, Open}; +use super::form; +use crate::{VectorcraftApp, io}; pub(super) const KIND: &str = "hpglOptions"; -pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |_| tl!("HP-GL Options").into(), - body, - confirm, - ok: Some("Export"), - min_width: 420.0, - max_width: Some(460.0), - inputs: |_| &["path"], - ..DialogSpec::FORM -}; - /// Fields that are not remembered between exports (they belong to one export). -const PER_EXPORT: [&str; 8] = ["format", "path", "useArtboards", "range", "artboard", "artboards", "selectedOnly", io::EXPORT_SELECTION]; +const PER_EXPORT: [&str; 7] = ["format", "path", "useArtboards", "range", "artboard", "artboards", "selectedOnly"]; /// The pen table set aside while One Pen per Color is chosen, so Pen Table shows it again. const SET_ASIDE: &str = "__pens"; @@ -43,9 +40,6 @@ const SET_ASIDE: &str = "__pens"; /// Why Pen Table could not start from the art's pens, shown under the Pens row. const PEN_ERROR: &str = "__penError"; -/// The field that holds the uid of the document the dialog was opened for. -const DOC: &str = "__doc"; - /// The Origin menu's names, in [`Origin::ALL`] order. pub(crate) const ORIGIN_NAMES: [&str; 2] = ["Bottom Left", "Center"]; @@ -65,9 +59,27 @@ fn defaults() -> Map { m } +/// The rows. +fn params() -> Vec { + vec![ + choice_param("hpglVersion", tl!("Version:"), Version::ALL.iter().map(|v| (v.id(), v.label()))), + Param::number("curveTolerance", tl!("Curve Tolerance:"), DEFAULT_TOLERANCE, 0.1, 2).bounds(Some(*TOLERANCE_RANGE.start()), Some(*TOLERANCE_RANGE.end())), + choice_param("origin", tl!("Origin:"), Origin::ALL.iter().map(|o| o.id()).zip(ORIGIN_NAMES)), + pens_param(), + check_param("sortPaths", tl!("Draw the Nearest Path Next")), + check_param("insideFirst", tl!("Draw Inner Paths First")), + ] +} + /// Open HP-GL Options for an export whose params (path, artboard choice, any HP-GL option) are /// `params`, over the options used last. pub fn open(app: &mut VectorcraftApp, params: &Value) { + open_with(app, params, false); +} + +/// [`open`] for Export Selection when `selection` is set: the options then plot the selection alone. +pub fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) { + let Some(doc) = app.session.active().map(|st| st.uid) else { return }; let mut fields = defaults(); for given in [&app.ui.hpgl_options, params] { if let Some(o) = given.as_object() { @@ -75,115 +87,156 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) { } } fields.insert("format".into(), json!("hpgl")); - fields.insert(DOC.into(), json!(app.session.active().map(|st| st.uid))); - app.ui.dialog = Some(Dialog::new(KIND, Value::Object(fields))); + let values = form::fields_of(¶ms(), &fields); + // PLAN: assumed `app.ui_ctx: Option` is set whenever a window is shown. + let ctx = app.ui_ctx.clone().unwrap_or_default(); + let dialog = HostedParamDialog::new(&ctx, KIND, values, |fields| { + // PLAN: assumed `ok_label` takes a `Label`. + ParamDialog::new(KIND, tl!("HP-GL Options"), params()).values(Bind::bound(fields)).ok_label(tl!("Export").into()) + }); + export_host::open(app, Export::Hpgl { doc }, selection, dialog); } -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let versions: Vec<(&str, &str)> = Version::ALL.iter().map(|v| (v.id(), v.label())).collect(); - choice(ui, d, "hpglVersion", tl!("Version:"), &versions); - ui.add_space(4.0); - widgets::label_row(ui, tl!("Curve Tolerance:"), LABEL, |ui| { - let x = d.f64("curveTolerance", DEFAULT_TOLERANCE); - if let Some(v) = widgets::plain_field(ui, "hpgl-tolerance", x, " pt", 2, 80.0) { - let (lo, hi) = (*TOLERANCE_RANGE.start(), *TOLERANCE_RANGE.end()); - d.fields.insert("curveTolerance".into(), json!(v.clamp(lo, hi))); - } - }); - ui.add_space(4.0); - let origins: Vec<(&str, &str)> = Origin::ALL.iter().map(|o| o.id()).zip(ORIGIN_NAMES).collect(); - choice(ui, d, "origin", tl!("Origin:"), &origins); - ui.add_space(10.0); - pens(app, ui, d); - ui.add_space(8.0); - check(ui, d, "sortPaths", tl!("Draw the Nearest Path Next")); - check(ui, d, "insideFirst", tl!("Draw Inner Paths First")); - false +/// The pen table `fields` hold: `None` for One Pen per Color. +fn table(fields: &DialogFields) -> Option> { + match fields.get("pens")? { + FieldValue::Json(Value::Array(a)) => Some(a.clone()), + FieldValue::List(l) => Some(l.iter().filter_map(|v| serde_json::to_value(v).ok()).collect()), + _ => None, + } +} + +/// The key a pen's picked colour comes back under. +fn pen_key(i: usize) -> String { + format!("__penColor{i}") } /// Pens: One Pen per Color (`pens` null) or Pen Table (`pens` the colors, pen 1's first), with a /// row per pen (its number, color and a Remove button) and Add. -fn pens(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { - let table = d.fields.get("pens").is_some_and(Value::is_array); - widgets::label_row(ui, tl!("Pens:"), LABEL, |ui| { - if widgets::radio(ui, tl!("One Pen per Color"), !table, true) { - let _ = set_pen_table(d, false, || Ok(Vec::new())); - d.fields.remove(PEN_ERROR); +fn pens_param() -> Param { + Param::custom("pens", tl!("Pens:"), |ui, fields, cx| { + ui.vertical(|ui| pens_ui(ui, fields, cx)).response + }) + .companions([SET_ASIDE, PEN_ERROR]) + .full_width() +} + +/// The pens row. Switching to Pen Table asks the host (`penTable`): the table starts from the document's pens, which +/// this draw cannot reach. +fn pens_ui(ui: &mut egui::Ui, fields: &mut DialogFields, cx: &mut CustomContext) { + let mut list = table(fields); + let mut changed = false; + // Colours the picker answered. + if let Some(pens) = list.as_mut() { + for (i, pen) in pens.iter_mut().enumerate() { + if let Some([r, g, b]) = fields.color(&pen_key(i)) { + let byte = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8; + *pen = json!(format!("#{:02x}{:02x}{:02x}", byte(r), byte(g), byte(b))); + fields.remove(&pen_key(i)); + changed = true; + } } - ui.add_space(12.0); - if widgets::radio(ui, tl!("Pen Table"), table, true) { - let shown = d.clone(); - match set_pen_table(d, true, || automatic_pens(app, &shown)) { - Ok(()) => d.fields.remove(PEN_ERROR), - Err(e) => d.fields.insert(PEN_ERROR.into(), json!(e)), - }; - } - }); - if let Some(e) = d.fields.get(PEN_ERROR).and_then(Value::as_str) { - let t = crate::theme::Tokens::get(ui.ctx()); - ui.label(egui::RichText::new(crate::i18n::message(crate::i18n::current(), e)).color(t.error)); } - // The table as the radio buttons left it, so a row edit committed this frame can't undo a switch. + let mut on = list.is_some(); + RadioGroup::new(tl!("Pens:"), Bind::bound(&mut on)).show(ui, |ui| { + Radio::new(false).label(tl!("One Pen per Color")).show(ui); + Radio::new(true).label(tl!("Pen Table")).show(ui); + }); + if on != list.is_some() { + if on { + cx.request_action("penTable"); + } else { + let _ = set_pen_table(fields, false, || Ok(Vec::new())); + fields.remove(PEN_ERROR); + list = None; + } + } + if let Some(e) = fields.text(PEN_ERROR) { + ui.colored_label(crate::theme::Tokens::get(ui.ctx()).error, crate::i18n::message(crate::i18n::current(), e)); + } // A table longer than a plot takes (set through `ui.dialog.set`) draws no rows: OK refuses it. - let Some(mut list) = d.fields.get("pens").and_then(Value::as_array).filter(|a| a.len() <= MAX_PENS).cloned() else { return }; - let t = crate::theme::Tokens::get(ui.ctx()); - let n = list.len(); - let (mut changed, mut remove) = (false, None); - egui::ScrollArea::vertical().id_salt("hpgl-pens").max_height(180.0).auto_shrink([false, true]).show(ui, |ui| { - for (i, v) in list.iter_mut().enumerate() { + let Some(mut pens) = list.filter(|a| a.len() <= MAX_PENS) else { return }; + let n = pens.len(); + let mut remove = None; + // PLAN: assumed `Stack::new().scroll(..).room_height(..)` builders and `show(ui, body)`. + Stack::new().scroll(craft_ui::contract::Scroll::vertical()).room_height(180.0).show(ui, |ui| { + for (i, pen) in pens.iter_mut().enumerate() { ui.horizontal(|ui| { - ui.add_space(LABEL + 8.0); - ui.add_sized([28.0, 18.0], egui::Label::new(egui::RichText::new((i + 1).to_string()).color(t.text))); - let hex = v.as_str().and_then(|s| s.strip_prefix('#')).unwrap_or_default().to_string(); - let (rect, _) = ui.allocate_exact_size(egui::vec2(20.0, 18.0), egui::Sense::hover()); - if let Some([r, g, b]) = rgb(&hex) { - ui.painter().rect_filled(rect, 2.0, egui::Color32::from_rgb(r, g, b)); + ui.label((i + 1).to_string()); + let mut color = pen.as_str().and_then(craft::theme::Srgba::from_hex).unwrap_or(craft::theme::Srgba::rgb(0.0, 0.0, 0.0)); + if Swatch::new(tl!("Pen color"), color).show(ui).response.clicked() { + cx.pick_color(&pen_key(i), color); } - ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); - if let Some(typed) = widgets::hex_field(ui, ("hpgl-pen", i), &hex) - && let Some(color) = pen_color(&typed) + let before = color; + HexField::new(tl!("Pen color"), Bind::bound(&mut color)).id_salt(("hpgl-pen", i)).show(ui); + if color != before + && let Some(typed) = pen_color(&color.to_hex()) { - *v = json!(color); + *pen = json!(typed); changed = true; } - if widgets::icon_button_enabled(ui, "x", tl!("Remove"), false, n > 1, 22.0).clicked() { + if IconButton::new(IconId::new("trash")).label(tl!("Remove")).enabled(n > 1).show(ui).clicks > 0 { remove = Some(i); } }); } }); - ui.horizontal(|ui| { - ui.add_space(LABEL + 8.0); - if ui.add_enabled(n < MAX_PENS, |ui: &mut egui::Ui| widgets::flat_button(ui, tl!("Add"), 60.0)).clicked() { - // A new pen starts as the last one's color, ready to be changed. - list.push(list.last().cloned().unwrap_or_else(|| json!("#000000"))); - changed = true; - } - }); - if let Some(i) = remove.filter(|_| list.len() > 1) { - list.remove(i); + if Button::new(tl!("Add")).enabled(n < MAX_PENS).show(ui).clicks > 0 { + // A new pen starts as the last one's color, ready to be changed. + pens.push(pens.last().cloned().unwrap_or_else(|| json!("#000000"))); + changed = true; + } + if let Some(i) = remove.filter(|_| pens.len() > 1) { + pens.remove(i); changed = true; } if changed { - d.fields.insert("pens".into(), Value::Array(list)); + fields.set("pens", FieldValue::Json(Value::Array(pens))); } } -/// The pens an export from dialog `d` with no pen table would get: its options, artboard choice and -/// source art (the selection with Export Selected Art Only, or when Export Selection opened `d`); -/// an error when there is no document or the export refuses those. -pub(super) fn automatic_pens(app: &VectorcraftApp, d: &Dialog) -> Result, String> { +/// Starts Pen Table for dialog `id`: the table the export would give the art, or the reason it cannot. It runs from +/// the host's pump, which holds no lock on the dialog while the document is read. +pub(super) fn pen_ask(app: &mut VectorcraftApp, id: DialogId) { + let Some(selection) = app.export_dialogs.0.iter().find(|o| o.id == id).map(|o| o.selection) else { return }; + let Some(mut copy) = app.dialogs().get_by_id::(id).map(|d| d.fields().clone()) else { return }; + let shown = copy.clone(); + let result = set_pen_table(&mut copy, true, || automatic_pens(app, &shown, selection)); + let Some(dialog) = app.dialogs().get_mut_by_id::(id) else { return }; + match result { + Ok(()) => { + for key in ["pens", SET_ASIDE] { + match copy.get(key) { + Some(v) => dialog.set_field(key, v.clone()), + None => dialog.clear_field(key), + } + } + dialog.clear_field(PEN_ERROR); + } + Err(e) => dialog.set_field(PEN_ERROR, FieldValue::Text(e)), + } +} + +/// The pens an export from a dialog holding `fields` with no pen table would get: its options, artboard choice and +/// source art (the selection with Export Selected Art Only, or when Export Selection opened the dialog); an error +/// when there is no document or the export refuses those. +pub(super) fn automatic_pens(app: &VectorcraftApp, fields: &DialogFields, selection: bool) -> Result, String> { let st = app.session.active().ok_or("no document")?; - let (doc, params) = source(st, d)?; + let (doc, params) = source(st, fields, selection)?; fileio::hpgl::automatic_pens(&doc, ¶ms) } -/// The document an export from dialog `d` writes and the export params it reads, as +/// The document an export from a dialog holding `fields` writes and the export params it reads, as /// [`io::export`] takes them ([`io::take_selection`]): with Export Selection the selection alone, /// without the artboard choice, else the whole document or, with Export Selected Art Only, its /// selected objects. -fn source<'a>(st: &'a vectorcraft_engine::DocState, d: &Dialog) -> Result<(std::borrow::Cow<'a, vectorcraft_doc::Document>, Value), String> { - let (selection, params) = io::take_selection(&super::export_as::exported(d, super::form::params(d)))?; +fn source<'a>( + st: &'a vectorcraft_engine::DocState, + fields: &DialogFields, + selection: bool, +) -> Result<(std::borrow::Cow<'a, vectorcraft_doc::Document>, Value), String> { + let params = Value::Object(form::json_of(¶ms(), fields)); + let (selection, params) = io::take_selection(&super::export_as::exported(selection, params))?; if !selection { let doc = fileio::export_source(st, ¶ms).map_err(|e| e.to_string())?; return Ok((doc, params)); @@ -196,11 +249,11 @@ fn source<'a>(st: &'a vectorcraft_engine::DocState, d: &Dialog) -> Result<(std:: /// per Color was chosen, else the pens the export would give the art (`automatic`), else one black /// pen when that art draws nothing; when `automatic` fails the dialog is left as it was and the /// error returned. One Pen per Color sets the table aside. -pub(super) fn set_pen_table(d: &mut Dialog, on: bool, automatic: impl FnOnce() -> Result, String>) -> Result<(), String> { - let table = d.fields.get("pens").filter(|v| v.is_array()).cloned(); +pub(super) fn set_pen_table(fields: &mut DialogFields, on: bool, automatic: impl FnOnce() -> Result, String>) -> Result<(), String> { + let table = table(fields); match (on, table) { (true, None) => { - let kept = d.fields.get(SET_ASIDE).filter(|v| v.as_array().is_some_and(|a| !a.is_empty())).cloned(); + let kept = fields.get(SET_ASIDE).and_then(|v| serde_json::to_value(v).ok()).filter(|v| v.as_array().is_some_and(|a| !a.is_empty())); let list = match kept { Some(list) => list, None => { @@ -212,12 +265,12 @@ pub(super) fn set_pen_table(d: &mut Dialog, on: bool, automatic: impl FnOnce() - json!(pens) } }; - d.fields.remove(SET_ASIDE); - d.fields.insert("pens".into(), list); + fields.remove(SET_ASIDE); + fields.set("pens", FieldValue::Json(list)); } (false, Some(list)) => { - d.fields.insert(SET_ASIDE.into(), list); - d.fields.insert("pens".into(), Value::Null); + fields.set(SET_ASIDE, FieldValue::Json(Value::Array(list))); + fields.set("pens", FieldValue::Json(Value::Null)); } _ => {} } @@ -243,33 +296,28 @@ fn rgb(hex: &str) -> Option<[u8; 3]> { /// Check the options, remember them, and write the file(s). When another document has become the /// active one since the dialog opened, it closes as Cancel does and writes nothing. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|st| st.uid) { - app.ui.dialog = None; - return Ok(json!({})); +pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result { + let Export::Hpgl { doc } = &open.kind else { return Err("this is not an HP-GL export".into()) }; + if Some(*doc) != app.session.active().map(|st| st.uid) { + // PLAN: assumed `After` is an `Option`; `None` closes the dialog with nothing to run. + return Ok(None); } - let params = super::form::params(d); + let map = form::json_of(¶ms(), fields); + let params = Value::Object(map.clone()); let st = app.session.active().ok_or("no document")?; // A bad option or artboard choice, nothing selected, or no art to export keeps the dialog open. - let (source, checked) = source(st, d)?; + let (source, checked) = source(st, fields, open.selection)?; fileio::hpgl::check(&source, &checked)?; - let remembered = params.as_object().map(|o| o.iter().filter(|(k, _)| !PER_EXPORT.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone()))); - let before = std::mem::replace(&mut app.ui.hpgl_options, Value::Object(remembered.into_iter().flatten().collect())); - app.ui.dialog = None; - let path = d.fields.get("path").and_then(Value::as_str).map(str::to_string); - let waiting = app.picks.is_waiting(); - let r = io::export(app, Some("hpgl"), path, &super::export_as::exported(d, params)); - if !waiting && app.picks.is_waiting() { - // A save panel shown off the UI thread confirms the dialog again when it answers, which - // remembers the options then; until it does, and when it is canceled, the options - // remembered before stay. + let remembered = Value::Object(map.into_iter().filter(|(k, _)| !PER_EXPORT.contains(&k.as_str())).collect()); + let before = std::mem::replace(&mut app.ui.hpgl_options, remembered); + let path = fields.text("path").map(str::to_string); + let waiting = app.file_dialog_open(); + let r = io::export(app, Some("hpgl"), path, &super::export_as::exported(open.selection, params)); + // A save panel shown off the UI thread confirms the dialog again when it answers, which remembers the options + // then; until it does, and when an export stops before writing (a canceled panel), the options remembered + // before stay. + if (!waiting && app.file_dialog_open()) || r.is_err() { app.ui.hpgl_options = before; - } else if r.is_err() && app.ui.dialog.is_none() { - // An export that stops before writing (a save panel that was canceled or could not be - // shown) leaves the dialog open over the options remembered before. A question that a - // save panel asked stays open. - app.ui.hpgl_options = before; - app.ui.dialog = Some(d.clone()); } - r + r.map(|_| None) } diff --git a/crates/ui-egui/src/dialogs/tests_dxf.rs b/crates/ui-egui/src/dialogs/tests_dxf.rs index 775562fa8f..1a9cbee3d2 100644 --- a/crates/ui-egui/src/dialogs/tests_dxf.rs +++ b/crates/ui-egui/src/dialogs/tests_dxf.rs @@ -1,14 +1,34 @@ //! Export As → DXF Options, and DWG listed as unavailable, drawn headlessly. +use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue}; use serde_json::json; -use super::tests_export::{app, frame, kind, names, set}; +// PLAN: assumed `fields(&app)` returns the values of the top hosted dialog (export-w9's helpers). +use super::tests_export::{app, fields, frame, kind, names, set}; use super::*; fn text(bytes: &[u8]) -> String { String::from_utf8(bytes.to_vec()).unwrap() } +/// A value as the old tests compared it. +fn show(d: &DialogFields, key: &str) -> String { + match d.get(key) { + Some(FieldValue::Text(s)) => s.clone(), + Some(FieldValue::Number(n)) => format!("{n:?}"), + Some(FieldValue::Int(n)) => n.to_string(), + Some(FieldValue::Bool(b)) => b.to_string(), + _ => String::new(), + } +} + +/// The preset's fields as one line. +fn line(d: &DialogFields) -> String { + ["dxfPreset", "version", "unit", "scale", "colors", "preserve", "alterPaths", "outlineText", "includeImages", "includeHatches"] + .map(|k| show(d, k)) + .join(" ") +} + #[test] fn export_as_dxf_shows_dxf_options_then_writes_and_remembers_them() { let (mut app, written) = app(1); @@ -18,8 +38,8 @@ fn export_as_dxf_shows_dxf_options_then_writes_and_remembers_them() { set(&mut app, "useArtboards", json!(true)); confirm(&mut app).unwrap(); assert_eq!(kind(&app), Some("dxfOptions"), "DXF Options follow"); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.str("path"), d.str("version"), d.str("preserve")), ("/out/Untitled-1.dxf".into(), "2018".into(), "appearance".into())); + let d = fields(&app); + assert_eq!((show(&d, "path"), show(&d, "version"), show(&d, "preserve")), ("/out/Untitled-1.dxf".into(), "2018".into(), "appearance".into())); frame(&mut app); // Every control draws: R12 with true colour shows its note, Maximize Editability frees Outline Text. set(&mut app, "version", json!("R12")); @@ -28,15 +48,15 @@ fn export_as_dxf_shows_dxf_options_then_writes_and_remembers_them() { frame(&mut app); set(&mut app, "colors", json!("256")); let r = confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + assert!(kind(&app).is_none()); assert_eq!(r["path"], "/out/Untitled-1.dxf"); let dxf = text(&written.borrow()[0].1); assert!(dxf.contains("$ACADVER\n 1\nAC1009"), "{dxf}"); // The next DXF Options start from these choices, but not from this export's path. crate::menus::invoke(&mut app, "ui.dxfOptionsDialog", json!({})); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.str("version"), d.str("unit"), d.str("colors")), ("R12".into(), "Inches".into(), "256".into())); - assert!(!d.fields.contains_key("path")); + let d = fields(&app); + assert_eq!((show(&d, "version"), show(&d, "unit"), show(&d, "colors")), ("R12".into(), "Inches".into(), "256".into())); + assert!(!d.contains("path")); assert!(app.ui.dxf_options.get("useArtboards").is_none()); } @@ -45,23 +65,17 @@ fn the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom() { let (mut app, written) = app(1); app.run("ui.dxfOptionsDialog", json!({"path": "/out/a.dxf"})).unwrap(); frame(&mut app); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("dxfPreset"), "custom"); + assert_eq!(show(&fields(&app), "dxfPreset"), "custom"); set(&mut app, "dxfPreset", json!("cnc")); frame(&mut app); - let d = app.ui.dialog.as_ref().unwrap(); - let fields = |d: &crate::state::Dialog| { - ["dxfPreset", "version", "unit", "scale", "colors", "preserve", "alterPaths", "outlineText", "includeImages", "includeHatches"] - .map(|k| d.str(k)) - .join(" ") - }; - assert_eq!(fields(d), "cnc 2000 Millimeters 1.0 256 editability false true false false"); + assert_eq!(line(&fields(&app)), "cnc 2000 Millimeters 1.0 256 editability false true false false"); // Any change to a field the preset sets shows Custom, and keeps the other fields. set(&mut app, "colors", json!("true")); frame(&mut app); - assert_eq!(fields(app.ui.dialog.as_ref().unwrap()), "custom 2000 Millimeters 1.0 true editability false true false false"); + assert_eq!(line(&fields(&app)), "custom 2000 Millimeters 1.0 true editability false true false false"); set(&mut app, "colors", json!("256")); frame(&mut app); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("dxfPreset"), "cnc", "matching every field again"); + assert_eq!(show(&fields(&app), "dxfPreset"), "cnc", "matching every field again"); confirm(&mut app).unwrap(); let dxf = text(&written.borrow()[0].1); let lines: Vec<&str> = dxf.lines().collect(); @@ -69,34 +83,30 @@ fn the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom() { assert_eq!((header("$ACADVER"), header("$INSUNITS")), (Some("AC1015"), Some("4"))); // The next DXF Options start from the preset; Custom puts back the defaults. crate::menus::invoke(&mut app, "ui.dxfOptionsDialog", json!({})); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("dxfPreset"), "cnc"); + assert_eq!(show(&fields(&app), "dxfPreset"), "cnc"); set(&mut app, "dxfPreset", json!("custom")); frame(&mut app); - assert_eq!(fields(app.ui.dialog.as_ref().unwrap()), "custom 2018 Millimeters 1.0 true appearance false false true true"); + assert_eq!(line(&fields(&app)), "custom 2018 Millimeters 1.0 true appearance false false true true"); // A preset the command gives sets the fields it does not give. - app.ui.dialog = None; + cancel(&mut app); app.run("ui.dxfOptionsDialog", json!({"dxfPreset": "cnc", "unit": "Inches"})).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(fields(d), "custom 2000 Inches 1.0 256 editability false true false false"); + assert_eq!(line(&fields(&app)), "custom 2000 Inches 1.0 256 editability false true false false"); // A preset set and confirmed without drawing (the control channel) sets its fields too. set(&mut app, "dxfPreset", json!("cnc")); confirm(&mut app).unwrap(); assert_eq!((app.ui.dxf_options["dxfPreset"].as_str(), app.ui.dxf_options["unit"].as_str()), (Some("cnc"), Some("Millimeters"))); - // `ui.dialog.set` sets the preset's fields at once, so a field set after it keeps its value. + // A field set after the preset, with no frame between, keeps its value and shows Custom. app.run("ui.dxfOptionsDialog", json!({"dxfPreset": "custom"})).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - set_field(d, "dxfPreset".into(), json!("cnc")); - assert_eq!(fields(d), "cnc 2000 Millimeters 1.0 256 editability false true false false"); - set_field(d, "unit".into(), json!("Inches")); - assert_eq!(d.str("dxfPreset"), "custom"); - // Setting the preset again sets its fields again. - set_field(d, "dxfPreset".into(), json!("cnc")); - assert_eq!(d.str("unit"), "Millimeters"); - set_field(d, "unit".into(), json!("Inches")); - // Setting Custom while Custom is shown still puts back the defaults. - let mut reset = d.clone(); - set_field(&mut reset, "dxfPreset".into(), json!("custom")); - assert_eq!(fields(&reset), "custom 2018 Millimeters 1.0 true appearance false false true true"); + set(&mut app, "dxfPreset", json!("cnc")); + set(&mut app, "unit", json!("Inches")); + frame(&mut app); + let d = fields(&app); + assert_eq!((show(&d, "unit"), show(&d, "dxfPreset"), show(&d, "version")), ("Inches".into(), "custom".into(), "2000".into())); + // Setting the preset again, once Custom is shown, sets its fields again. + set(&mut app, "dxfPreset", json!("cnc")); + frame(&mut app); + assert_eq!(show(&fields(&app), "unit"), "Millimeters"); + set(&mut app, "unit", json!("Inches")); confirm(&mut app).unwrap(); let remembered = ["dxfPreset", "version", "unit"].map(|k| app.ui.dxf_options[k].as_str()); assert_eq!(remembered, [Some("custom"), Some("2000"), Some("Inches")]); @@ -106,8 +116,8 @@ fn the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom() { fn include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom() { let (mut app, written) = app(1); let shown = |app: &VectorcraftApp| { - let d = app.ui.dialog.as_ref().unwrap(); - (d.str("dxfPreset"), d.bool("includeImages"), d.bool("includeHatches")) + let d = fields(app); + (show(&d, "dxfPreset"), d.bool("includeImages") == Some(true), d.bool("includeHatches") == Some(true)) }; app.run("ui.dxfOptionsDialog", json!({"path": "/out/a.dxf"})).unwrap(); frame(&mut app); @@ -171,7 +181,7 @@ fn bad_dxf_options_keep_the_dialog_open() { fn dwg_is_listed_but_points_to_dxf() { let (mut app, written) = app(1); app.run("file.exportAs", json!({"format": "dwg"})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("format"), "dwg"); + assert_eq!(show(&fields(&app), "format"), "dwg"); frame(&mut app); let e = confirm(&mut app).unwrap_err(); assert!(e.contains("DWG") && e.contains("DXF"), "{e}"); @@ -181,10 +191,3 @@ fn dwg_is_listed_but_points_to_dxf() { assert_eq!(kind(&app), Some("dxfOptions")); assert!(written.borrow().is_empty()); } - -#[test] -fn the_dxf_options_dialog_needs_a_document() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - assert!(app.run("ui.dxfOptionsDialog", json!({})).is_err()); - assert!(!crate::menus::enabled(&app, "ui.dxfOptionsDialog")); -} diff --git a/crates/ui-egui/src/dialogs/tests_eps.rs b/crates/ui-egui/src/dialogs/tests_eps.rs index 5cd2efe24c..fc48587d10 100644 --- a/crates/ui-egui/src/dialogs/tests_eps.rs +++ b/crates/ui-egui/src/dialogs/tests_eps.rs @@ -1,8 +1,11 @@ //! Export As → EPS Options, drawn headlessly. +use craft_ui::patterns::form_dialogs::DialogFields; use serde_json::json; -use super::tests_export::{app, frame, kind, names, set}; +// PLAN: assumed `fields(&app)` (values of the top hosted dialog) and `press(&mut app, name)` (the control channel's +// click on a control by name, export-w23) in export-w9's helpers. +use super::tests_export::{app, fields, frame, kind, names, press, set}; use super::*; /// The PostScript of an EPS file. @@ -10,6 +13,21 @@ fn ps(bytes: &[u8]) -> String { String::from_utf8(vectorcraft_eps::sections(bytes).unwrap().0.to_vec()).unwrap() } +/// A text value of the open dialog. +fn text(d: &DialogFields, key: &str) -> String { + d.text(key).unwrap_or_default().to_string() +} + +/// The custom flattener options an EPS Options dialog holds. +fn flattener(d: &DialogFields) -> serde_json::Value { + d.get("flattener").and_then(|v| serde_json::to_value(v).ok()).unwrap_or_default() +} + +/// A dialog's values as JSON, to compare two states. +fn as_json(d: &DialogFields) -> serde_json::Value { + serde_json::to_value(d).unwrap_or_default() +} + #[test] fn export_as_eps_shows_eps_options_then_writes_and_remembers_them() { let (mut app, written) = app(2); @@ -19,9 +37,9 @@ fn export_as_eps_shows_eps_options_then_writes_and_remembers_them() { set(&mut app, "useArtboards", json!(true)); confirm(&mut app).unwrap(); assert_eq!(kind(&app), Some("epsOptions"), "EPS Options follow"); - let d = app.ui.dialog.as_ref().unwrap(); + let d = fields(&app); assert_eq!( - (d.str("path"), d.str("previewFormat"), d.str("flattenerPreset")), + (text(&d, "path"), text(&d, "previewFormat"), text(&d, "flattenerPreset")), ("/out/Untitled-1.eps".into(), "tiffColor".into(), "Medium Resolution".into()) ); frame(&mut app); @@ -30,22 +48,22 @@ fn export_as_eps_shows_eps_options_then_writes_and_remembers_them() { set(&mut app, "level", json!(2)); set(&mut app, "cmykPostScript", json!(false)); frame(&mut app); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("level"), "2", "a number reads as the level"); + assert_eq!(text(&fields(&app), "level"), "2", "a number reads as the level"); set(&mut app, "flattenerPreset", json!("High Resolution")); let r = confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + assert!(kind(&app).is_none()); // The central file, then one file per artboard, named with an underscore. assert_eq!(names(&written), ["/out/Untitled-1.eps", "/out/Untitled-1_Artboard-1.eps", "/out/Untitled-1_Artboard-2.eps"]); assert_eq!(r["files"].as_array().map(Vec::len), Some(3)); let bytes = &written.borrow()[0].1; - let (text, tiff) = vectorcraft_eps::sections(bytes).unwrap(); - assert!(tiff.is_some() && String::from_utf8_lossy(text).contains("%%LanguageLevel: 2")); + let (text_part, tiff) = vectorcraft_eps::sections(bytes).unwrap(); + assert!(tiff.is_some() && String::from_utf8_lossy(text_part).contains("%%LanguageLevel: 2")); assert!(ps(bytes).contains(" rg\n"), "RGB PostScript"); // The next EPS Options start from these choices, but not from this export's path. crate::menus::invoke(&mut app, "ui.epsOptionsDialog", json!({})); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.str("previewFormat"), d.str("level"), d.str("flattenerPreset")), ("tiffBw".into(), "2".into(), "High Resolution".into())); - assert!(!d.bool("cmykPostScript") && !d.fields.contains_key("path")); + let d = fields(&app); + assert_eq!((text(&d, "previewFormat"), text(&d, "level"), text(&d, "flattenerPreset")), ("tiffBw".into(), "2".into(), "High Resolution".into())); + assert!(d.bool("cmykPostScript") != Some(true) && !d.contains("path")); assert!(app.ui.eps_options.get("useArtboards").is_none()); } @@ -54,7 +72,7 @@ fn eps_options_take_saved_flattener_presets_and_refuse_bad_ones() { let (mut app, written) = app(1); app.run("flattener.presets.save", json!({"name": "Mine", "balance": 0})).unwrap(); app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps", "flattenerPreset": "medium"})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("flattenerPreset"), "Medium Resolution", "an id shows as its name"); + assert_eq!(text(&fields(&app), "flattenerPreset"), "Medium Resolution", "an id shows as its name"); frame(&mut app); set(&mut app, "flattenerPreset", json!("Nope")); let e = confirm(&mut app).unwrap_err(); @@ -77,10 +95,9 @@ fn transparent_art(app: &mut VectorcraftApp) { app.run("transparency.set", json!({"opacity": 50})).unwrap(); } -/// Custom… over EPS Options, as its button opens it. +/// Custom… over EPS Options, pressed as the user presses it. fn open_custom(app: &mut VectorcraftApp) { - let parent = app.ui.dialog.clone().expect("EPS Options are open"); - app.ui.dialog = Some(eps_options::over(&parent, &app.session.prefs.flattener_presets)); + press(app, "Custom…"); frame(app); } @@ -89,16 +106,16 @@ fn custom_flattener_options_start_from_the_preset_and_cancel_goes_back_unchanged let (mut app, _) = app(1); app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps", "flattenerPreset": "high"})).unwrap(); frame(&mut app); - let before = app.ui.dialog.as_ref().unwrap().fields.clone(); + let before = as_json(&fields(&app)); open_custom(&mut app); assert_eq!(kind(&app), Some(eps_options::CUSTOM_KIND)); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.f64("balance", 0.0), d.f64("lineArtPpi", 0.0), d.bool("clipComplexRegions")), (100.0, 1200.0, true), "High Resolution's"); - assert!(!d.bool("preserveAlpha"), "EPS has no alpha"); + let d = fields(&app); + assert_eq!((d.number("balance"), d.number("lineArtPpi"), d.bool("clipComplexRegions")), (Some(100.0), Some(1200.0), Some(true)), "High Resolution's"); + assert_ne!(d.bool("preserveAlpha"), Some(true), "EPS has no alpha"); set(&mut app, "balance", json!(10)); cancel(&mut app); assert_eq!(kind(&app), Some("epsOptions")); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields, before, "Cancel leaves EPS Options as they were"); + assert_eq!(as_json(&fields(&app)), before, "Cancel leaves EPS Options as they were"); } #[test] @@ -110,24 +127,25 @@ fn custom_flattener_options_are_exported_and_remembered_until_a_preset_is_chosen app.run("ui.epsOptionsDialog", opts).unwrap(); frame(&mut app); open_custom(&mut app); - assert_eq!(app.ui.dialog.as_ref().unwrap().f64("balance", 0.0), 100.0, "the saved preset's"); + assert_eq!(fields(&app).number("balance"), Some(100.0), "the saved preset's"); set(&mut app, "balance", json!(0)); confirm(&mut app).unwrap(); - assert_eq!(kind(&app), Some("epsOptions"), "OK goes back to EPS Options"); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.fields["flattener"]["balance"].as_f64(), d.fields["flattener"]["preserveAlpha"].as_bool()), (Some(0.0), Some(false))); - assert_eq!(d.str("flattenerPreset"), "Medium Resolution", "a built-in preset under options that set everything"); frame(&mut app); + assert_eq!(kind(&app), Some("epsOptions"), "OK goes back to EPS Options"); + let d = fields(&app); + let custom = flattener(&d); + assert_eq!((custom["balance"].as_f64(), custom["preserveAlpha"].as_bool()), (Some(0.0), Some(false))); + assert_eq!(text(&d, "flattenerPreset"), "Medium Resolution", "a built-in preset under options that set everything"); // The custom options don't need the saved preset they started from. app.run("flattener.presets.delete", json!({"name": "Mine"})).unwrap(); confirm(&mut app).unwrap(); assert!(ps(&written.borrow()[0].1).contains("image"), "balance 0 rasterizes the flattened art"); // The next EPS Options start from them; a preset asked for without options drops them. crate::menus::invoke(&mut app, "ui.epsOptionsDialog", json!({})); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["flattener"]["balance"].as_f64(), Some(0.0)); + assert_eq!(flattener(&fields(&app))["balance"].as_f64(), Some(0.0)); cancel(&mut app); app.run("ui.epsOptionsDialog", json!({"path": "/out/b.eps", "flattenerPreset": "medium"})).unwrap(); - assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("flattener")); + assert!(!fields(&app).contains("flattener")); confirm(&mut app).unwrap(); assert!(!ps(&written.borrow()[1].1).contains("image"), "Medium Resolution keeps the squares vector"); } @@ -140,14 +158,14 @@ fn a_flattener_preset_set_from_outside_drops_the_custom_options() { open_custom(&mut app); set(&mut app, "balance", json!(20)); confirm(&mut app).unwrap(); - assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key("flattener")); + frame(&mut app); + assert!(fields(&app).contains("flattener")); // `ui.dialog.set {flattenerPreset: "low"}`, as the control channel sets it. - let old = app.ui.dialog.as_ref().unwrap().fields.get("flattenerPreset").cloned(); set(&mut app, "flattenerPreset", json!("low")); - field_set(&mut app, "flattenerPreset", old.as_ref()).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert!(!d.fields.contains_key("flattener"), "the preset replaces the custom options"); - assert_eq!(d.str("flattenerPreset"), "Low Resolution"); + frame(&mut app); + let d = fields(&app); + assert!(!d.contains("flattener"), "the preset replaces the custom options"); + assert_eq!(text(&d, "flattenerPreset"), "Low Resolution"); } #[test] @@ -165,8 +183,9 @@ fn bad_custom_flattener_options_keep_the_dialog_open() { set(&mut app, "gradientPpi", json!(150)); set(&mut app, "preserveAlpha", json!(true)); confirm(&mut app).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.fields["flattener"]["preserveOverprints"].as_bool(), d.fields["flattener"]["preserveAlpha"].as_bool()), (Some(true), Some(false))); + frame(&mut app); + let custom = flattener(&fields(&app)); + assert_eq!((custom["preserveOverprints"].as_bool(), custom["preserveAlpha"].as_bool()), (Some(true), Some(false))); } /// Headless frames of the dialog layer with screen-reader output, input events and a clock. @@ -222,76 +241,6 @@ impl Frames { } } -/// Enter on the focused Custom… button opens the custom options and does not also confirm them. -#[test] -fn enter_on_the_custom_button_opens_the_custom_options() { - use egui::accesskit::{Action, ActionRequest, Role, TreeId}; - let (mut app, _) = app(1); - app.run("flattener.presets.save", json!({"name": "Mine", "balance": 0})).unwrap(); - app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps", "flattenerPreset": "Mine"})).unwrap(); - let mut f = Frames::new(); - let (node, _) = f.control(&mut app, "Custom…", Role::Button); - f.run( - &mut app, - vec![egui::Event::AccessKitActionRequest(ActionRequest { action: Action::Focus, target_node: node, target_tree: TreeId::ROOT, data: None })], - ); - let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; - f.run(&mut app, vec![enter(true)]); - f.run(&mut app, vec![enter(false)]); - assert_eq!(kind(&app), Some(eps_options::CUSTOM_KIND), "the custom options stay open"); - let parent = super::parent(app.ui.dialog.as_ref().unwrap()).unwrap(); - assert_eq!(parent.str("flattenerPreset"), "Mine", "EPS Options keep their preset"); -} - -/// With a value out of range, the editor shows the values entered, and changing a switch keeps -/// them, so OK still refuses the bad value. -#[test] -fn a_switch_changed_beside_a_bad_value_keeps_the_values_entered() { - let (mut app, _) = app(1); - app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps"})).unwrap(); - frame(&mut app); - open_custom(&mut app); - set(&mut app, "balance", json!(20)); - set(&mut app, "gradientPpi", json!(9000)); - set(&mut app, "lineArtPpi", json!("many")); - let mut f = Frames::new(); - let (_, at) = f.control(&mut app, "Convert All Text to Outlines", egui::accesskit::Role::CheckBox); - let before = app.ui.dialog.as_ref().unwrap().bool("textToOutlines"); - f.click(&mut app, at); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.bool("textToOutlines"), !before, "the switch changes"); - assert_eq!((d.f64("balance", 0.0), d.f64("gradientPpi", 0.0)), (20.0, 9000.0), "the other values stay as entered"); - assert_eq!(d.fields["lineArtPpi"], json!("many"), "a value of the wrong type stays to be refused"); - assert!(confirm(&mut app).is_err()); - set(&mut app, "lineArtPpi", json!(300)); - assert!(confirm(&mut app).unwrap_err().contains("resolutions")); -} - -/// A value of the wrong type shows blank, and typing the default preset's value into its field -/// replaces it, so OK takes the options. -#[test] -fn the_default_value_typed_over_a_value_of_the_wrong_type_replaces_it() { - let (mut app, _) = app(1); - app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps"})).unwrap(); - frame(&mut app); - open_custom(&mut app); - set(&mut app, "lineArtPpi", json!("many")); - let default = vectorcraft_engine::cmd::FlattenOptions::default().line_art_ppi; - let mut f = Frames::new(); - f.type_into(&mut app, "Line Art and Text Resolution:", &default.to_string()); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["lineArtPpi"], json!(default)); - confirm(&mut app).unwrap(); - assert_eq!(kind(&app), Some("epsOptions")); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["flattener"]["lineArtPpi"].as_f64(), Some(default)); -} - -#[test] -fn the_eps_options_dialog_needs_a_document() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - assert!(app.run("ui.epsOptionsDialog", json!({})).is_err()); - assert!(!crate::menus::enabled(&app, "ui.epsOptionsDialog")); -} - /// Opening an EPS file whose PostScript reads only partly says why, in the status bar and in /// `file.open`'s result (what `app.open` and MCP's `open_file` return): the error, the operator /// and the procedure it ran in. diff --git a/crates/ui-egui/src/dialogs/tests_hpgl.rs b/crates/ui-egui/src/dialogs/tests_hpgl.rs index 45e1075260..c037866e80 100644 --- a/crates/ui-egui/src/dialogs/tests_hpgl.rs +++ b/crates/ui-egui/src/dialogs/tests_hpgl.rs @@ -2,35 +2,48 @@ //! curve tolerance, origin, pens, path order), remembered for the next export, and one plot per //! artboard with Use Artboards. +use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue}; use serde_json::json; use vectorcraft_engine::cmd::fileio; -use super::tests_export::{app, frame, kind, names, set}; +// PLAN: assumed `fields(&app)` (values of the top hosted dialog) and `press(&mut app, name)` (the control channel's +// click on a control by name, export-w23) in export-w9's helpers. +use super::tests_export::{app, fields, frame, kind, names, press, set}; use super::*; +/// The pen table a dialog holds: null for One Pen per Color. +fn pens(d: &DialogFields) -> serde_json::Value { + d.get("pens").and_then(|v| serde_json::to_value(v).ok()).unwrap_or_default() +} + +fn text(d: &DialogFields, key: &str) -> String { + d.text(key).unwrap_or_default().to_string() +} + #[test] fn export_as_hpgl_shows_hpgl_options_then_writes_and_remembers_them() { let (mut app, written) = app(2); app.run("file.exportAs", json!({"format": "hpgl"})).unwrap(); assert_eq!(kind(&app), Some("exportAs")); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("format"), "hpgl"); + assert_eq!(text(&fields(&app), "format"), "hpgl"); frame(&mut app); confirm(&mut app).unwrap(); assert_eq!(kind(&app), Some("hpglOptions"), "HP-GL Options follow"); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.str("path"), d.str("hpglVersion"), d.str("origin")), ("/out/Untitled-1.plt".into(), "hpgl".into(), "bottomLeft".into())); - assert_eq!((d.f64("curveTolerance", 0.0), d.fields["pens"].is_null(), d.bool("sortPaths"), d.bool("insideFirst")), (0.1, true, false, false)); + let d = fields(&app); + assert_eq!((text(&d, "path"), text(&d, "hpglVersion"), text(&d, "origin")), ("/out/Untitled-1.plt".into(), "hpgl".into(), "bottomLeft".into())); + assert_eq!( + (d.number("curveTolerance"), pens(&d).is_null(), d.bool("sortPaths"), d.bool("insideFirst")), + (Some(0.1), true, Some(false), Some(false)) + ); frame(&mut app); // The defaults write the plot an export with this artboard choice and no HP-GL options writes. - let fields = &app.ui.dialog.as_ref().unwrap().fields; - let choice: serde_json::Map = fields - .iter() + let choice: serde_json::Map = form::json_of(&[], &fields(&app)) + .into_iter() .filter(|(k, _)| ["useArtboards", "range", "artboard", "artboards"].contains(&k.as_str())) - .map(|(k, v)| (k.clone(), v.clone())) .collect(); let plain = fileio::encode(&app.session.active().unwrap().doc, "hpgl", &serde_json::Value::Object(choice)).unwrap(); let r = confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + assert!(kind(&app).is_none()); assert_eq!(r["path"], "/out/Untitled-1.plt"); assert_eq!(written.borrow()[0].1, plain); assert!(plain.starts_with(b"IN;") && plain.ends_with(b"PU;SP0;")); @@ -52,12 +65,12 @@ fn export_as_hpgl_shows_hpgl_options_then_writes_and_remembers_them() { assert!(plot.starts_with("IN;NP4;PC1,255,0,0;PC2,0,0,0;"), "{plot}"); // The next HP-GL Options start from these choices, but not from this export's path. crate::menus::invoke(&mut app, "ui.hpglOptionsDialog", json!({})); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.str("hpglVersion"), d.str("origin"), d.f64("curveTolerance", 0.0)), ("hpgl2".into(), "center".into(), 0.5)); - assert_eq!((d.fields["pens"].clone(), d.bool("sortPaths"), d.bool("insideFirst")), (json!(["#ff0000", "#000000"]), true, true)); - assert!(!d.fields.contains_key("path")); + let d = fields(&app); + assert_eq!((text(&d, "hpglVersion"), text(&d, "origin"), d.number("curveTolerance")), ("hpgl2".into(), "center".into(), Some(0.5))); + assert_eq!((pens(&d), d.bool("sortPaths"), d.bool("insideFirst")), (json!(["#ff0000", "#000000"]), Some(true), Some(true))); + assert!(!d.contains("path")); assert!(app.ui.hpgl_options.get("useArtboards").is_none()); - app.ui.dialog = None; + cancel(&mut app); // One plot per artboard. app.run("file.exportAs", json!({"format": "hpgl"})).unwrap(); @@ -88,7 +101,7 @@ fn bad_hpgl_options_keep_the_dialog_open() { ("artboard", json!(3), "artboard"), ("useArtboards", json!("yes"), "useArtboards"), ] { - let before = app.ui.dialog.as_ref().unwrap().fields.get(field).cloned(); + let before = fields(&app).get(field).and_then(|v| serde_json::to_value(v).ok()); set(&mut app, field, value.clone()); frame(&mut app); let e = confirm(&mut app).unwrap_err(); @@ -111,25 +124,29 @@ fn pen_table_starts_from_the_art_s_pens_and_comes_back() { assert_eq!(automatic.len(), 1, "the ellipse's fill is one pen"); app.run("ui.hpglOptionsDialog", json!({})).unwrap(); let none = || -> Result, String> { Ok(Vec::new()) }; - let d = app.ui.dialog.as_mut().unwrap(); - hpgl_options::set_pen_table(d, true, || Ok(automatic.clone())).unwrap(); - assert_eq!(d.fields["pens"], json!(automatic)); - d.fields.insert("pens".into(), json!(["#00ff00", "#0000ff"])); - hpgl_options::set_pen_table(d, false, none).unwrap(); - assert!(d.fields["pens"].is_null()); + let mut d = fields(&app); + hpgl_options::set_pen_table(&mut d, true, || Ok(automatic.clone())).unwrap(); + assert_eq!(pens(&d), json!(automatic)); + d.set("pens", FieldValue::Json(json!(["#00ff00", "#0000ff"]))); + hpgl_options::set_pen_table(&mut d, false, none).unwrap(); + assert!(pens(&d).is_null()); // The table set aside is not an export option. - assert_eq!(d.fields["__pens"], json!(["#00ff00", "#0000ff"])); - assert!(form::params(d).get("__pens").is_none()); + assert_eq!(serde_json::to_value(d.get("__pens")).unwrap(), json!(["#00ff00", "#0000ff"])); + assert!(form::json_of(&[], &d).get("__pens").is_none()); // Choosing One Pen per Color again keeps the table set aside. - hpgl_options::set_pen_table(d, false, none).unwrap(); - hpgl_options::set_pen_table(d, true, || panic!("the table set aside comes back")).unwrap(); - assert_eq!(d.fields["pens"], json!(["#00ff00", "#0000ff"])); + hpgl_options::set_pen_table(&mut d, false, none).unwrap(); + hpgl_options::set_pen_table(&mut d, true, || panic!("the table set aside comes back")).unwrap(); + assert_eq!(pens(&d), json!(["#00ff00", "#0000ff"])); // Nothing set aside and nothing drawn: one black pen. - d.fields.insert("pens".into(), serde_json::Value::Null); - d.fields.remove("__pens"); - hpgl_options::set_pen_table(d, true, none).unwrap(); - assert_eq!(d.fields["pens"], json!(["#000000"])); + d.set("pens", FieldValue::Json(serde_json::Value::Null)); + d.remove("__pens"); + hpgl_options::set_pen_table(&mut d, true, none).unwrap(); + assert_eq!(pens(&d), json!(["#000000"])); + // The Pen Table button asks the host, which starts the table from the art's pens. frame(&mut app); + press(&mut app, "Pen Table"); + frame(&mut app); + assert_eq!(pens(&fields(&app)), json!(automatic)); } /// Pen Table with options the export refuses keeps One Pen per Color and says why, rather than @@ -138,21 +155,19 @@ fn pen_table_starts_from_the_art_s_pens_and_comes_back() { fn pen_table_with_refused_options_keeps_one_pen_per_color() { let (mut app, _) = app(1); app.run("ui.hpglOptionsDialog", json!({"curveTolerance": 20})).unwrap(); - let d = app.ui.dialog.clone().unwrap(); - let e = hpgl_options::automatic_pens(&app, &d).unwrap_err(); + let mut d = fields(&app); + let e = hpgl_options::automatic_pens(&app, &d, false).unwrap_err(); assert!(e.contains("`curveTolerance`"), "{e}"); - let d = app.ui.dialog.as_mut().unwrap(); - assert_eq!(hpgl_options::set_pen_table(d, true, || Err(e.clone())), Err(e)); - assert!(d.fields["pens"].is_null(), "One Pen per Color stays chosen"); + assert_eq!(hpgl_options::set_pen_table(&mut d, true, || Err(e.clone())), Err(e)); + assert!(pens(&d).is_null(), "One Pen per Color stays chosen"); frame(&mut app); // With the tolerance corrected, Pen Table starts from the art's pen. set(&mut app, "curveTolerance", json!(0.1)); - let d = app.ui.dialog.clone().unwrap(); - let pens = hpgl_options::automatic_pens(&app, &d).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - hpgl_options::set_pen_table(d, true, || Ok(pens.clone())).unwrap(); - assert_eq!(d.fields["pens"], json!(pens)); - assert_eq!(pens.len(), 1, "the ellipse's fill is one pen"); + let mut d = fields(&app); + let found = hpgl_options::automatic_pens(&app, &d, false).unwrap(); + hpgl_options::set_pen_table(&mut d, true, || Ok(found.clone())).unwrap(); + assert_eq!(pens(&d), json!(found)); + assert_eq!(found.len(), 1, "the ellipse's fill is one pen"); } /// Export Selection to HP-GL checks, lists the pens of and writes the selection alone, and the next @@ -167,18 +182,18 @@ fn export_selection_to_hpgl_uses_the_selection_and_is_not_remembered() { app.services.pick_save = Some(Box::new(|_: &crate::FilePick| Some("/out/sel.plt".to_string()))); app.run("document.exportSelection", json!({})).unwrap(); assert_eq!(kind(&app), Some("hpglOptions")); - let d = app.ui.dialog.clone().unwrap(); - assert!(d.bool(export_as::SELECTION_FIELD) && !d.fields.contains_key(crate::io::EXPORT_SELECTION)); - assert_eq!(hpgl_options::automatic_pens(&app, &d).unwrap(), ["#0000ff"], "the selection's pen only"); + let d = fields(&app); + assert!(!d.contains(crate::io::EXPORT_SELECTION)); + assert_eq!(hpgl_options::automatic_pens(&app, &d, true).unwrap(), ["#0000ff"], "the selection's pen only"); // An artboard choice the whole document would refuse is not this export's. set(&mut app, "artboard", json!(5)); frame(&mut app); confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + assert!(kind(&app).is_none()); assert_eq!(names(&written), ["/out/sel.plt"]); let plot = String::from_utf8_lossy(&written.borrow()[0].1).into_owned(); assert_eq!(plot.matches("PD").count(), 1, "the rectangle alone: {plot}"); - assert!(app.ui.hpgl_options.get(export_as::SELECTION_FIELD).is_none()); + assert!(app.ui.hpgl_options.get(crate::io::EXPORT_SELECTION).is_none()); // A selection export asked for by its param is not remembered either. app.run("ui.hpglOptionsDialog", json!({"path": "/out/b.plt", "exportSelection": true})).unwrap(); confirm(&mut app).unwrap(); @@ -200,7 +215,7 @@ fn a_canceled_save_panel_keeps_hpgl_options_open() { frame(&mut app); assert!(confirm(&mut app).is_err()); assert_eq!(kind(&app), Some("hpglOptions")); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("origin"), "bottomLeft"); + assert_eq!(text(&fields(&app), "origin"), "bottomLeft"); assert_eq!(app.ui.hpgl_options, json!({"origin": "center"})); assert!(written.borrow().is_empty()); app.services.pick_save = Some(Box::new(|_: &crate::FilePick| Some("/out/d.plt".to_string()))); @@ -248,7 +263,7 @@ fn pen_table_starts_from_the_pens_of_what_the_export_plots() { frame(&mut app); confirm(&mut app).unwrap(); assert_eq!(kind(&app), Some("hpglOptions")); - let seed = |app: &VectorcraftApp| hpgl_options::automatic_pens(app, app.ui.dialog.as_ref().unwrap()).unwrap(); + let seed = |app: &VectorcraftApp| hpgl_options::automatic_pens(app, &fields(app), false).unwrap(); assert_eq!(seed(&app), [on_board[0].as_str(), "#0000ff"], "the art's bounds"); // The rectangle is the selection. set(&mut app, "selectedOnly", json!(true)); @@ -266,8 +281,8 @@ fn hpgl_options_write_nothing_after_another_document_became_active() { app.run("ui.hpglOptionsDialog", json!({"path": "/out/first.plt"})).unwrap(); app.run("file.new", json!({"width": 60, "height": 40})).unwrap(); assert_eq!(kind(&app), Some("hpglOptions")); - assert_eq!(confirm(&mut app).unwrap(), json!({})); - assert!(app.ui.dialog.is_none()); + confirm(&mut app).unwrap(); + assert!(kind(&app).is_none()); assert!(written.borrow().is_empty(), "nothing is written over the first document's path"); // Opened for the document that is active, OK writes it. app.run("window.nextDocument", json!({})).unwrap(); @@ -275,10 +290,3 @@ fn hpgl_options_write_nothing_after_another_document_became_active() { confirm(&mut app).unwrap(); assert_eq!(names(&written), ["/out/first.plt"]); } - -#[test] -fn the_hpgl_options_dialog_needs_a_document() { - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - assert!(app.run("ui.hpglOptionsDialog", json!({})).is_err()); - assert!(!crate::menus::enabled(&app, "ui.hpglOptionsDialog")); -}