diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index ae70d682c4..48bcc59657 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -6,6 +6,10 @@ //! are `document.export` params (format, path, artboard choice…); `__`-prefixed ones are the //! dialog's. +use craft_ui::contract::Bind; +use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft_ui::text::NumberField; +use craft_ui::value_drag::SliderScale; use serde::Deserialize; use serde_json::{Map, Value, json}; use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, Format}; @@ -13,13 +17,11 @@ use vectorcraft_render::AntiAlias; use vectorcraft_render::encode::jpeg::{self, ColorModel, Method}; use vectorcraft_render::encode::quantize::{Dither, PaletteOptions, Reduction}; -use super::{DialogSpec, form, psd_options, tiff_bmp_tga}; -use crate::state::Dialog; -use crate::theme::Tokens; -use crate::{VectorcraftApp, io, widgets}; - -pub(super) const SPEC: DialogSpec = - DialogSpec { heading, body, confirm, ok: Some("Export"), min_width: 360.0, inputs: |_| &["path"], ..DialogSpec::FORM }; +use super::export_host::{self, After, Export, Open}; +// PLAN: assumed `form::{fields_of, json_of}` (wg.S12, widgets-w12) live in `dialogs::form`. +use super::form::{fields_of, json_of}; +use super::{psd_options, tiff_bmp_tga}; +use crate::{VectorcraftApp, io}; /// Resolution presets (pixels per inch). pub(super) const RESOLUTIONS: [f64; 3] = [72.0, 150.0, 300.0]; @@ -32,8 +34,6 @@ const BACKGROUND_LABELS: [&str; 4] = ["Transparent", "White", "Black", "Other"]; /// JPEG image map param values and their labels. const IMAGE_MAPS: [&str; 3] = ["none", "client", "server"]; const IMAGE_MAP_LABELS: [&str; 3] = ["None", "Client-side (.html)", "Server-side (.map)"]; -/// Palette sizes offered (any 2–256 can be typed). -const COLOR_COUNTS: [&str; 8] = ["2", "4", "8", "16", "32", "64", "128", "256"]; /// Matte param values and their labels (`Other`: a colour). const MATTES: [&str; 3] = ["none", "white", "black"]; const MATTE_LABELS: [&str; 4] = ["None", "White", "Black", "Other"]; @@ -43,6 +43,10 @@ const QUALITY_BANDS: [&str; 11] = ["Low", "Low", "Low", "Medium", "Medium", "Med const WEBP_COMPRESSION_LABELS: [&str; 2] = ["Lossless", "Lossy"]; /// The lossy WebP quality a new export starts with (0–100). const WEBP_QUALITY: u8 = 90; +/// The colour a colour choice's `Other` starts from. +const OTHER_COLOR: &str = "#808080"; +/// Params the engine reads as whole numbers; a row may hold them as floats or as option ids. +const INTEGER_KEYS: [&str; 5] = ["quality", "scans", "colors", "ditherAmount", "depth"]; /// The dialog kind of a raster format (`pngOptions`, `jpgOptions`, `webpOptions`, `gifOptions`, /// `png8Options`). @@ -50,14 +54,14 @@ fn kind(f: &Format) -> String { format!("{}Options", f.id) } -fn format_of(d: &Dialog) -> Option<&'static Format> { - fileio::format(d.kind.strip_suffix("Options")?) -} - /// Open the options of raster format `f` for an export whose params (format, path, artboard /// choice) are `params`. -pub fn open(app: &mut VectorcraftApp, f: &Format, mut params: Value) { - let selection = params[super::export_as::SELECTION_FIELD] == true; +pub fn open(app: &mut VectorcraftApp, f: &Format, params: Value) { + open_with(app, f, params, false); +} + +/// [`open`] for Export Selection when `selection`: the size shown is the selection's crop. +pub(crate) fn open_with(app: &mut VectorcraftApp, f: &Format, mut params: Value, selection: bool) { let size = app.session.active().and_then(|st| match selection { true => vectorcraft_engine::cmd::fileio::selection_doc(st, "document.exportSelection", false).ok().map(|(_, r)| (r.width(), r.height())), false => export_size(&st.doc, ¶ms), @@ -74,7 +78,23 @@ pub fn open(app: &mut VectorcraftApp, f: &Format, mut params: Value) { o.insert("__size".into(), json!([w, h])); } } - app.ui.dialog = Some(Dialog::new(&kind(f), params)); + let Some(ctx) = app.ui_ctx.clone() else { return }; + let size = size.map(|(w, h)| [w, h]); + let (id, label, key) = (f.id, f.label, kind(f)); + let map = params.as_object().cloned().unwrap_or_default(); + let initial = fields_of(&raster_rows(id, false, size, &DialogFields::new()), &map); + let build = { + let key = key.clone(); + move |fields: &mut DialogFields| { + normalize_colors(fields); + if id == "bmp" { + tiff_bmp_tga::normalize_bmp(fields); + } + ParamDialog::new(key.clone(), heading(label), raster_rows(id, false, size, fields)).values(Bind::bound(fields)).ok_label(tl!("Export")) + } + }; + let dialog = HostedParamDialog::new(&ctx, key, initial, build); + export_host::open(app, Export::Raster { format: id }, selection, dialog); } /// The options raster format `f` starts with (after the resolution): the document's background @@ -132,7 +152,7 @@ fn export_size(doc: &vectorcraft_doc::Document, p: &Value) -> Option<(f64, f64)> Some(false) => vectorcraft_render::encode::art_bounds(doc)?, Some(true) => match pick.resolve(n).ok()?.as_deref() { Some([i]) => doc.artboards.get(*i)?.rect, - None if n == 1 => doc.artboards[0].rect, + None if n == 1 => doc.artboards.first()?.rect, _ => return None, }, None => doc.artboards.get(pick.one(n).ok()?)?.rect, @@ -140,241 +160,226 @@ fn export_size(doc: &vectorcraft_doc::Document, p: &Value) -> Option<(f64, f64)> Some((r.width(), r.height())) } -fn heading(d: &Dialog) -> String { - crate::i18n::fmt(tl!("{format} Options"), &[("format", format_of(d).map_or(tl!("Export"), |f| f.label))]) +fn heading(label: &str) -> String { + crate::i18n::fmt(tl!("{format} Options"), &[("format", label)]) } -fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let t = Tokens::get(ui.ctx()); - let id = format_of(d).map_or("png", |f| f.id); - let label = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(tl!(text)).color(t.text_dim)); - egui::Grid::new("raster-options").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| { - label(ui, tl!("Resolution:")); - let ppi = d.f64("ppi", 72.0); - let preset = RESOLUTIONS.iter().position(|p| *p == ppi).filter(|_| !d.bool("__otherPpi")); - ui.horizontal(|ui| { - if let Some(i) = widgets::dropdown(ui, "ro-ppi", RESOLUTION_LABELS[preset.unwrap_or(3)], &RESOLUTION_LABELS, 150.0) { - if let Some(p) = RESOLUTIONS.get(i) { - d.fields.insert("ppi".into(), json!(p)); - } - d.fields.insert("__otherPpi".into(), json!(i == 3)); - } - if preset.is_none() - && let Some(v) = widgets::range_field(ui, "ro-ppi-other", ppi, 1.0..=4608.0, &super::ppi_suffix(), 0, 80.0) - { - d.fields.insert("ppi".into(), json!(v)); - } - }); - ui.end_row(); - - option_rows(ui, d, id, false); - - if let Some([w, h]) = - d.fields.get("__size").and_then(Value::as_array).map(|a| [0, 1].map(|i| a.get(i).and_then(Value::as_f64).unwrap_or(0.0))) - { - label(ui, tl!("Size:")); - let (pw, ph) = vectorcraft_render::region_pixels(vectorcraft_geom::Rect::new(0.0, 0.0, w, h), d.f64("ppi", 72.0) / 72.0); - ui.label(egui::RichText::new(format!("{pw} × {ph} px")).color(t.text)); - ui.end_row(); - } - }); - false +/// The rows of raster format `id`'s options: resolution, the size it gives, background, +/// anti-aliasing and the format's own. `screens` (Export for Screens' Format Settings) leaves out +/// what its rows choose (JPEG quality) and what writes other files (image maps). `size` is the +/// region's size in points, when one region is exported. +pub(crate) fn raster_params(id: &str, screens: bool, size: Option<[f64; 2]>) -> Vec { + raster_rows(id, screens, size, &DialogFields::new()) } -/// The grid rows of raster format `id`'s options after the resolution: background, anti-aliasing -/// and the format's own. `screens` (Export for Screens' Format Settings) leaves out what its rows -/// choose (JPEG quality) and what writes other files (image maps). -pub(super) fn option_rows(ui: &mut egui::Ui, d: &mut Dialog, id: &str, screens: bool) { - let t = Tokens::get(ui.ctx()); - let label = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(tl!(text)).color(t.text_dim)); - label(ui, tl!("Background Color:")); - let bg = d.str("background"); - let choice = BACKGROUNDS.iter().position(|v| bg.eq_ignore_ascii_case(v)).unwrap_or(3); +/// [`raster_params`] for a dialog whose rows depend on its values (BMP's palette rows). +fn raster_rows(id: &str, screens: bool, size: Option<[f64; 2]>, fields: &DialogFields) -> Vec { + let mut rows = vec![resolution_row()]; + if let Some([w, h]) = size { + rows.push(size_row(w, h)); + } // JPEG has no transparency, nor have some TIFF, BMP and Targa options: their list starts at // White, which is what transparent becomes. - let first = usize::from(!tiff_bmp_tga::keeps_alpha(id, d)); - ui.horizontal(|ui| { - if let Some(i) = widgets::dropdown(ui, "ro-bg", BACKGROUND_LABELS[choice.max(first)], &BACKGROUND_LABELS[first..], 150.0) { - let value = BACKGROUNDS.get(i + first).copied().unwrap_or("#808080"); - d.fields.insert("background".into(), json!(value)); - } - if choice == 3 { - color_button(ui, d, "background"); - } - }); - ui.end_row(); - - label(ui, tl!("Anti-aliasing:")); - let aa = AntiAlias::from_id(&d.str("antiAlias")).unwrap_or_default(); - if let Some(i) = widgets::dropdown(ui, "ro-aa", aa.label(), &AntiAlias::ALL.map(AntiAlias::label), 150.0) { - d.fields.insert("antiAlias".into(), json!(AntiAlias::ALL[i].id())); - } - ui.end_row(); - + let format = id.to_string(); + rows.push(color_choice("background", tl!("Background Color:"), &BACKGROUNDS, &BACKGROUND_LABELS, move |f| { + usize::from(!tiff_bmp_tga::keeps_alpha(&format, f)) + })); + rows.push(choice("antiAlias", tl!("Anti-aliasing:"), &AntiAlias::ALL.map(AntiAlias::id), &AntiAlias::ALL.map(AntiAlias::label))); match id { - "png" => { - ui.label(""); - form::check(ui, d, "interlaced", tl!("Interlaced")); - ui.end_row(); + "png" => rows.push(check("interlaced", tl!("Interlaced"), false)), + "jpg" => rows.extend(jpeg_rows(screens)), + "gif" | "png8" => rows.extend(palette_rows()), + "webp" => rows.extend(webp_rows()), + "psd" => rows.extend(psd_options::params()), + id => rows.extend(tiff_bmp_tga::params(id, fields)), + } + rows +} + +/// A dropdown row bound to `key`: one of `ids`, shown by its label. +pub(super) fn choice(key: &str, label: &str, ids: &[impl AsRef], labels: &[&str]) -> Param { + let options = ids.iter().zip(labels).map(|(id, l)| (id.as_ref().to_string(), tl!(*l).into())).collect(); + Param::new(key, tl!(label), ParamKind::choice(options, ids.first().map(|id| id.as_ref().to_string()))) +} + +/// A check box row bound to `key`. +pub(super) fn check(key: &str, label: &str, default: bool) -> Param { + Param::new(key, tl!(label), ParamKind::bool(default)) +} + +/// Resolution: a preset, or Other with a field of its own (`__otherPpi` marks Other, so a typed +/// 72 stays Other). +fn resolution_row() -> Param { + Param::custom("ppi", tl!("Resolution:"), |ui, fields, _| { + let ppi = fields.number("ppi").unwrap_or(72.0); + let preset = RESOLUTIONS.iter().position(|p| *p == ppi).filter(|_| fields.bool("__otherPpi") != Some(true)); + let shown = preset.unwrap_or(RESOLUTION_LABELS.len() - 1); + ui.horizontal(|ui| { + craft_ui::ComboBox::from_id_salt("ro-ppi").selected_text(tl!(RESOLUTION_LABELS.get(shown).copied().unwrap_or_default())).show_ui( + ui, + |ui| { + for (i, label) in RESOLUTION_LABELS.iter().enumerate() { + if ui.selectable_label(i == shown, tl!(*label)).clicked() { + if let Some(p) = RESOLUTIONS.get(i) { + fields.set("ppi", *p); + } + fields.set("__otherPpi", i == RESOLUTION_LABELS.len() - 1); + } + } + }, + ); + if preset.is_none() { + let field = NumberField::new(tl!("Resolution:"), Bind::given(Some(ppi))).range(1.0..=4608.0).step(1.0).unit(super::ppi_suffix()).show(ui); + if let Some(Some(v)) = field.value().copied() { + fields.set("ppi", v); + } + } + }) + .response + }) + .companions(["__otherPpi"]) + .opens_with(72.0) +} + +/// The pixel size the region of `w` × `h` points gives at the current resolution. +fn size_row(w: f64, h: f64) -> Param { + Param::custom("__sizeText", tl!("Size:"), move |ui, fields, _| { + let (pw, ph) = vectorcraft_render::region_pixels(vectorcraft_geom::Rect::new(0.0, 0.0, w, h), fields.number("ppi").unwrap_or(72.0) / 72.0); + ui.label(format!("{pw} × {ph} px")) + }) +} + +/// A colour row: one of `ids` shown by its label, or Other (the last label) with a swatch that +/// asks the host's colour picker. The value is an id or `"#rrggbb"`. `first` is where the list +/// starts for the current values. +fn color_choice( + key: &'static str, + label: &'static str, + ids: &'static [&'static str], + labels: &'static [&'static str], + first: impl Fn(&DialogFields) -> usize + Send + Sync + 'static, +) -> Param { + Param::custom(key, tl!(label), move |ui, fields, cx| { + let current = fields.text(key).unwrap_or_default().to_string(); + let at = ids.iter().position(|v| current.eq_ignore_ascii_case(v)).unwrap_or(ids.len()); + let start = first(fields); + let shown = at.max(start); + ui.horizontal(|ui| { + craft_ui::ComboBox::from_id_salt(("ro", key)).selected_text(tl!(labels.get(shown).copied().unwrap_or_default())).show_ui(ui, |ui| { + for (i, l) in labels.iter().enumerate().skip(start) { + if ui.selectable_label(i == shown, tl!(*l)).clicked() { + fields.set(key, ids.get(i).copied().unwrap_or(OTHER_COLOR)); + } + } + }); + if at == ids.len() { + let c = vectorcraft_color::Color::from_hex(¤t).map_or([128, 128, 128, 255], |c| c.to_rgba8(1.0)); + let (rect, response) = ui.allocate_exact_size(egui::vec2(28.0, 18.0), egui::Sense::click()); + ui.painter().rect_filled(rect, 2.0, egui::Color32::from_rgb(c[0], c[1], c[2])); + if response.clicked() { + cx.pick_color(key, craft::theme::Srgba::rgb(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0)); + } + } + }) + .response + }) +} + +/// The picker answers a colour row with a colour value; the dialog keeps one representation, the +/// `"#rrggbb"` text the export reads. +fn normalize_colors(fields: &mut DialogFields) { + for key in ["background", "matte"] { + if let Some([r, g, b]) = fields.color(key) { + let to8 = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8; + fields.set(key, format!("#{:02x}{:02x}{:02x}", to8(r), to8(g), to8(b))); } - "jpg" => jpeg_rows(ui, d, &label, screens), - "gif" | "png8" => palette_rows(ui, d, &label), - "webp" => webp_rows(ui, d, &label), - "psd" => psd_options::rows(ui, d, &label), - id => tiff_bmp_tga::rows(ui, d, id, &label), } } /// The JPEG Options rows: colour model, quality, method and scans, profile and image map (not /// quality and image map for Export for Screens). -fn jpeg_rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response, screens: bool) { - label(ui, tl!("Color Model:")); - choice(ui, d, "colorModel", &ColorModel::ALL.map(ColorModel::id), &ColorModel::ALL.map(ColorModel::label)); - ui.end_row(); - +fn jpeg_rows(screens: bool) -> Vec { + let mut rows = vec![choice("colorModel", tl!("Color Model:"), &ColorModel::ALL.map(ColorModel::id), &ColorModel::ALL.map(ColorModel::label))]; if !screens { - quality_row(ui, d, label); + rows.push(quality_row()); } - method_row(ui, d, label); + rows.push(choice("method", tl!("Method:"), &Method::ALL.map(Method::id), &Method::ALL.map(Method::label))); + let scans = ParamKind::int(Some(i64::from(*jpeg::SCANS.start())), Some(i64::from(*jpeg::SCANS.end())), 3); + rows.push(Param::new("scans", tl!("Scans:"), scans).visible_when("method", Method::Progressive.id())); if !screens { - label(ui, tl!("Image Map:")); - choice(ui, d, "imageMap", &IMAGE_MAPS, &IMAGE_MAP_LABELS); - ui.end_row(); + rows.push(choice("imageMap", tl!("Image Map:"), &IMAGE_MAPS, &IMAGE_MAP_LABELS)); } - - ui.label(""); - form::check(ui, d, "embedIcc", tl!("Embed ICC Profile")); - ui.end_row(); + rows.push(check("embedIcc", tl!("Embed ICC Profile"), true)); + rows } /// JPEG quality on the dialog's 0–10 scale (stored ×10). -fn quality_row(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) { - label(ui, tl!("Quality:")); - let mut q = (d.f64("quality", 90.0) / 10.0).round().clamp(0.0, 10.0) as u8; - ui.horizontal(|ui| { - if widgets::slider(ui, egui::Slider::new(&mut q, 0..=10)).changed() { - d.fields.insert("quality".into(), json!(u32::from(q) * 10)); - } - label(ui, QUALITY_BANDS[q as usize]); - }); - ui.end_row(); +fn quality_row() -> Param { + Param::custom("quality", tl!("Quality:"), |ui, fields, _| { + let mut q = (fields.number("quality").unwrap_or(90.0) / 10.0).round().clamp(0.0, 10.0) as u8; + ui.horizontal(|ui| { + if ui.add(egui::Slider::new(&mut q, 0..=10)).changed() { + fields.set("quality", f64::from(q) * 10.0); + } + ui.label(tl!(QUALITY_BANDS.get(usize::from(q)).copied().unwrap_or_default())); + }) + .response + }) + .opens_with(90.0) } /// The WebP Options rows: Lossless or Lossy compression, and the quality 0–100 that Lossy uses -/// (dimmed while Lossless is chosen, keeping its value). -fn webp_rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) { - label(ui, tl!("Compression:")); - let lossless = d.fields.get("lossless").and_then(Value::as_bool).unwrap_or(true); - if let Some(i) = widgets::dropdown(ui, "ro-webp", WEBP_COMPRESSION_LABELS[usize::from(!lossless)], &WEBP_COMPRESSION_LABELS, 150.0) { - d.fields.insert("lossless".into(), json!(i == 0)); - } - ui.end_row(); - - label(ui, tl!("Quality:")); - let mut q = d.f64("quality", f64::from(WEBP_QUALITY)).round().clamp(0.0, 100.0) as u8; - ui.add_enabled_ui(!lossless, |ui| { - if widgets::slider(ui, egui::Slider::new(&mut q, 0..=100)).changed() { - d.fields.insert("quality".into(), json!(q)); - } - }); - ui.end_row(); -} - -/// The JPEG method, and its scans when progressive. -fn method_row(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) { - label(ui, tl!("Method:")); - ui.horizontal(|ui| { - choice(ui, d, "method", &Method::ALL.map(Method::id), &Method::ALL.map(Method::label)); - if Method::from_id(&d.str("method")) == Some(Method::Progressive) { - label(ui, tl!("Scans:")); - let range = f64::from(*jpeg::SCANS.start())..=f64::from(*jpeg::SCANS.end()); - if let Some(scans) = widgets::range_field(ui, "scans", d.f64("scans", 3.0), range, "", 0, 44.0) { - d.fields.insert("scans".into(), json!(scans as u8)); - } - } - }); - ui.end_row(); +/// (disabled while Lossless is chosen, keeping its value). +fn webp_rows() -> Vec { + let [lossless, lossy] = WEBP_COMPRESSION_LABELS; + let compression = ParamKind::radio(vec![("true".into(), tl!(lossless).into()), ("false".into(), tl!(lossy).into())], Some("true".into())); + vec![ + Param::new("lossless", tl!("Compression:"), compression), + Param::new("quality", tl!("Quality:"), ParamKind::range(0.0, 100.0, f64::from(WEBP_QUALITY), SliderScale::Linear)).enabled_when("lossless", "false"), + ] } /// The PNG-8 and GIF Options rows: the palette (reduction, colours, dither and amount), /// transparency and matte, interlacing. -fn palette_rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) { - label(ui, tl!("Color Reduction:")); - choice(ui, d, "reduction", &Reduction::ALL.map(Reduction::id), &Reduction::ALL.map(Reduction::label)); - ui.end_row(); - - label(ui, tl!("Colors:")); - let mut n = d.f64("colors", 256.0).round().clamp(2.0, 256.0) as u16; - ui.horizontal(|ui| { - if let Some(i) = widgets::dropdown(ui, "ro-colors", &n.to_string(), &COLOR_COUNTS, 70.0) { - n = COLOR_COUNTS.get(i).and_then(|c| c.parse().ok()).unwrap_or(n); - d.fields.insert("colors".into(), json!(n)); - } - if let Some(n) = widgets::range_field(ui, "colors", f64::from(n), 2.0..=256.0, "", 0, 52.0) { - d.fields.insert("colors".into(), json!(n as u16)); - } - }); - ui.end_row(); - - label(ui, tl!("Dither:")); - ui.horizontal(|ui| { - choice(ui, d, "dither", &Dither::ALL.map(Dither::id), &Dither::ALL.map(Dither::label)); - if Dither::from_id(&d.str("dither")).is_some_and(|x| x != Dither::None) - && let Some(amount) = widgets::range_field(ui, "ditherAmount", d.f64("ditherAmount", 100.0), 0.0..=100.0, "%", 0, 52.0) - { - d.fields.insert("ditherAmount".into(), json!(amount as u8)); - } - }); - ui.end_row(); - - label(ui, tl!("Matte:")); - let matte = d.str("matte"); - let at = MATTES.iter().position(|v| matte.eq_ignore_ascii_case(v)).unwrap_or(3); - ui.horizontal(|ui| { - if let Some(i) = widgets::dropdown(ui, "ro-matte", MATTE_LABELS[at], &MATTE_LABELS, 150.0) { - d.fields.insert("matte".into(), json!(MATTES.get(i).copied().unwrap_or("#808080"))); - } - if at == 3 { - color_button(ui, d, "matte"); - } - }); - ui.end_row(); - - ui.label(""); - ui.horizontal(|ui| { - form::check(ui, d, "transparency", tl!("Transparency")); - form::check(ui, d, "interlaced", tl!("Interlaced")); - }); - ui.end_row(); +fn palette_rows() -> Vec { + let dithering = Dither::ALL.iter().copied().filter(|d| *d != Dither::None).map(Dither::id); + vec![ + choice("reduction", tl!("Color Reduction:"), &Reduction::ALL.map(Reduction::id), &Reduction::ALL.map(Reduction::label)), + Param::new("colors", tl!("Colors:"), ParamKind::int(Some(2), Some(256), 256)), + choice("dither", tl!("Dither:"), &Dither::ALL.map(Dither::id), &Dither::ALL.map(Dither::label)), + Param::new("ditherAmount", tl!("Dither Amount:"), ParamKind::int(Some(0), Some(100), 100)).enabled_when_in("dither", dithering), + color_choice("matte", tl!("Matte:"), &MATTES, &MATTE_LABELS, |_| 0), + check("transparency", tl!("Transparency"), true), + check("interlaced", tl!("Interlaced"), false), + ] } -/// A colour button bound to `d.fields[key]` (`"#rrggbb"`; grey when unset). -pub(super) fn color_button(ui: &mut egui::Ui, d: &mut Dialog, key: &str) { - let c = vectorcraft_color::Color::from_hex(&d.str(key)).map_or([128, 128, 128, 255], |c| c.to_rgba8(1.0)); - let mut rgb = [c[0], c[1], c[2]]; - if ui.color_edit_button_srgb(&mut rgb).changed() { - d.fields.insert(key.into(), json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]))); - } -} - -/// A dropdown bound to `d.fields[key]`: one of `ids`, shown by its label (the first when unknown). -pub(super) fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, ids: &[&str], labels: &[&str]) { - let cur = d.str(key); - let at = ids.iter().position(|v| v.eq_ignore_ascii_case(&cur)).unwrap_or(0); - if let Some(i) = widgets::dropdown(ui, ("ro", key), labels.get(at).copied().unwrap_or_default(), labels, 150.0) - && let Some(v) = ids.get(i) - { - d.fields.insert(key.into(), json!(v)); +/// Whole-number params the rows hold as floats or option ids are written as integers, as the +/// export reads them. +fn integers(params: &mut Value) { + let Some(o) = params.as_object_mut() else { return }; + for key in INTEGER_KEYS { + let number = match o.get(key) { + Some(Value::String(text)) => text.parse::().ok(), + Some(Value::Number(n)) => n.as_f64().filter(|_| !n.is_u64() && !n.is_i64()), + _ => None, + }; + if let Some(n) = number.filter(|n| n.is_finite() && n.fract() == 0.0 && *n >= 0.0) { + o.insert(key.into(), json!(n as u64)); + } } } /// Write the file(s) with the chosen options. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let (format, path) = (d.str("format"), d.str("path")); - app.ui.dialog = None; - let mut params = form::params(d); +pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result { + let format = fields.text("format").unwrap_or_default().to_string(); + let path = fields.text("path").unwrap_or_default().to_string(); + let id = fileio::format(&format).map_or("png", |f| f.id); + let mut params = Value::Object(json_of(&raster_rows(id, false, None, fields), fields)); + integers(&mut params); if format == "psd" { psd_options::drop_unused(&mut params); } - io::export(app, Some(&format), Some(path), &super::export_as::exported(d, params)) + // PLAN: assumed `After: From` (the export's result, what ex.A1's `confirm` hands the host). + io::export(app, Some(&format), Some(path), &super::export_as::exported(open.selection, params)).map(After::from) } diff --git a/crates/ui-egui/src/dialogs/psd_options.rs b/crates/ui-egui/src/dialogs/psd_options.rs index 68aad6bf58..b79731a171 100644 --- a/crates/ui-egui/src/dialogs/psd_options.rs +++ b/crates/ui-egui/src/dialogs/psd_options.rs @@ -2,13 +2,12 @@ //! Editability, hidden layers, profile), after the raster export rows it shares with PNG Options ([`super::png_options`]): the //! `psdOptions` dialog. +use craft_ui::patterns::form_dialogs::{Param, ParamKind}; use serde_json::{Map, Value, json}; use vectorcraft_render::encode::jpeg::ColorModel; use vectorcraft_render::encode::psd::PsdOptions; -use super::form; -use super::png_options::choice; -use crate::state::Dialog; +use super::png_options::{check, choice}; /// The options PSD starts with (`cmyk`: a CMYK document exports CMYK). pub(super) fn defaults(cmyk: bool, o: &mut Map) { @@ -34,34 +33,15 @@ pub(super) fn drop_unused(p: &mut Value) { } } -/// The grid rows of PSD's own options. -pub(super) fn rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) { - label(ui, tl!("Color Model:")); - choice(ui, d, "colorModel", &ColorModel::ALL.map(ColorModel::id), &ColorModel::ALL.map(ColorModel::label)); - ui.end_row(); - - label(ui, tl!("Options:")); - ui.vertical(|ui| { - let mut layers = d.bool("layers"); - if ui.radio_value(&mut layers, false, tl!("Flat Image")).changed() | ui.radio_value(&mut layers, true, tl!("Write Layers")).changed() { - d.fields.insert("layers".into(), json!(layers)); - } - ui.add_enabled_ui(layers, |ui| { - for (key, text) in [ - ("preserveText", tl!("Preserve Text Editability")), - ("maxEditability", tl!("Maximum Editability")), - ("hiddenLayers", tl!("Include Hidden Layers")), - ] { - ui.horizontal(|ui| { - ui.add_space(22.0); - form::check(ui, d, key, text); - }); - } - }); - }); - ui.end_row(); - - ui.label(""); - form::check(ui, d, "embedIcc", tl!("Embed ICC Profile")); - ui.end_row(); +/// The rows of PSD's own options. `layers` is a two-id radio, so the export sees a boolean. +pub(super) fn params() -> Vec { + let layers = ParamKind::radio(vec![("false".into(), tl!("Flat Image").into()), ("true".into(), tl!("Write Layers").into())], Some("true".into())); + vec![ + choice("colorModel", tl!("Color Model:"), &ColorModel::ALL.map(ColorModel::id), &ColorModel::ALL.map(ColorModel::label)), + Param::new("layers", tl!("Options:"), layers), + check("preserveText", tl!("Preserve Text Editability"), false).enabled_when("layers", "true"), + check("maxEditability", tl!("Maximum Editability"), false).enabled_when("layers", "true"), + check("hiddenLayers", tl!("Include Hidden Layers"), false).enabled_when("layers", "true"), + check("embedIcc", tl!("Embed ICC Profile"), true), + ] } diff --git a/crates/ui-egui/src/dialogs/svg_options.rs b/crates/ui-egui/src/dialogs/svg_options.rs index 99b471e3f6..77a1e69611 100644 --- a/crates/ui-egui/src/dialogs/svg_options.rs +++ b/crates/ui-egui/src/dialogs/svg_options.rs @@ -7,24 +7,17 @@ use std::borrow::Cow; use std::sync::Arc; +use craft_ui::contract::{Bind, TooltipSpec}; +use craft_ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft_ui::sections::{DialogRole, FooterButton}; use serde_json::{Map, Value, json}; use vectorcraft_engine::cmd::fileio; -use super::DialogSpec; -use crate::state::Dialog; -use crate::theme::{self, Tokens}; -use crate::{VectorcraftApp, io, widgets}; - -pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |_| tl!("SVG Options").into(), - body, - confirm, - ok: Some("OK"), - min_width: 380.0, - max_width: Some(560.0), - inputs: |_| &["path", "showCode"], - ..DialogSpec::FORM -}; +use super::export_host::{self, After, Export, Open}; +// PLAN: assumed `form::{fields_of, json_of}` (wg.S12, widgets-w12) live in `dialogs::form`. +use super::form::{fields_of, json_of}; +use super::png_options::{check, choice}; +use crate::{VectorcraftApp, io}; /// `Dialog::kind` of this dialog. pub const KIND: &str = "svgOptions"; @@ -32,9 +25,15 @@ pub const KIND: &str = "svgOptions"; /// The UI command of the dialog's Show in Browser button. pub const BROWSER: &str = "file.export.svg.browser"; +/// The id of the dialog's Show in Browser footer button, as `take_footer_action` reports it. +pub(super) const BROWSER_ACTION: &str = "browser"; + /// The folder in the system's temporary folder that Show in Browser's previews go to. const PREVIEW_ROOT: &str = "VectorCraft SVG Preview"; +/// The longest code text the code view shows. +const MAX_CODE: usize = 200_000; + /// What OK does: Export As SVG, Save As or Save a Copy. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Mode { @@ -43,24 +42,6 @@ pub enum Mode { SaveCopy, } -impl Mode { - fn id(self) -> &'static str { - match self { - Mode::Export => "export", - Mode::Save => "save", - Mode::SaveCopy => "copy", - } - } - - fn of(d: &Dialog) -> Self { - match d.str("mode").as_str() { - "save" => Mode::Save, - "copy" => Mode::SaveCopy, - _ => Mode::Export, - } - } -} - /// (option value, label) for each choice list. const STYLING: [(&str, &str); 4] = [ ("css", "Internal CSS"), @@ -68,7 +49,7 @@ const STYLING: [(&str, &str); 4] = [ ("style", "Style Attributes"), ("entities", "Style Attributes (Entity References)"), ]; -const FONTS: [(bool, &str); 2] = [(false, "SVG"), (true, "Convert To Outlines")]; +const FONTS: [(&str, &str); 2] = [("false", "SVG"), ("true", "Convert To Outlines")]; const IMAGES: [(&str, &str); 2] = [("embed", "Embed"), ("link", "Link")]; const OBJECT_IDS: [(&str, &str); 3] = [("layerNames", "Layer Names"), ("minimal", "Minimal"), ("unique", "Unique")]; const PROFILES: [(&str, &str); 2] = [("svg11", "SVG 1.1"), ("tiny12", "SVG Tiny 1.2")]; @@ -77,6 +58,18 @@ const ENCODINGS: [(&str, &str); 3] = [("utf8", "Unicode (UTF-8)"), ("utf16", "Un /// Dialog fields that are not SVG options. const UI_KEYS: [&str; 5] = ["mode", "path", "showCode", "allArtboards", "range"]; +/// What the code view's text was encoded from: the text is encoded again only when one of these +/// changes. The read roots in force and the document's folder decide whether the text may be shown. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct SvgCodeKey { + uid: u64, + revision: u64, + options: String, + roots: Option, + path: Option, + selected: Option>, +} + /// The options a first SVG Options dialog starts from: the engine's defaults with Internal CSS /// and Responsive on (as the reference app's Export As starts). Hidden layers are left to the /// command (Save keeps them, Export leaves them out). @@ -92,6 +85,12 @@ pub(super) fn first_use() -> Map { /// Open SVG Options for `mode`, filled with the options used last (a save starts from the ones /// the document was last saved with). `path`: where a save goes. pub fn open(app: &mut VectorcraftApp, mode: Mode, path: Option<&str>) { + open_with(app, mode, path, false); +} + +/// [`open`] for Export Selection when `selection`: the dialog has no artboards to choose, and the +/// code and the browser preview show the selection's crop. +pub(crate) fn open_with(app: &mut VectorcraftApp, mode: Mode, path: Option<&str>, selection: bool) { let mut fields = first_use(); // Fonts start from Document Setup → Type → Export. if app.session.active().is_some_and(|st| st.doc.setup.export_text == vectorcraft_doc::ExportText::Appearance) { @@ -108,27 +107,114 @@ pub fn open(app: &mut VectorcraftApp, mode: Mode, path: Option<&str>) { fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))); } } - fields.insert("mode".into(), json!(mode.id())); fields.insert("allArtboards".into(), json!(true)); fields.insert("range".into(), json!("")); if let Some(p) = path { fields.insert("path".into(), json!(p)); } - app.ui.dialog = Some(Dialog::new(KIND, Value::Object(fields))); + let Some(ctx) = app.ui_ctx.clone() else { return }; + let count = app.session.active().map_or(0, |st| st.doc.artboards.len()); + let web = io::is_web(app); + let initial = fields_of(&dialog_params(mode, selection, count, false), &fields); + let build = move |fields: &mut DialogFields| { + let tiny = fields.text("profile") == Some("tiny12"); + // SVG Tiny has presentation attributes alone; the other styles are shown disabled. + if tiny && fields.text("styling") != Some("presentation") { + fields.set("styling", "presentation"); + } + if fields.bool("__hasArtboards") != Some(count > 0) { + fields.set("__hasArtboards", count > 0); + } + let browser = FooterButton::new(tl!("Show in Browser"), DialogRole::Other).enabled(!web).disabled_reason(tl!("Needs the desktop app")); + ParamDialog::new(KIND, tl!("SVG Options"), dialog_params(mode, selection, count, tiny)) + .values(Bind::bound(fields)) + .extra_buttons(vec![(BROWSER_ACTION.into(), browser)]) + }; + let dialog = HostedParamDialog::new(&ctx, KIND, initial, build); + export_host::open(app, Export::Svg { mode }, selection, dialog); +} + +/// A choice row over `(value, label)` pairs. +fn pairs(key: &str, label: &str, choices: &[(&str, &str)]) -> Param { + let ids: Vec<&str> = choices.iter().map(|(v, _)| *v).collect(); + let labels: Vec<&str> = choices.iter().map(|(_, l)| *l).collect(); + choice(key, label, &ids, &labels) +} + +/// The SVG options: profile, styling, fonts, images, object ids, decimals, encoding, minify, +/// responsive, ``s and metadata. `screens` (Export for Screens' Format Settings) leaves out +/// Images and Variable Data: a linked image is another file. `tiny`: SVG Tiny has presentation +/// attributes alone and no web fonts. +pub(crate) fn svg_params(screens: bool, tiny: bool) -> Vec { + let styling = pairs("styling", tl!("Styling:"), &STYLING); + let fonts = ParamKind::radio(FONTS.iter().map(|(v, l)| ((*v).to_string(), tl!(*l).into())).collect(), Some("false".into())); + let (lo, hi) = (*vectorcraft_svg::DECIMALS.start() as f64, *vectorcraft_svg::DECIMALS.end() as f64); + let mut rows = vec![ + pairs("profile", tl!("SVG Profile:"), &PROFILES), + if tiny { styling.disabled_options(["css", "style", "entities"]) } else { styling }, + Param::new("outlineText", tl!("Font:"), fonts), + ]; + if !screens { + rows.push(pairs("images", tl!("Images:"), &IMAGES)); + } + rows.push(pairs("objectIds", tl!("Object IDs:"), &OBJECT_IDS)); + rows.push(Param::number("decimals", tl!("Decimal:"), 3.0, 1.0, 0).bounds(Some(lo), Some(hi))); + rows.push(pairs("encoding", tl!("Encoding:"), &ENCODINGS)); + rows.push(check("minify", tl!("Minify"), false)); + rows.push(check("responsive", tl!("Responsive"), true)); + // Embedded fonts need SVG 1.1 and text that stays text. + let embed = check("embedFonts", tl!("Embed Fonts (Glyphs Used)"), false); + rows.push(if tiny { embed.enabled_when("profile", "svg11") } else { embed.enabled_when("outlineText", "false") }); + rows.push(check("fewerTspans", tl!("Fewer Elements"), false).enabled_when("outlineText", "false")); + rows.push(check("metadata", tl!("Include Metadata"), true)); + if !screens { + rows.push(check("variableData", tl!("Include Variable Data"), false)); + } + rows +} + +/// Use Artboards: all of them or a range; off = the bounds of all art. +fn artboard_rows(count: usize) -> Vec { + let range = ParamKind::radio(vec![("true".into(), tl!("All").into()), ("false".into(), tl!("Range:").into())], Some("true".into())); + let reason = TooltipSpec::new(tl!("Write each artboard, or the bounds of all art when off")).disabled_text(tl!("The document has no artboards")); + vec![ + // `__hasArtboards` is the dialog's own mirror of the document's artboard count. + check("useArtboards", tl!("Use Artboards"), true).enabled_when("__hasArtboards", true).tooltip(reason), + Param::new("allArtboards", tl!("Artboards:"), range).enabled_when("useArtboards", true), + Param::new("range", tl!("Range:"), ParamKind::text("")).enabled_when("allArtboards", "false").hint(format!("1-{count}")), + ] +} + +/// Every row of the dialog for `mode`. Export Selection writes the selection's crop, without +/// artboards to choose. +fn dialog_params(mode: Mode, selection: bool, count: usize, tiny: bool) -> Vec { + let mut rows = svg_params(false, tiny); + match mode { + Mode::Export if !selection => rows.extend(artboard_rows(count)), + Mode::Export => {} + Mode::Save | Mode::SaveCopy => rows.push(check("preserveEditing", tl!("Preserve Editing Capabilities"), false)), + } + rows.push(Param::new("showCode", tl!("Show Code"), ParamKind::bool(false)).in_footer(tl!("Hide Code"))); + rows.push(Param::custom("__code", tl!("Code"), code_view).visible_when("showCode", true).opens_with("")); + rows +} + +/// A two-id radio or a check box as a flag, whichever the value holds. +fn flag(f: &DialogFields, key: &str, default: bool) -> bool { + f.bool(key).or_else(|| f.text(key).map(|t| t == "true")).unwrap_or(default) } /// The SVG options the dialog's fields describe (artboards only when exporting, editing data /// only when saving). -fn options(d: &Dialog) -> Value { - let mode = Mode::of(d); - let mut o: Map = - d.fields.iter().filter(|(k, _)| !UI_KEYS.contains(&k.as_str()) && !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); +fn options(mode: Mode, f: &DialogFields) -> Value { + let tiny = f.text("profile") == Some("tiny12"); + let mut o = json_of(&dialog_params(mode, false, 1, tiny), f); + o.retain(|k, _| !UI_KEYS.contains(&k.as_str()) && !k.starts_with("__")); if mode == Mode::Export { o.remove("preserveEditing"); - if d.bool("useArtboards") { - let range = d.str("range"); - let range = range.trim(); - o.insert("range".into(), json!(if d.bool("allArtboards") || range.is_empty() { "all" } else { range })); + if f.bool("useArtboards").unwrap_or(false) { + let range = f.text("range").unwrap_or_default().trim(); + o.insert("range".into(), json!(if flag(f, "allArtboards", true) || range.is_empty() { "all" } else { range })); } } else { o.remove("useArtboards"); @@ -136,10 +222,11 @@ fn options(d: &Dialog) -> Value { Value::Object(o) } -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let opts = options(d); - let selection = d.bool(super::export_as::SELECTION_FIELD); - if Mode::of(d) == Mode::Export && d.bool("useArtboards") && !selection { +pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result { + let Export::Svg { mode } = open.kind else { return Err("not the SVG options".into()) }; + let selection = open.selection; + let opts = options(mode, fields); + if mode == Mode::Export && fields.bool("useArtboards").unwrap_or(false) && !selection { let n = app.session.active().map_or(0, |st| st.doc.artboards.len()); let pick: vectorcraft_engine::cmd::fileio::ArtboardPick = serde_json::from_value(opts.clone()).map_err(|e| e.to_string())?; pick.resolve(n)?; @@ -157,140 +244,25 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } } app.ui.svg_options = last; - app.ui.dialog = None; let mut params = json!({ "svg": opts }); - if let Some(p) = d.fields.get("path").filter(|p| p.is_string()) { - params["path"] = p.clone(); + if let Some(p) = fields.text("path") { + params["path"] = json!(p); } - let params = super::export_as::exported(d, params); - let id = match Mode::of(d) { + let params = super::export_as::exported(selection, params); + let id = match mode { Mode::Export => "file.export.svg", Mode::Save => "file.saveAs", Mode::SaveCopy => "file.saveCopy", }; - app.run(id, params) + // PLAN: assumed `After: From` (the command's result, what ex.A1's `confirm` hands the host). + app.run(id, params).map(After::from) } -/// One labelled choice row: the dropdown sets `d.fields[key]` to the chosen value. `forced`: the -/// value the export uses whatever is chosen (shown, the dropdown disabled). -fn choice + Copy>(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, choices: &[(V, &str)], forced: Option) { - let t = Tokens::get(ui.ctx()); - ui.label(egui::RichText::new(label).color(t.text_dim)); - let current = forced.map(Into::into).or_else(|| d.fields.get(key).cloned()).unwrap_or(Value::Null); - let shown = choices.iter().find(|(v, _)| (*v).into() == current).or(choices.first()).map_or("", |(_, l)| *l); - let labels: Vec<&str> = choices.iter().map(|(_, l)| *l).collect(); - let picked = ui.add_enabled_ui(forced.is_none(), |ui| widgets::dropdown(ui, key, shown, &labels, 250.0)).inner; - if let Some((v, _)) = picked.and_then(|i| choices.get(i)) { - d.fields.insert(key.into(), (*v).into()); - } - ui.end_row(); -} - -/// A checkbox bound to `d.fields[key]`. -fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, enabled: bool) { - if widgets::check(ui, label, d.bool(key), enabled) { - d.fields.insert(key.into(), json!(!d.bool(key))); - } -} - -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - option_fields(ui, d, false); - // Export Selection writes the selection's crop, without artboards to choose. - if Mode::of(d) == Mode::Export { - if !d.bool(super::export_as::SELECTION_FIELD) { - artboards(app, ui, d); - } - } else { - check(ui, d, "preserveEditing", tl!("Preserve Editing Capabilities"), true); - } - ui.add_space(10.0); - let show = d.bool("showCode"); - let mut browser = false; - ui.horizontal(|ui| { - if widgets::secondary_button(ui, if show { tl!("Hide Code") } else { tl!("Show Code") }).clicked() { - d.fields.insert("showCode".into(), json!(!show)); - } - let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, tl!("Show in Browser"))); - browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked(); - }); - if browser && let Err(e) = app.run(BROWSER, preview_params(d)) { - app.status(e); - } - if show { - ui.add_space(6.0); - code_view(app, ui, d); - } - false -} - -/// The SVG options: styling, fonts, images, object ids, decimals, minify, responsive, ``s -/// and metadata. `screens` (Export for Screens' Format Settings) leaves out Images: a linked -/// image is another file. -pub(super) fn option_fields(ui: &mut egui::Ui, d: &mut Dialog, screens: bool) { - let t = Tokens::get(ui.ctx()); - // SVG Tiny has presentation attributes alone and no web fonts. - let tiny = d.str("profile") == "tiny12"; - egui::Grid::new("svg-options").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| { - choice(ui, d, "profile", tl!("SVG Profile:"), &PROFILES, None); - choice(ui, d, "styling", tl!("Styling:"), &STYLING, tiny.then_some("presentation")); - choice(ui, d, "outlineText", tl!("Font:"), &FONTS, None); - if !screens { - choice(ui, d, "images", tl!("Images:"), &IMAGES, None); - } - choice(ui, d, "objectIds", tl!("Object IDs:"), &OBJECT_IDS, None); - widgets::field_label(ui, egui::RichText::new(tl!("Decimal:")).color(t.text_dim)); - let decimals = d.f64("decimals", 3.0); - if let Some(v) = widgets::spin_plain(ui, "svg-decimals", decimals, "", 0, 70.0, 1.0, 1.0, &[]) { - let (lo, hi) = (*vectorcraft_svg::DECIMALS.start() as f64, *vectorcraft_svg::DECIMALS.end() as f64); - d.fields.insert("decimals".into(), json!(v.round().clamp(lo, hi) as u8)); - } - ui.end_row(); - choice(ui, d, "encoding", tl!("Encoding:"), &ENCODINGS, None); - }); - ui.add_space(6.0); - ui.horizontal(|ui| { - check(ui, d, "minify", tl!("Minify"), true); - ui.add_space(12.0); - check(ui, d, "responsive", tl!("Responsive"), true); - }); - check(ui, d, "embedFonts", tl!("Embed Fonts (Glyphs Used)"), !d.bool("outlineText") && !tiny); - check(ui, d, "fewerTspans", tl!("Fewer Elements"), !d.bool("outlineText")); - check(ui, d, "metadata", tl!("Include Metadata"), true); - if !screens { - check(ui, d, "variableData", tl!("Include Variable Data"), true); - } -} - -/// Use Artboards: all of them or a range; off = the bounds of all art. -fn artboards(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { - let count = app.session.active().map_or(0, |st| st.doc.artboards.len()); - ui.add_space(4.0); - check(ui, d, "useArtboards", tl!("Use Artboards"), count > 0); - let on = d.bool("useArtboards") && count > 0; - ui.add_enabled_ui(on, |ui| { - ui.horizontal(|ui| { - ui.add_space(22.0); - let all = d.bool("allArtboards"); - if ui.radio(all, tl!("All")).clicked() { - d.fields.insert("allArtboards".into(), json!(true)); - } - if ui.radio(!all, tl!("Range:")).clicked() { - d.fields.insert("allArtboards".into(), json!(false)); - } - let mut range = d.str("range"); - let edit = egui::TextEdit::singleline(&mut range).align(egui::Align2::LEFT_CENTER).hint_text(format!("1-{count}")).desired_width(90.0); - if ui.add_enabled(!all, edit).changed() { - d.fields.insert("range".into(), json!(range)); - } - }); - }); -} - -/// The SVG options the dialog `d`'s OK writes with: [`options`], with hidden layers kept (not +/// The SVG options the dialog's OK writes with: [`options`], with hidden layers kept (not /// displayed) when OK saves, as a save keeps them unless told otherwise. -fn written_options(d: &Dialog) -> Value { - let mut o = options(d); - if Mode::of(d) != Mode::Export +fn written_options(mode: Mode, f: &DialogFields) -> Value { + let mut o = options(mode, f); + if mode != Mode::Export && let Some(m) = o.as_object_mut() { m.entry("hiddenLayers").or_insert(json!(true)); @@ -298,10 +270,10 @@ fn written_options(d: &Dialog) -> Value { o } -/// The params of [`BROWSER`] for the dialog `d`: the SVG options OK writes with +/// The params of [`BROWSER`] for the dialog's fields: the SVG options OK writes with /// ([`written_options`]), and `exportSelection` when Export Selection opened it. -fn preview_params(d: &Dialog) -> Value { - super::export_as::exported(d, json!({ "svg": written_options(d) })) +pub(super) fn preview_params(mode: Mode, selection: bool, f: &DialogFields) -> Value { + super::export_as::exported(selection, json!({ "svg": written_options(mode, f) })) } /// The SVG file that the SVG options `svg` write for one page of the document `st`, and the @@ -367,11 +339,11 @@ pub(crate) fn browser_preview(app: &mut VectorcraftApp, p: &Value) -> Result Result = match ui.ctx().data(|m| m.get_temp::<(u64, Arc)>(key)).filter(|(s, _)| *s == sig) { - Some((_, c)) => c, - None => { - const MAX: usize = 200_000; - let mut text = match encode_page(st, &opts, selection) { - // Shown as text whatever the file's encoding. - Ok((_, enc)) => enc - .files - .into_iter() - .next() - .map(|(_, b)| vectorcraft_svg::text_of(&b).map_or_else(|_| String::from_utf8_lossy(&b).into_owned(), |t| t.into_owned())) - .unwrap_or_default(), - Err(e) => e, - }; - if text.len() > MAX { - let cut = (0..=MAX).rev().find(|i| text.is_char_boundary(*i)).unwrap_or(0); - text.truncate(cut); - text.push_str("\n…"); - } - let c = Arc::new(text); - ui.ctx().data_mut(|m| m.insert_temp(key, (sig, c.clone()))); - c - } +/// the selection alone, cropped to it, as the code view shows it. Encoded again only when what +/// [`SvgCodeKey`] holds changes; a failure is the text (it names no file outside the read roots). +fn code_text(app: &mut VectorcraftApp, mode: Mode, selection: bool, fields: &DialogFields) -> Option> { + let st = app.session.active()?; + let opts = written_options(mode, fields); + let key = SvgCodeKey { + uid: st.uid, + revision: st.revision, + options: opts.to_string(), + roots: vectorcraft_engine::file_access::current().map(|r| r.describe()), + path: st.path.clone(), + selected: selection.then(|| st.selection.objects.clone()), }; - widgets::list_box(ui, |ui| { - egui::ScrollArea::both().max_height(260.0).max_width(520.0).auto_shrink([false, true]).show(ui, |ui| { - ui.add( - egui::TextEdit::multiline(&mut code.as_str()) - .font(theme::mono(11.5)) - .text_color(t.text) - .frame(egui::Frame::NONE) - .desired_width(f32::INFINITY) - .desired_rows(12), - ); - }); - }); + if let Some((cached, text)) = &app.canvas.svg_code + && *cached == key + { + return Some(text.clone()); + } + let mut text = match encode_page(st, &opts, selection) { + // Shown as text whatever the file's encoding. + Ok((_, enc)) => enc + .files + .into_iter() + .next() + .map(|(_, b)| vectorcraft_svg::text_of(&b).map_or_else(|_| String::from_utf8_lossy(&b).into_owned(), |t| t.into_owned())) + .unwrap_or_default(), + Err(e) => e, + }; + if text.len() > MAX_CODE { + let cut = (0..=MAX_CODE).rev().find(|i| text.is_char_boundary(*i)).unwrap_or(0); + text.truncate(cut); + text.push_str("\n…"); + } + let text: Arc = text.into(); + app.canvas.svg_code = Some((key, text.clone())); + Some(text) +} + +/// Fills the open dialog's code view with the SVG the options write, while Show Code is on; the +/// host calls it each pass. +pub(super) fn refresh_code(app: &mut VectorcraftApp, dialog: &mut HostedParamDialog, mode: Mode, selection: bool) { + if dialog.fields().bool("showCode") != Some(true) { + return; + } + let Some(text) = code_text(app, mode, selection, dialog.fields()) else { return }; + if dialog.fields().text("__code") != Some(&*text) { + dialog.set_field("__code", FieldValue::Text(text.to_string())); + } +} + +/// The code view row: the text `refresh_code` keeps in `__code`, read-only and selectable. +fn code_view(ui: &mut egui::Ui, fields: &mut DialogFields, _: &mut CustomContext) -> egui::Response { + let code = fields.text("__code").unwrap_or_default(); + // PLAN: the sheet names `Stack` + `Scroll::vertical()` + `SelectableText::mono().multiline()`; their builders are not in this tree. + egui::ScrollArea::vertical() + .max_height(260.0) + .auto_shrink([false, true]) + .show(ui, |ui| ui.add(egui::Label::new(egui::RichText::new(code).monospace()).selectable(true))) + .inner } #[cfg(test)] @@ -442,23 +424,22 @@ mod tests { use vectorcraft_engine::Session; + use super::super::tests_export::{frame, kind, set}; + use super::super::tests_raster_formats::fields; use super::*; - use crate::Services; + use crate::{Services, theme}; type Written = Rc)>>>; - /// An app with two artboards and a rectangle whose save dialog answers `picked` and whose - /// writer records what it is given. - fn app(picked: &str) -> (VectorcraftApp, Written) { + /// An app with two artboards and a rectangle whose writer records what it is given. + fn app() -> (VectorcraftApp, Written) { let written = Written::default(); let w = written.clone(); - let picked = picked.to_string(); let services = Services { write: Some(Box::new(move |p: &str, b: &[u8]| { w.borrow_mut().push((p.to_string(), b.to_vec())); Ok(()) })), - pick_save: Some(Box::new(move |_: &crate::FilePick| Some(picked.clone()))), ..Default::default() }; let mut app = VectorcraftApp::new(Session::new(), services); @@ -467,43 +448,50 @@ mod tests { (app, written) } - /// One headless frame of the dialog layer. - fn frame(app: &mut VectorcraftApp) { - let ctx = egui::Context::default(); - theme::install_fonts(&ctx); - let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(app, ui.ctx())); - out.textures_delta.clear(); + /// SVG Options open for `mode` and `path`, drawn once. + fn start(app: &mut VectorcraftApp, mode: Mode, path: &str, selection: bool) { + open_with(app, mode, Some(path), selection); + frame(app); } fn text(w: &Written, i: usize) -> String { String::from_utf8(w.borrow()[i].1.clone()).unwrap() } - type Opened = Rc>>; + /// The URLs the app asked egui to open in one frame. + fn open_urls(app: &mut VectorcraftApp) -> Vec { + // PLAN: hub-w3 deletes `Services::open_url`; the URL reaches the frame as `OutputCommand::OpenUrl`. + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + let out = ctx.run_ui(Default::default(), |ui| super::super::show(app, ui.ctx())); + out.platform_output + .commands + .iter() + .filter_map(|c| match c { + egui::OutputCommand::OpenUrl(o) => Some(o.url.clone()), + _ => None, + }) + .collect() + } - /// [`app`] whose browser records each URL it is asked to open. Its previews go to a temporary - /// folder of the test's own ([`preview_tmp`]), not the system's. - fn browsing(picked: &str) -> (VectorcraftApp, Written, Opened) { + /// [`app`] whose previews go to a temporary folder of the test's own ([`preview_tmp`]), not the system's. + fn browsing() -> (VectorcraftApp, Written) { static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); let tmp = vectorcraft_testkit::temp_dir(&format!("svg-browser-{}", N.fetch_add(1, std::sync::atomic::Ordering::Relaxed))); - super::super::save_for_web::TEST_TMP.set(Some(tmp)); - let (mut app, written) = app(picked); - let opened = Opened::default(); - let o = opened.clone(); - app.services.open_url = Some(Box::new(move |u: &str| o.borrow_mut().push(u.to_string()))); - (app, written, opened) + super::super::preview_folders::TEST_TMP.set(Some(tmp)); + app() } /// The SVG preview folder inside this test's temporary folder ([`browsing`]), with `/` between /// its parts. fn preview_tmp() -> String { - let tmp = super::super::save_for_web::TEST_TMP.with_borrow(Clone::clone).expect("browsing sets the temporary folder"); + let tmp = super::super::preview_folders::TEST_TMP.with_borrow(Clone::clone).expect("browsing sets the temporary folder"); tmp.join(PREVIEW_ROOT).to_string_lossy().replace('\\', "/") } /// Show in Browser for the open dialog's current choices, as its button runs it. - fn show_in_browser(app: &mut VectorcraftApp) -> Result { - let p = preview_params(app.ui.dialog.as_ref().expect("SVG Options open")); + fn show_in_browser(app: &mut VectorcraftApp, mode: Mode, selection: bool) -> Result { + let p = preview_params(mode, selection, &fields(app)); app.run(BROWSER, p) } @@ -512,52 +500,51 @@ mod tests { /// open, nothing is remembered, and OK then writes the same SVG to the chosen file. #[test] fn show_in_browser_opens_what_ok_writes_without_confirming() { - let (mut app, written, opened) = browsing("/tmp/out.svg"); - app.run("file.export.svg", Value::Null).unwrap(); + let (mut app, written) = browsing(); + start(&mut app, Mode::Export, "/tmp/out.svg", false); + set(&mut app, "decimals", json!(1)); + set(&mut app, "allArtboards", json!(false)); + set(&mut app, "range", json!("2")); frame(&mut app); - let f = &mut app.ui.dialog.as_mut().unwrap().fields; - f.insert("decimals".into(), json!(1)); - f.insert("allArtboards".into(), json!(false)); - f.insert("range".into(), json!("2")); let remembered = app.ui.svg_options.clone(); - let r = show_in_browser(&mut app).unwrap_or_else(|e| panic!("{e}")); + let r = show_in_browser(&mut app, Mode::Export, false).unwrap_or_else(|e| panic!("{e}")); let path = r["path"].as_str().unwrap().to_string(); assert!(path.starts_with(&format!("{}/", preview_tmp())) && path.ends_with("/Untitled-1.svg"), "{path}"); - assert_eq!(*opened.borrow(), [io::file_url(&path)]); + let mut opened = open_urls(&mut app); + assert_eq!(opened, [io::file_url(&path)]); assert_eq!(written.borrow().len(), 1); assert_eq!(written.borrow()[0].0, path); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the dialog stays open"); + assert_eq!(kind(&app), Some(KIND), "the dialog stays open"); assert_eq!(app.ui.svg_options, remembered, "nothing is remembered"); assert!(app.session.active().unwrap().path.is_none()); - frame(&mut app); super::super::confirm(&mut app).unwrap(); assert_eq!(written.borrow()[1].0, "/tmp/out.svg"); assert_eq!(text(&written, 0), text(&written, 1), "the preview is the file OK writes"); - assert_eq!(opened.borrow().len(), 1); + opened.extend(open_urls(&mut app)); + assert_eq!(opened.len(), 1); } /// A range the document has no artboard for is refused, as OK refuses it: nothing is written /// or opened, and the dialog stays open. #[test] fn show_in_browser_refuses_a_range_the_document_lacks() { - let (mut app, written, opened) = browsing("/tmp/out.svg"); - app.run("file.export.svg", Value::Null).unwrap(); - let f = &mut app.ui.dialog.as_mut().unwrap().fields; - f.insert("allArtboards".into(), json!(false)); - f.insert("range".into(), json!("5")); - assert!(show_in_browser(&mut app).is_err()); - assert!(written.borrow().is_empty() && opened.borrow().is_empty()); - assert!(app.ui.dialog.is_some()); + let (mut app, written) = browsing(); + start(&mut app, Mode::Export, "/tmp/out.svg", false); + set(&mut app, "allArtboards", json!(false)); + set(&mut app, "range", json!("5")); + assert!(show_in_browser(&mut app, Mode::Export, false).is_err()); + assert!(written.borrow().is_empty() && open_urls(&mut app).is_empty()); + assert_eq!(kind(&app), Some(KIND)); } /// A write that fails opens nothing and removes the folder made for that preview. #[test] fn show_in_browser_removes_its_folder_when_a_write_fails() { - let (mut app, _, opened) = browsing("/tmp/out.svg"); + let (mut app, _) = browsing(); app.services.write = Some(Box::new(|_: &str, _: &[u8]| Err("disk full".to_string()))); - app.run("file.export.svg", Value::Null).unwrap(); - assert!(show_in_browser(&mut app).unwrap_err().contains("disk full")); - assert!(opened.borrow().is_empty()); + start(&mut app, Mode::Export, "/tmp/out.svg", false); + assert!(show_in_browser(&mut app, Mode::Export, false).unwrap_err().contains("disk full")); + assert!(open_urls(&mut app).is_empty()); let left: Vec<_> = std::fs::read_dir(preview_tmp()).map(|d| d.flatten().map(|e| e.file_name()).collect()).unwrap_or_default(); assert!(left.is_empty(), "{left:?}"); } @@ -565,29 +552,28 @@ mod tests { /// Under Export Selection the preview is the selection alone, cropped to it, as OK writes it. #[test] fn show_in_browser_under_export_selection_shows_the_selection() { - let (mut app, written, opened) = browsing("/tmp/selection.svg"); + let (mut app, written) = browsing(); app.run("shape.rectangle", json!({"x": 70, "y": 40, "width": 20, "height": 20})).unwrap(); - app.run("document.exportSelection", Value::Null).unwrap(); - assert!(app.ui.dialog.as_ref().unwrap().bool(super::super::export_as::SELECTION_FIELD)); - show_in_browser(&mut app).unwrap_or_else(|e| panic!("{e}")); + start(&mut app, Mode::Export, "/tmp/selection.svg", true); + show_in_browser(&mut app, Mode::Export, true).unwrap_or_else(|e| panic!("{e}")); super::super::confirm(&mut app).unwrap(); assert_eq!(written.borrow()[1].0, "/tmp/selection.svg"); assert_eq!(text(&written, 0), text(&written, 1)); assert_eq!(text(&written, 0).matches("Untitled-1", "doc"), text(&written, 1)); @@ -613,28 +599,28 @@ mod tests { /// writes it, rather than refused for its artboard range. #[test] fn show_in_browser_previews_a_document_without_artboards() { - let (mut app, written, opened) = browsing("/tmp/out.svg"); - app.run("file.export.svg", Value::Null).unwrap(); + let (mut app, written) = browsing(); + start(&mut app, Mode::Export, "/tmp/out.svg", false); std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc).artboards.clear(); - show_in_browser(&mut app).unwrap_or_else(|e| panic!("{e}")); + show_in_browser(&mut app, Mode::Export, false).unwrap_or_else(|e| panic!("{e}")); assert_eq!(vectorcraft_testkit::svg_shapes(&text(&written, 0)), 1, "{}", text(&written, 0)); - assert_eq!(opened.borrow().len(), 1); + assert_eq!(open_urls(&mut app).len(), 1); } /// The web build has no file to open, and a control or MCP request may not open another app: /// both are refused before anything is written or opened. #[test] fn show_in_browser_is_refused_on_the_web_and_for_automation() { - let (mut app, written, opened) = browsing("/tmp/out.svg"); - app.run("file.export.svg", Value::Null).unwrap(); + let (mut app, written) = browsing(); + start(&mut app, Mode::Export, "/tmp/out.svg", false); app.ui.answering_control = true; - assert!(show_in_browser(&mut app).unwrap_err().contains("opens another app")); + assert!(show_in_browser(&mut app, Mode::Export, false).unwrap_err().contains("opens another app")); app.ui.answering_control = false; assert!(crate::menus::enabled(&app, BROWSER)); app.services.download = Some(Box::new(|_: &str, _: &[u8]| Ok(()))); assert!(!crate::menus::enabled(&app, BROWSER), "the command palette and menus show it disabled on the web"); - assert!(show_in_browser(&mut app).is_err()); - assert!(written.borrow().is_empty() && opened.borrow().is_empty()); + assert!(show_in_browser(&mut app, Mode::Export, false).is_err()); + assert!(written.borrow().is_empty() && open_urls(&mut app).is_empty()); } /// SVG previews have their own folder: making one removes only old SVG preview folders and @@ -642,9 +628,9 @@ mod tests { #[test] fn svg_preview_folders_leave_save_for_web_previews_alone() { let tmp = vectorcraft_testkit::temp_dir("svg-preview-folders"); - let web = super::super::save_for_web::preview_folder_in(&tmp, std::time::Duration::from_secs(3600)).unwrap(); - let old = super::super::save_for_web::preview_folder_under(&tmp, PREVIEW_ROOT, std::time::Duration::from_secs(3600)).unwrap(); - let new = super::super::save_for_web::preview_folder_under(&tmp, PREVIEW_ROOT, std::time::Duration::ZERO).unwrap(); + let web = super::super::preview_folders::preview_folder_in(&tmp, std::time::Duration::from_secs(3600)).unwrap(); + let old = super::super::preview_folders::preview_folder_under(&tmp, PREVIEW_ROOT, std::time::Duration::from_secs(3600)).unwrap(); + let new = super::super::preview_folders::preview_folder_under(&tmp, PREVIEW_ROOT, std::time::Duration::ZERO).unwrap(); assert!(new.contains("/VectorCraft SVG Preview/"), "{new}"); assert!(std::path::Path::new(&web).is_dir(), "Save for Web's preview is kept"); assert!(!std::path::Path::new(&old).exists(), "the old SVG preview is removed"); @@ -653,30 +639,49 @@ mod tests { #[test] fn export_as_svg_opens_the_options_and_remembers_them() { - let (mut app, written) = app("/tmp/out.svg"); - app.run("file.export.svg", Value::Null).unwrap(); - let d = app.ui.dialog.clone().expect("SVG Options opened"); - assert_eq!(d.kind, KIND); - assert_eq!((d.str("styling"), d.bool("responsive"), d.str("mode")), ("css".into(), true, "export".into()), "first-use defaults"); - frame(&mut app); + let (mut app, written) = app(); + start(&mut app, Mode::Export, "/tmp/out.svg", false); + assert_eq!(kind(&app), Some(KIND)); // Show Code draws the SVG the options write. - app.ui.dialog.as_mut().unwrap().fields.insert("showCode".into(), json!(true)); + set(&mut app, "showCode", json!(true)); frame(&mut app); - assert!(app.ui.dialog.is_some()); - let f = &mut app.ui.dialog.as_mut().unwrap().fields; - f.insert("decimals".into(), json!(1)); - f.insert("allArtboards".into(), json!(false)); - f.insert("range".into(), json!("1")); + assert_eq!(kind(&app), Some(KIND)); + set(&mut app, "decimals", json!(1)); + set(&mut app, "allArtboards", json!(false)); + set(&mut app, "range", json!("1")); super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + assert_eq!(kind(&app), None); let svg = text(&written, 0); assert_eq!(written.borrow()[0].0, "/tmp/out.svg"); assert!(svg.contains("