diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index 60701aae13..aaef3802ef 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -11,16 +11,18 @@ use std::sync::LazyLock; +use craft_ui::contract::Bind; +use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft_ui::runtime::env::Label; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, Format}; -use super::{DialogSpec, dxf_options, eps_options, form, hpgl_options, plugin, png_options, save_pdf, svg_options, text_export}; -use crate::state::Dialog; -use crate::theme::Tokens; -use crate::{VectorcraftApp, io, widgets}; +use super::export_host::{self, After, Export, Open}; +use super::{dxf_options, eps_options, form, hpgl_options, plugin, png_options, save_pdf, svg_options, text_export}; +use crate::{VectorcraftApp, io}; -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("Export As").into(), body, confirm, ok: Some("Export…"), min_width: 380.0, ..DialogSpec::FORM }; +/// The dialog's key. +pub(super) const KIND: &str = "exportAs"; /// The built-in formats Export As writes (the native format and `.ai` are Save As's). static BUILT_IN: LazyLock> = @@ -38,16 +40,78 @@ fn from_plugin(f: &Format) -> bool { vectorcraft_plugins::export::by_format(f.id).is_some() } -/// What to use instead when the field names a format that can't be written (DWG). -fn unavailable(d: &Dialog) -> Option<(&'static str, &'static str)> { - let id = d.str("format"); +/// What to use instead when the format field names a format that can't be written (DWG). +fn unavailable(fields: &DialogFields) -> Option<(&'static str, &'static str)> { + let id = fields.text("format")?; let (_, label) = UNAVAILABLE.iter().find(|u| u.0 == id)?; - Some((label, fileio::unsupported(&id)?.hint)) + Some((label, fileio::unsupported(id)?.hint)) +} + +/// The chosen format (PNG when the field names none Export As writes). +fn chosen(fields: &DialogFields) -> Option<&'static Format> { + let all = formats(); + let find = |id: &str| all.iter().copied().find(|f| f.id == id); + find(fields.text("format").unwrap_or("png")).or_else(|| find("png")) +} + +/// Whether the artboard choice is All; the radio's ids are `true` and `false`. +fn is_all(fields: &DialogFields) -> bool { + fields.bool("all").or_else(|| fields.text("all").map(|t| t == "true")).unwrap_or(true) +} + +/// The rows, from the formats installed now. +fn params() -> Vec { + let all = formats(); + let choices = all.iter().map(|f| (f.id, f.label)).chain(UNAVAILABLE); + // An exporter plug-in writes the whole document: Use Artboards is not its to apply. + let whole: Vec<&str> = all.iter().filter(|f| !from_plugin(f)).map(|f| f.id).collect(); + vec![ + Param::new( + "format", + tl!("Format:"), + ParamKind::choice(choices.map(|(id, label)| (id.to_string(), Label::from(label))).collect(), Some("png".into())), + ) + .disabled_options(UNAVAILABLE.map(|u| u.0)), + Param::new("useArtboards", tl!("Use Artboards"), ParamKind::bool(false)).enabled_when_in("format", whole), + Param::new( + "all", + tl!("Artboards"), + ParamKind::radio( + vec![("true".into(), Label::from(tl!("All"))), ("false".into(), Label::from(tl!("Range:")))], + Some("true".into()), + ), + ) + .enabled_when("useArtboards", true), + Param::new("range", "", ParamKind::text("")).hint("1-3, 5").enabled_when("all", "false"), + ] +} + +/// The line under the rows: what the export writes, or what to use instead of DWG. +fn summary(fields: &DialogFields) -> String { + if let Some((_, hint)) = unavailable(fields) { + return hint.to_string(); + } + let Some(f) = chosen(fields) else { return String::new() }; + let whole = from_plugin(f); + let use_artboards = fields.bool("useArtboards").unwrap_or(false) && !whole; + match (use_artboards, f.id) { + _ if whole => tl!("The plug-in writes the whole document.").to_string(), + (true, "pdf") => tl!("One page per artboard.").to_string(), + (true, _) => crate::i18n::fmt(tl!("One file per artboard: -.{ext}"), &[("ext", f.extensions[0])]), + (false, _) => tl!("The bounds of the visible art.").to_string(), + } } /// Open the dialog on `format` (an id or extension, default PNG); `p` may preset `useArtboards` /// and `range`. pub fn open(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) { + if let Err(e) = open_dialog(app, format, p) { + app.status(e); + } +} + +fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Result<(), String> { + let ctx = app.ui_ctx.clone().ok_or("no window")?; let n = app.session.active().map_or(0, |s| s.doc.artboards.len()); let missing = format.and_then(|f| UNAVAILABLE.iter().find(|u| u.0.eq_ignore_ascii_case(f.trim_start_matches('.')))); let format = match missing { @@ -55,84 +119,35 @@ pub fn open(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) { None => format.and_then(fileio::format).filter(|f| formats().iter().any(|g| g.id == f.id)).map_or("png", |f| f.id), }; let range = p.get("range").and_then(Value::as_str); - app.ui.dialog = Some(Dialog::new( - "exportAs", - json!({ - "format": format, - "useArtboards": p.get("useArtboards").and_then(Value::as_bool).unwrap_or(false), - "all": range.is_none(), - "range": range.map_or_else(|| if n > 1 { format!("1-{n}") } else { "1".into() }, str::to_string), - }), - )); -} - -/// The chosen format (PNG when the field names none Export As writes). -fn chosen(d: &Dialog) -> Option<&'static Format> { - let id = d.str("format"); - let all = formats(); - let find = |id: &str| all.iter().copied().find(|f| f.id == id); - find(&id).or_else(|| find("png")) -} - -fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let t = Tokens::get(ui.ctx()); - let Some(f) = chosen(d) else { return false }; - let missing = unavailable(d); - egui::Grid::new("export-as").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| { - ui.label(egui::RichText::new(tl!("Format:")).color(t.text_dim)); - let shown = missing.map_or(f.label, |(label, _)| label); - let all = formats(); - let labels: Vec<&str> = all.iter().map(|f| f.label).chain(UNAVAILABLE.iter().map(|u| u.1)).collect(); - if let Some(g) = widgets::dropdown_with(ui, "export-as-format", shown, &labels, 160.0, |i| i < all.len()).and_then(|i| all.get(i)) { - d.fields.insert("format".into(), json!(g.id)); - } - ui.end_row(); + let initial = json!({ + "format": format, + "useArtboards": p.get("useArtboards").and_then(Value::as_bool).unwrap_or(false), + "all": range.is_none(), + "range": range.map_or_else(|| if n > 1 { format!("1-{n}") } else { "1".into() }, str::to_string), }); - if let Some((_, hint)) = missing { - ui.add_space(6.0); - form::caption(ui, hint); - } - ui.add_space(10.0); - // An exporter plug-in writes the whole document: Use Artboards is not its to apply. - let whole = from_plugin(f); - ui.add_enabled_ui(!whole, |ui| form::check(ui, d, "useArtboards", tl!("Use Artboards"))); - let use_artboards = d.bool("useArtboards") && !whole; - ui.add_enabled_ui(use_artboards, |ui| { - ui.horizontal(|ui| { - ui.add_space(22.0); - let mut all = d.bool("all"); - if ui.radio_value(&mut all, true, tl!("All")).changed() | ui.radio_value(&mut all, false, tl!("Range:")).changed() { - d.fields.insert("all".into(), json!(all)); - } - let mut range = d.str("range"); - let field = egui::TextEdit::singleline(&mut range).align(egui::Align2::LEFT_CENTER).desired_width(90.0).hint_text("1-3, 5"); - if ui.add_enabled(!all, field).changed() { - d.fields.insert("range".into(), json!(range)); - } - }); + let fields = form::fields_of(¶ms(), &initial.as_object().cloned().unwrap_or_default()); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, |fields| { + ParamDialog::new(KIND, tl!("Export As"), params()) + .values(Bind::bound(fields)) + .below(|ui, fields| { + ui.weak(summary(fields)); + }) + .ok_label(Label::from("Export…")) }); - ui.add_space(8.0); - let ext = f.extensions[0]; - let hint = match (use_artboards, f.id) { - _ if whole => tl!("The plug-in writes the whole document.").to_string(), - (true, "pdf") => tl!("One page per artboard.").to_string(), - (true, _) => crate::i18n::fmt(tl!("One file per artboard: -.{ext}"), &[("ext", ext)]), - (false, _) => tl!("The bounds of the visible art.").to_string(), - }; - ui.label(egui::RichText::new(hint).color(t.text_dim).size(11.5)); - false + export_host::open(app, Export::As, false, dialog).map(|_| ()).ok_or_else(|| "no window".into()) } -/// Check the artboard range, pick the file, then show the format's options or write the file. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - if let Some((_, hint)) = unavailable(d) { +/// Check the artboard range and that there is something to export; the save panel and the format's options or +/// the file follow once the dialog has closed. +pub(super) fn confirm(app: &mut VectorcraftApp, _open: &Open, fields: &DialogFields) -> Result { + if let Some((_, hint)) = unavailable(fields) { return Err(hint.into()); } - let f = chosen(d).ok_or("no format to export to")?; + let f = chosen(fields).ok_or("no format to export to")?; let plugin = vectorcraft_plugins::export::by_format(f.id); - let use_artboards = d.bool("useArtboards") && plugin.is_none(); - let all = d.bool("all"); - let range = d.str("range"); + let use_artboards = fields.bool("useArtboards").unwrap_or(false) && plugin.is_none(); + let all = is_all(fields); + let range = fields.text("range").unwrap_or_default().to_string(); if use_artboards && !all { // A bad range keeps the dialog open. let n = app.session.active().map_or(0, |s| s.doc.artboards.len()); @@ -146,23 +161,15 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { { return Err("nothing to export: the document has no visible art (or turn on Use Artboards)".into()); } - app.ui.dialog = None; - let path = io::export_path(app, None, f)?; let range = if all { "all".to_string() } else { range }; - let r = options_or_write(app, f, plugin, path, Pages { use_artboards, all, range, selection: false }); - // The options follow the save panel: the Enter that closed it isn't theirs (as in Save As). - super::opened_by_panel(app); - r + let pages = Pages { use_artboards, all, range, selection: false }; + Ok(Some(Box::new(move |app| io::export_path(app, None, f, move |app, path| options_or_write(app, f, plugin, path, pages))))) } -/// The options dialogs' field that is true when Export Selection opened them: OK then writes the -/// selection alone ([`exported`]). Not remembered with the dialog's options. -pub(super) const SELECTION_FIELD: &str = "__selection"; - -/// `params` of an options dialog `d` for [`io::export`]: with [`io::EXPORT_SELECTION`] when -/// Export Selection opened `d`. -pub(super) fn exported(d: &Dialog, mut params: Value) -> Value { - if d.bool(SELECTION_FIELD) +/// `params` of an options dialog for [`io::export`]: with [`io::EXPORT_SELECTION`] when +/// Export Selection opened the dialog (`selection`). +pub(super) fn exported(selection: bool, mut params: Value) -> Value { + if selection && let Some(o) = params.as_object_mut() { o.insert(io::EXPORT_SELECTION.into(), json!(true)); @@ -181,9 +188,7 @@ pub fn export_selection(app: &mut VectorcraftApp) -> Result { let f = fileio::writable_format(None, Some(&path))?; let plugin = vectorcraft_plugins::export::by_format(f.id); let pages = Pages { use_artboards: false, all: true, range: String::new(), selection: true }; - let r = options_or_write(app, f, plugin, path, pages); - super::opened_by_panel(app); - r + options_or_write(app, f, plugin, path, pages) } /// What an export writes: with `use_artboards` the artboards (`all`, else the 1-based `range`), @@ -205,24 +210,20 @@ fn options_or_write( pages: Pages, ) -> Result { let Pages { use_artboards, all, range, selection } = pages; - let r = match f.id { + match f.id { "svg" | "svgz" => { - svg_options::open(app, svg_options::Mode::Export, Some(&path)); - if let Some(o) = app.ui.dialog.as_mut() { - o.fields.extend([("useArtboards".into(), json!(use_artboards)), ("allArtboards".into(), json!(all)), ("range".into(), json!(range))]); + svg_options::open_with(app, svg_options::Mode::Export, Some(&path), selection); + // Export Selection shows no artboard choice: the selection is one page. + if !selection && let Some(id) = app.export_dialogs.last_id() { + let rows = [("useArtboards", json!(use_artboards)), ("allArtboards", json!(all)), ("range", json!(range))]; + export_host::set_fields(app, id, &rows)?; } Ok(Value::Null) } // Save PDF writes the artboards as pages, or one page of the art's bounds or the selection. - "pdf" if use_artboards => save_pdf::open(app, &json!({ "path": path, "range": (!all).then_some(range) })), - "pdf" => save_pdf::open(app, &json!({ "path": path, "useArtboards": false })), - "txt" => { - text_export::open(app, &path); - if let Some(o) = app.ui.dialog.as_mut().filter(|_| selection) { - o.fields.insert("selectionOnly".into(), json!(true)); - } - Ok(Value::Null) - } + "pdf" if use_artboards => save_pdf::open_with(app, &json!({ "path": path, "range": (!all).then_some(range) }), selection), + "pdf" => save_pdf::open_with(app, &json!({ "path": path, "useArtboards": false }), selection), + "txt" => text_export::open(app, &path, selection).map(|()| Value::Null), _ => { let mut params = json!({ "format": f.id, "path": path }); // A format that holds the whole document (a template) has no Use Artboards: the @@ -234,37 +235,26 @@ fn options_or_write( } } let plugin = plugin.filter(|p| !p.manifest().params.is_empty()); - let dialog = plugin.is_none() && (f.raster || matches!(f.id, "dxf" | "eps" | "hpgl")); - if selection { - // An options dialog keeps the mark as a field of its own, which OK hands on. - params[if dialog { SELECTION_FIELD } else { io::EXPORT_SELECTION }] = json!(true); + // A raster format's dialog is told about Export Selection by its record; the others read the param. + let raster_dialog = plugin.is_none() && f.raster; + if selection && !raster_dialog { + params[io::EXPORT_SELECTION] = json!(true); } if let Some(plugin) = plugin { plugin::open_export(app, &plugin, params); return Ok(Value::Null); } if f.raster { - png_options::open(app, f, params); + png_options::open_with(app, f, params, selection); return Ok(Value::Null); } - if f.id == "dxf" { - dxf_options::open(app, ¶ms); - return Ok(Value::Null); + match f.id { + "dxf" => dxf_options::open(app, ¶ms), + "eps" => eps_options::open(app, ¶ms), + "hpgl" => hpgl_options::open(app, ¶ms), + _ => return io::export(app, Some(f.id), Some(path), ¶ms), } - if f.id == "eps" { - eps_options::open(app, ¶ms); - return Ok(Value::Null); - } - if f.id == "hpgl" { - hpgl_options::open(app, ¶ms); - return Ok(Value::Null); - } - return io::export(app, Some(f.id), Some(path), ¶ms); + Ok(Value::Null) } - }; - // Export Selection's mark on the options dialog that opened. - if let Some(o) = app.ui.dialog.as_mut().filter(|_| selection) { - o.fields.insert(SELECTION_FIELD.into(), json!(true)); } - r } diff --git a/crates/ui-egui/src/dialogs/export_host.rs b/crates/ui-egui/src/dialogs/export_host.rs new file mode 100644 index 0000000000..b11d520078 --- /dev/null +++ b/crates/ui-egui/src/dialogs/export_host.rs @@ -0,0 +1,188 @@ +//! The export dialogs on the dialog host: Export As, the raster, SVG, EPS, DXF and HP-GL options, Save for +//! Office, Text Export and the Save options. Each is a hosted parameter dialog whose OK runs its kind's `confirm` +//! (through `host::open_held_with`); a refusal keeps the dialog open with its reason, and what has to follow the +//! dialog's closing (the save panel, the next dialog, the file) waits on the record here until the host reports +//! the dialog gone. The rows' own requests (the SVG browser preview, the EPS `Custom…` and HP-GL pen table +//! buttons) are answered in [`pump`]. + +use craft_ui::dialog::DialogId; +use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamResult}; +use serde_json::Value; + +use super::host::{self, HeldOptions}; +use super::{dxf_options, eps_options, export_as, hpgl_options, office_export, png_options, save_options, svg_options, text_export}; +use crate::VectorcraftApp; + +/// What runs once the dialog that confirmed has closed. It has no reply to give: its failure goes to the status +/// line, and a command that returns a value calls the step itself. +pub(crate) type After = Option Result>>; + +/// Which export dialog a record is. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Export { + /// Export As. + As, + /// The options of the raster format `format`. + Raster { + /// The format's id. + format: &'static str, + }, + /// SVG Options, for Export As, Save As or Save a Copy. + Svg { + /// What OK does. + mode: svg_options::Mode, + }, + /// EPS Options. + Eps, + /// Custom Transparency Flattener Options, over EPS Options. + EpsCustom { + /// The EPS Options dialog it edits. + parent: DialogId, + }, + /// DXF Options. + Dxf, + /// HP-GL Options, for the document `doc`. + Hpgl { + /// The uid of the document the pens are read from. + doc: u64, + }, + /// Save for Office Documents. + Office, + /// Text Export Options. + Text, + /// The options a save or open asks for before it goes on, for `action`. + Save { + /// The action the options belong to. + action: String, + }, +} + +/// One open export dialog. +pub(crate) struct Open { + /// The hosted dialog's id. + pub id: DialogId, + /// Which dialog it is. + pub kind: Export, + /// Whether Export Selection opened it: OK then writes the selection alone. + pub selection: bool, + /// What runs once the dialog has closed after an OK; empty for a dialog that was cancelled. + pub after: After, +} + +/// The export dialogs that are open (`app.export_dialogs`). +#[derive(Default)] +pub(crate) struct ExportDialogs(Vec); + +impl ExportDialogs { + fn find(&self, id: DialogId) -> Option<&Open> { + self.0.iter().find(|o| o.id == id) + } + + /// The id of the dialog opened last, for a caller that opened it through a kind's own `open`. + pub(super) fn last_id(&self) -> Option { + self.0.last().map(|o| o.id) + } +} + +/// `ids` paired with `labels` as the options of a choice row. +pub(super) fn options>(ids: &[&'static str], labels: &[&'static str]) -> Vec<(String, L)> { + ids.iter().zip(labels).map(|(id, label)| (id.to_string(), L::from(label))).collect() +} + +/// Opens `dialog` as the export dialog `kind` and records it; `None` without a window. A dialog of the same key +/// replaces the one open, and its record. +pub(crate) fn open(app: &mut VectorcraftApp, kind: Export, selection: bool, dialog: HostedParamDialog) -> Option { + let options = match &kind { + Export::EpsCustom { parent } => HeldOptions { parent: Some(*parent), cancel: None }, + _ => HeldOptions::default(), + }; + let id = host::open_held_with(app, dialog, answer, options)?; + app.export_dialogs.0.retain(|o| o.id != id); + app.export_dialogs.0.push(Open { id, kind, selection, after: None }); + Some(id) +} + +/// Sets `fields` on the open dialog `id`, as the user editing its rows would. +pub(super) fn set_fields(app: &VectorcraftApp, id: DialogId, fields: &[(&str, Value)]) -> Result<(), String> { + let ctx = app.ui_ctx.clone().ok_or("no window")?; + // PLAN: assumed `VectorcraftApp::dialogs(&self) -> Option` (wg.S1) + let dialogs = app.dialogs().ok_or("no window")?; + let fields: Vec<(String, Value)> = fields.iter().map(|(k, v)| (k.to_string(), v.clone())).collect(); + dialogs.with(|host| host.set_json_fields(&ctx, id, &fields)) +} + +/// OK of the dialog `result` is from: its kind's `confirm`, and the step that follows kept for [`pump`]. +fn answer(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> { + let (id, kind, selection) = + app.export_dialogs.find(result.id).map(|o| (o.id, o.kind.clone(), o.selection)).ok_or("this export dialog is no longer open")?; + let open = Open { id, kind, selection, after: None }; + let after = confirm(app, &open, &result.fields)?; + if let Some(record) = app.export_dialogs.0.iter_mut().find(|o| o.id == id) { + record.after = after; + } + Ok(()) +} + +fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result { + match &open.kind { + Export::As => export_as::confirm(app, open, fields), + Export::Raster { .. } => png_options::confirm(app, open, fields), + Export::Svg { .. } => svg_options::confirm(app, open, fields), + Export::Eps => eps_options::confirm(app, open, fields), + // PLAN: assumed `eps_options::confirm_custom(app, &Open, &DialogFields) -> Result` (export-w11) + Export::EpsCustom { .. } => eps_options::confirm_custom(app, open, fields), + Export::Dxf => dxf_options::confirm(app, open, fields), + Export::Hpgl { .. } => hpgl_options::confirm(app, open, fields), + Export::Office => office_export::confirm(app, open, fields), + Export::Text => text_export::confirm(app, open, fields), + Export::Save { .. } => save_options::confirm(app, open, fields), + } +} + +/// Reports a failed step on the status line. +fn report(app: &mut VectorcraftApp, result: Result) { + if let Err(e) = result { + app.status(e); + } +} + +/// Once per frame: answers the rows' requests of each open export dialog, and runs the step after a confirmed +/// dialog that has closed. Each dialog's requests are taken once, so a second pass in the same frame finds none. +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + // PLAN: assumed `VectorcraftApp::dialogs(&self) -> Option` (wg.S1) + let Some(dialogs) = app.dialogs() else { return }; + let ids: Vec = app.export_dialogs.0.iter().map(|o| o.id).collect(); + for id in ids { + let taken = dialogs.with(|host| host.get_mut_by_id::(id).map(|d| (d.take_footer_action(), d.take_actions()))); + let Some(open) = app.export_dialogs.find(id) else { continue }; + let (kind, selection) = (open.kind.clone(), open.selection); + let Some((footer, actions)) = taken else { + // The dialog closed: the step after an OK runs, a cancelled one has none. + if let Some(i) = app.export_dialogs.0.iter().position(|o| o.id == id) { + let record = app.export_dialogs.0.remove(i); + if let Some(after) = record.after { + let result = after(app); + report(app, result); + } + } + continue; + }; + if footer.as_deref() == Some("browser") && matches!(kind, Export::Svg { .. }) { + // PLAN: assumed `svg_options::browser_preview(app, id) -> Result` (export-w10) + let result = svg_options::browser_preview(app, id); + report(app, result); + } + for action in actions { + match (&kind, action.as_str()) { + // PLAN: assumed `eps_options::open_custom(app, parent: DialogId)` (export-w11) + (Export::Eps, "custom") => eps_options::open_custom(app, id), + // PLAN: assumed `hpgl_options::pen_ask(app, id, selection) -> Result<(), String>` (export-w11) + (Export::Hpgl { .. }, "penTable") => { + let result = hpgl_options::pen_ask(app, id, selection); + report(app, result); + } + _ => {} + } + } + } +} diff --git a/crates/ui-egui/src/dialogs/office_export.rs b/crates/ui-egui/src/dialogs/office_export.rs index 45893bf156..7b1a6fcab1 100644 --- a/crates/ui-egui/src/dialogs/office_export.rs +++ b/crates/ui-egui/src/dialogs/office_export.rs @@ -1,71 +1,86 @@ //! File → Save for Office Documents…: an artboard as a PNG for office documents and slides, at //! 72, 150 or 300 ppi, on white or transparent. Fields are `document.exportForOffice` params. +use craft_ui::contract::Bind; +use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft_ui::runtime::env::Label; use serde_json::{Value, json}; +use super::export_host::{self, After, Export, Open}; use super::png_options::{RESOLUTION_LABELS, RESOLUTIONS}; -use super::{DialogSpec, form}; -use crate::state::Dialog; -use crate::theme::Tokens; -use crate::{VectorcraftApp, io, widgets}; +use crate::{VectorcraftApp, io}; +/// The dialog's key. pub(crate) const KIND: &str = "saveForOffice"; -pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |_| tl!("Save for Office Documents").into(), - body, - confirm, - ok: Some("Save…"), - min_width: 340.0, - inputs: |_| &["path"], - ..DialogSpec::FORM -}; +/// The document's artboards as the dialog needs them: their names and the size each has at every resolution +/// (`sizes[board][resolution]`), worked out when the dialog opens. +struct Boards { + names: Vec, + sizes: Vec>, +} + +impl Boards { + fn of(doc: &vectorcraft_doc::Document) -> Self { + let sizes = doc + .artboards + .iter() + .map(|a| { + RESOLUTIONS + .iter() + .map(|ppi| { + let (w, h) = vectorcraft_render::region_pixels(a.rect, ppi / 72.0); + format!("{w} × {h} px") + }) + .collect() + }) + .collect(); + Boards { names: doc.artboards.iter().map(|a| a.name.clone()).collect(), sizes } + } +} + +/// A number field's value, also when a client set it as the text of a choice's id. +fn number(fields: &DialogFields, key: &str) -> Option { + fields.number(key).or_else(|| fields.text(key)?.parse().ok()) +} + +fn params(boards: &Boards, fields: &DialogFields) -> Vec { + let ppi = number(fields, "ppi").unwrap_or(RESOLUTIONS[1]); + let at = RESOLUTIONS.iter().position(|r| *r == ppi).unwrap_or(1); + let board = (number(fields, "artboard").unwrap_or(0.0).max(0.0) as usize).min(boards.names.len().saturating_sub(1)); + let resolutions = RESOLUTIONS.iter().zip(RESOLUTION_LABELS.iter()).map(|(r, label)| (r.to_string(), Label::from(*label))).collect(); + let mut rows = vec![Param::new("ppi", tl!("Resolution:"), ParamKind::choice(resolutions, Some(RESOLUTIONS[1].to_string())))]; + if boards.names.len() > 1 { + let names = boards.names.iter().enumerate().map(|(i, name)| (i.to_string(), Label::from(name.clone()))).collect(); + rows.push(Param::new("artboard", tl!("Artboard:"), ParamKind::choice(names, Some("0".into())))); + } + let size = boards.sizes.get(board).and_then(|s| s.get(at)).cloned().unwrap_or_default(); + rows.push(Param::read_only_text("size", tl!("Size:"), size)); + rows.push(Param::new("transparent", tl!("Transparent Background"), ParamKind::bool(false))); + rows +} /// Open the dialog (150 ppi on white, the first artboard). pub fn open(app: &mut VectorcraftApp) -> Result { - app.session.active().ok_or("no document")?; - app.ui.dialog = Some(Dialog::new(KIND, json!({"ppi": RESOLUTIONS[1], "transparent": false, "artboard": 0}))); + let boards = Boards::of(&app.session.active().ok_or("no document")?.doc); + let ctx = app.ui_ctx.clone().ok_or("no window")?; + let mut fields = DialogFields::from_pairs([("ppi", RESOLUTIONS[1].to_string()), ("artboard", "0".to_string())]); + fields.set("transparent", false); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { + let rows = params(&boards, fields); + ParamDialog::new(KIND, tl!("Save for Office Documents"), rows).values(Bind::bound(fields)).ok_label(Label::from("Save…")) + }); + export_host::open(app, Export::Office, false, dialog).ok_or("no window")?; Ok(Value::Null) } -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let t = Tokens::get(ui.ctx()); - let label = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(text).color(t.text_dim)); - let Some(doc) = app.session.active().map(|st| &st.doc) else { return true }; - let ppi = d.f64("ppi", RESOLUTIONS[1]); - let board = (d.f64("artboard", 0.0).max(0.0) as usize).min(doc.artboards.len().saturating_sub(1)); - egui::Grid::new("office-export").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| { - label(ui, tl!("Resolution:")); - let at = RESOLUTIONS.iter().position(|r| *r == ppi).unwrap_or(1); - if let Some(i) = widgets::dropdown(ui, "office-ppi", RESOLUTION_LABELS[at], &RESOLUTION_LABELS[..RESOLUTIONS.len()], 160.0) - && let Some(r) = RESOLUTIONS.get(i) - { - d.fields.insert("ppi".into(), json!(r)); - } - ui.end_row(); - if doc.artboards.len() > 1 { - label(ui, tl!("Artboard:")); - let names: Vec<&str> = doc.artboards.iter().map(|a| a.name.as_str()).collect(); - if let Some(i) = widgets::dropdown_names(ui, "office-artboard", names.get(board).copied().unwrap_or_default(), &names, 160.0) { - d.fields.insert("artboard".into(), json!(i)); - } - ui.end_row(); - } - if let Some(a) = doc.artboards.get(board) { - label(ui, tl!("Size:")); - let (w, h) = vectorcraft_render::region_pixels(a.rect, ppi / 72.0); - ui.label(egui::RichText::new(format!("{w} × {h} px")).color(t.text)); - ui.end_row(); - } - }); - ui.add_space(8.0); - form::check(ui, d, "transparent", tl!("Transparent Background")); - false -} - /// Pick the file and write it (the command runs first: bad options keep the dialog open). -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let path = io::save_command_output(app, "document.exportForOffice", "png", form::params(d))?; - app.ui.dialog = None; - Ok(json!({ "path": path })) +pub(super) fn confirm(app: &mut VectorcraftApp, _open: &Open, fields: &DialogFields) -> Result { + let params = json!({ + "ppi": number(fields, "ppi").unwrap_or(RESOLUTIONS[1]), + "artboard": number(fields, "artboard").unwrap_or(0.0).max(0.0) as u64, + "transparent": fields.bool("transparent").unwrap_or(false), + }); + io::save_command_output(app, "document.exportForOffice", "png", params)?; + Ok(None) } diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index 6d388f7950..db37d67e69 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -1,11 +1,11 @@ -//! Export As and the raster options dialogs, drawn headlessly. +//! Export As, driven through the dialog host headlessly. use std::cell::RefCell; use std::rc::Rc; -use serde_json::json; +use craft_ui::dialog::{DialogHost, DialogId}; +use serde_json::{Value, json}; use vectorcraft_engine::Session; -use vectorcraft_engine::cmd::fileio; use super::*; use crate::Services; @@ -32,55 +32,68 @@ pub(super) fn app_saving(artboards: usize, pick: fn(&crate::FilePick) -> String) ..Default::default() }; let mut app = VectorcraftApp::new(Session::new(), services); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + app.ui_ctx = Some(ctx); app.run("file.new", json!({"width": 60, "height": 40, "artboards": artboards})).unwrap(); app.run("paint.setStroke", json!({"none": true})).unwrap(); app.run("shape.ellipse", json!({"x": 5, "y": 4, "width": 30, "height": 20})).unwrap(); (app, written) } -/// One headless frame of the dialog layer. +/// One headless frame: the app's pass, then the dialog layer's pump. pub(super) fn frame(app: &mut VectorcraftApp) { - let ctx = egui::Context::default(); - theme::install_fonts(&ctx); - let mut out = ctx.run_ui(Default::default(), |ui| show(app, ui.ctx())); + let ctx = app.ui_ctx.clone().expect("a test app has a window"); + let mut out = ctx.run_ui(Default::default(), |ui| app.ui(ui)); out.textures_delta.clear(); + super::host::pump(app, &ctx); } -pub(super) fn kind(app: &VectorcraftApp) -> Option<&str> { - app.ui.dialog.as_ref().map(|d| d.kind.as_str()) +/// Runs `f` on the host with the top dialog's id; `None` when no dialog is open. +fn on_top(app: &VectorcraftApp, f: impl FnOnce(&mut DialogHost, &egui::Context, DialogId) -> R) -> Option { + let ctx = app.ui_ctx.clone()?; + app.dialogs()?.with(|host| { + let id = host.open_dialogs().last()?.id; + Some(f(host, &ctx, id)) + }) } -pub(super) fn set(app: &mut VectorcraftApp, field: &str, value: serde_json::Value) { - app.ui.dialog.as_mut().expect("a dialog is open").fields.insert(field.into(), value); +/// The key of the top dialog, `None` when none is open. +pub(super) fn kind(app: &VectorcraftApp) -> Option { + app.dialogs().and_then(|d| d.with(|host| host.open_dialogs().last().and_then(|o| o.key.clone()))) +} + +/// The top dialog's values as JSON. +pub(super) fn fields(app: &VectorcraftApp) -> Value { + app.dialogs().and_then(|d| d.with(|host| host.open_dialogs().last().and_then(|o| o.fields.clone()))).unwrap_or(Value::Null) +} + +/// Sets a value of the top dialog as the user editing it would. +pub(super) fn set(app: &mut VectorcraftApp, field: &str, value: Value) { + on_top(app, |host, ctx, id| host.set_json_field(ctx, id, field, value)).expect("a dialog is open").expect("the field is set"); +} + +/// Presses OK on the top dialog: the first frame runs its confirmation, the second closes it and runs what follows. +pub(super) fn confirm(app: &mut VectorcraftApp) { + on_top(app, |host, ctx, id| host.confirm_by_id(ctx, id)).expect("a dialog is open"); + frame(app); + frame(app); +} + +/// Cancels the top dialog. +fn cancel(app: &mut VectorcraftApp) { + on_top(app, |host, ctx, id| host.cancel_by_id(ctx, id)).expect("a dialog is open"); + frame(app); + frame(app); } pub(super) fn names(w: &Written) -> Vec { w.borrow().iter().map(|(p, _)| p.clone()).collect() } -#[test] -fn png_options_draw_and_export_with_the_chosen_options() { - let (mut app, written) = app(2); - png_options::open(&mut app, fileio::format("png").unwrap(), json!({"format": "png", "path": "/out/a.png", "artboard": 1})); - assert_eq!(kind(&app), Some("pngOptions")); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.f64("ppi", 0.0), d.str("background"), d.str("antiAlias"), d.bool("interlaced")), (72.0, "transparent".into(), "art".into(), false)); - assert_eq!(d.fields["__size"], json!([60.0, 40.0]), "the chosen artboard"); - frame(&mut app); - // Other resolution and an Other background colour draw their own field and colour button. - set(&mut app, "__otherPpi", json!(true)); - set(&mut app, "ppi", json!(200)); - set(&mut app, "background", json!("#204080")); - set(&mut app, "antiAlias", json!("type")); - set(&mut app, "interlaced", json!(true)); - frame(&mut app); - assert_eq!(confirm(&mut app).unwrap()["path"], "/out/a.png"); - assert!(app.ui.dialog.is_none()); - let png = written.borrow()[0].1.clone(); - assert_eq!(png[28], 1, "interlaced"); - let phys = png.windows(4).position(|w| w == b"pHYs").unwrap(); - assert_eq!(&png[phys + 4..phys + 8], ((200.0f64 / 0.0254).round() as u32).to_be_bytes()); - let img = craft_image_codecs::decode(&png) +/// The picture a raster file holds. +pub(super) fn rgba(bytes: &[u8]) -> image::RgbaImage { + craft_image_codecs::decode(bytes) .map(|__cimg| { let (__w, __h) = __cimg.dimensions(); match (__cimg.layout(), __cimg.sample_type()) { @@ -97,27 +110,17 @@ fn png_options_draw_and_export_with_the_chosen_options() { } }) .unwrap() - .to_rgba8(); - assert_eq!(img.dimensions(), (167, 111), "60 × 40 pt at 200 ppi"); - assert_eq!(img.get_pixel(0, 0).0, [0x20, 0x40, 0x80, 255]); - // JPEG Options: quality, and no transparent background. - png_options::open(&mut app, fileio::format("jpg").unwrap(), json!({"format": "jpg", "path": "/out/a.jpg"})); - assert_eq!(kind(&app), Some("jpgOptions")); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("background"), "white"); - frame(&mut app); - set(&mut app, "quality", json!(40)); - confirm(&mut app).unwrap(); - assert_eq!(&written.borrow()[1].1[..2], [0xFF, 0xD8]); + .to_rgba8() } #[test] fn export_as_png_picks_the_file_then_shows_png_options() { let (mut app, written) = app(1); app.run("file.export.png", json!({})).unwrap(); - assert_eq!(kind(&app), Some("pngOptions")); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("path"), "/out/Untitled-1.png"); + assert_eq!(kind(&app).as_deref(), Some("pngOptions")); + assert_eq!(fields(&app)["path"], "/out/Untitled-1.png"); assert!(written.borrow().is_empty()); - app.ui.dialog = None; + cancel(&mut app); let r = app.run("file.export.png", json!({"path": "/x/a.png", "ppi": 144})).unwrap(); assert_eq!(r["path"], "/x/a.png"); assert_eq!(&written.borrow()[0].1[16..20], 120u32.to_be_bytes(), "60 pt at 144 ppi"); @@ -129,49 +132,28 @@ fn export_as_png_picks_the_file_then_shows_png_options() { fn export_as_png_exports_the_active_artboard() { let (mut app, written) = app(2); // The ellipse is on the first artboard; the second is empty. - let opaque = |bytes: &[u8]| { - craft_image_codecs::decode(bytes) - .map(|__cimg| { - let (__w, __h) = __cimg.dimensions(); - match (__cimg.layout(), __cimg.sample_type()) { - (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { - image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) - } - (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { - image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) - } - (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { - image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) - } - _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), - } - }) - .unwrap() - .to_rgba8() - .pixels() - .any(|p| p.0[3] > 0) - }; + let opaque = |bytes: &[u8]| rgba(bytes).pixels().any(|p| p.0[3] > 0); app.view_mut().unwrap().artboard = 1; app.run("file.export.png", json!({})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["artboard"], json!(1)); + assert_eq!(fields(&app)["artboard"], json!(1)); frame(&mut app); - confirm(&mut app).unwrap(); + confirm(&mut app); assert!(!opaque(&written.borrow()[0].1), "the second artboard, which is empty"); app.view_mut().unwrap().artboard = 0; app.run("file.export.png", json!({})).unwrap(); frame(&mut app); - confirm(&mut app).unwrap(); + confirm(&mut app); assert!(opaque(&written.borrow()[1].1), "the first artboard, with the ellipse"); // A choice given is kept. app.run("file.export.png", json!({"useArtboards": false})).unwrap(); - assert!(app.ui.dialog.as_ref().unwrap().fields.get("artboard").is_none_or(serde_json::Value::is_null)); - app.ui.dialog = None; + assert!(fields(&app).get("artboard").is_none_or(Value::is_null)); + cancel(&mut app); // Artboards the Artboard tool selected: one file each. app.select_tool("artboard"); app.session.set_tool_option("selected", &json!([0, 1])); app.run("file.export.png", json!({})).unwrap(); frame(&mut app); - confirm(&mut app).unwrap(); + confirm(&mut app); assert_eq!(names(&written)[2..], ["/out/Untitled-1-Artboard-1.png", "/out/Untitled-1-Artboard-2.png"]); } @@ -179,48 +161,29 @@ fn export_as_png_exports_the_active_artboard() { fn export_as_with_a_range_then_png_options_writes_one_file_per_artboard() { let (mut app, written) = app(3); app.run("file.exportAs", json!({})).unwrap(); - assert_eq!(kind(&app), Some("exportAs")); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("range"), "1-3"); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); + assert_eq!(fields(&app)["range"], "1-3"); frame(&mut app); set(&mut app, "useArtboards", json!(true)); set(&mut app, "all", json!(false)); set(&mut app, "range", json!("1, 3")); frame(&mut app); - confirm(&mut app).unwrap(); - assert_eq!(kind(&app), Some("pngOptions"), "PNG Options follow"); + confirm(&mut app); + assert_eq!(kind(&app).as_deref(), Some("pngOptions"), "PNG Options follow"); assert!(written.borrow().is_empty(), "nothing is written before the options are confirmed"); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.str("path"), d.str("range"), d.str("background")), ("/out/Untitled-1.png".into(), "1, 3".into(), "transparent".into())); - assert!(!d.fields.contains_key("__size"), "two artboards: no single size to show"); + let d = fields(&app); + assert_eq!((&d["path"], &d["range"], &d["background"]), (&json!("/out/Untitled-1.png"), &json!("1, 3"), &json!("transparent"))); frame(&mut app); set(&mut app, "ppi", json!(144)); set(&mut app, "interlaced", json!(true)); set(&mut app, "antiAlias", json!("none")); frame(&mut app); - let r = confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); - assert_eq!(r["files"].as_array().unwrap().len(), 2, "{r}"); + confirm(&mut app); + assert!(kind(&app).is_none()); assert_eq!(names(&written), ["/out/Untitled-1-Artboard-1.png", "/out/Untitled-1-Artboard-3.png"]); let png = &written.borrow()[0].1; assert_eq!(png[28], 1, "interlaced"); - let img = craft_image_codecs::decode(png) - .map(|__cimg| { - let (__w, __h) = __cimg.dimensions(); - match (__cimg.layout(), __cimg.sample_type()) { - (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { - image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) - } - (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { - image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) - } - (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { - image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) - } - _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), - } - }) - .unwrap() - .to_rgba8(); + let img = rgba(png); assert_eq!(img.dimensions(), (120, 80), "144 ppi"); assert!(img.pixels().all(|p| p[3] == 0 || p[3] == 255), "no anti-aliasing"); } @@ -229,333 +192,61 @@ fn export_as_with_a_range_then_png_options_writes_one_file_per_artboard() { fn a_bad_range_keeps_export_as_open() { let (mut app, written) = app(2); app.run("file.exportAs", json!({"useArtboards": true, "range": "5"})).unwrap(); - assert!(!app.ui.dialog.as_ref().unwrap().bool("all")); - assert!(confirm(&mut app).is_err()); - assert_eq!(kind(&app), Some("exportAs")); + assert_eq!(fields(&app)["all"], json!(false)); + confirm(&mut app); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); assert!(written.borrow().is_empty()); } -/// An emptied Range field shows an example of the artboard numbers it takes, as Save As's does. +/// Each format's Export As continues in its options dialog, writes nothing before that dialog's OK, and then +/// writes its files: (case, artboards, Export As params, the options' key, the files, the pages of a PDF, the +/// page size of a PDF of the art's bounds). #[test] -fn an_empty_export_as_range_shows_an_example() { - let (mut app, _) = app(2); - app.run("file.exportAs", json!({"useArtboards": true, "range": ""})).unwrap(); - let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); - assert!(text.lines().any(|l| l == "1-3, 5"), "{text}"); -} - -/// #5941: the Format list showed no scroll bar until the pointer came over it, so nothing told -/// the user that more formats lay below the last one shown, and it opened again where it was last -/// scrolled, with its first formats out of view. Opened with the pointer elsewhere and a format -/// near the end chosen, a list that does not show every format shows its bar, the chosen format shows -/// whole, and a list opened again after a scroll shows the same rows as when it first opened. -#[test] -fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format_in_view() { - fn walk(shape: &egui::Shape, clip: egui::Rect, texts: &mut Vec<(String, egui::Rect, egui::Rect)>, bars: &mut Vec) { - match shape { - egui::Shape::Text(t) => texts.push((t.galley.text().into(), t.visual_bounding_rect(), clip)), - egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect), - egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, texts, bars)), - _ => {} - } - } - // A built-in format six from the end of the built-in ones: out of view when the list opens at - // its top, and far enough from the end that a plug-in format another test adds after the - // built-in ones does not move the rows shown around it. The window is short enough that the - // list centered on it stops short of its end. - let built_in: Vec<_> = fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).collect(); - let labels: Vec<&str> = built_in.iter().map(|f| f.label).collect(); - let chosen = built_in.len().checked_sub(6).and_then(|i| built_in.get(i)).copied().expect("Export As lists formats"); - let (mut app, _) = app(1); - app.run("file.exportAs", json!({"format": chosen.id})).unwrap(); - let ctx = egui::Context::default(); - theme::install_fonts(&ctx); - theme::apply(&ctx, Default::default()); - // Every scroll area takes the bar at rest from the theme, whatever style the list sets itself. - assert_eq!(ctx.global_style().spacing.scroll, crate::widgets::list_scroll_style()); - let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1024.0, 280.0))); - let mut time = 0.0; - let popup = std::cell::RefCell::new(vec![]); - // The texts and bars painted on the open list (without the dialog under it), and every text. - let mut run = |app: &mut VectorcraftApp, events: Vec| { - time += 0.25; - let mut out = ctx.run_ui(egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }, |ui| { - show(app, ui.ctx()); - popup.replace(crate::widgets::top_popup_shapes(ui.ctx())); - }); - out.textures_delta.clear(); - let (mut texts, mut bars, mut all) = (vec![], vec![], vec![]); - popup.take().iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts, &mut bars)); - out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut all, &mut vec![])); - (texts, bars, all) - }; - let away = egui::Event::PointerMoved(egui::pos2(1.0, 1.0)); - run(&mut app, vec![away.clone()]); - let (_, _, texts) = run(&mut app, vec![]); - let field = texts.iter().find(|(s, ..)| s == chosen.label).map(|(_, r, _)| r.center()).expect("the Format field shows the chosen format"); - let click_at = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - // Opens the list, moves the pointer away and returns the list's rect, the format names drawn in - // it with their clip rects, and the bars drawn. - type Texts = Vec<(String, egui::Rect, egui::Rect)>; - type Run<'r> = dyn FnMut(&mut VectorcraftApp, Vec) -> (Texts, Vec, Texts) + 'r; - let open = |run: &mut Run<'_>, app: &mut VectorcraftApp| { - run(app, vec![egui::Event::PointerMoved(field), click_at(field, true)]); - run(app, vec![click_at(field, false)]); - run(app, vec![away.clone()]); - let (mut texts, mut bars) = (vec![], vec![]); - for _ in 0..4 { - (texts, bars, _) = run(app, vec![]); - } - let list = ctx - .memory(|m| { - m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id)) - }) - .expect("the Format list is open"); - let rows: Vec<_> = texts.into_iter().filter(|(s, r, _)| labels.contains(&s.as_str()) && list.contains_rect(*r)).collect(); - (list, rows, bars) - }; - let whole = |rows: &[(String, egui::Rect, egui::Rect)], name: &str| { - rows.iter().any(|(s, r, clip)| s == name && r.top() >= clip.top() && r.bottom() <= clip.bottom()) - }; - let tops = |rows: &[(String, egui::Rect, egui::Rect)]| rows.iter().map(|(s, r, _)| (s.clone(), r.top().round())).collect::>(); - let (list, rows, bars) = open(&mut run, &mut app); - assert!(!rows.is_empty(), "the Format list is open"); - assert!(whole(&rows, chosen.label), "the chosen format shows whole: {:?}", tops(&rows)); - // A list that shows every format needs no bar; one that does not shows its bar. - if rows.len() < labels.len() { - assert!( - bars.iter().any(|b| list.contains_rect(*b) && b.left() > list.center().x), - "the list's scroll bar is drawn at rest in {list:?}: {bars:?}" - ); - } - - // Scrolled, closed and opened again, the list shows the rows it first opened with, not the - // offset it was scrolled to. - run(&mut app, vec![egui::Event::PointerMoved(list.center())]); - let wheel = egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(0.0, 30.0), - modifiers: Default::default(), - phase: egui::TouchPhase::Move, - source: egui::MouseWheelSource::Unknown, - }; - run(&mut app, vec![wheel]); - let mut scrolled = vec![]; - for _ in 0..4 { - (scrolled, ..) = run(&mut app, vec![]); - } - let scrolled: Vec<_> = scrolled.into_iter().filter(|(s, r, _)| labels.contains(&s.as_str()) && list.contains_rect(*r)).collect(); - // Escape closes it: a list taller than the room beside its field covers the field. - let escape = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; - run(&mut app, vec![escape(true)]); - run(&mut app, vec![escape(false)]); - let (_, reopened, _) = open(&mut run, &mut app); - if rows.len() < labels.len() { - assert_ne!(tops(&scrolled), tops(&rows), "the wheel scrolled the list"); - } - assert_eq!(tops(&reopened), tops(&rows), "the reopened list shows the rows it first opened with"); - assert!(whole(&reopened, chosen.label), "the chosen format shows whole: {:?}", tops(&reopened)); -} - -/// #5941: the Format list stopped at the room on one side of its field, so a window with room for -/// every format still cut the list short. In windows of 1280×900 and 1000×856 the list shows every -/// built-in format whole, the grayed-out DWG row after them included, inside the window, without a -/// scroll bar. A plug-in format that another test adds or removes meanwhile is not counted. -#[test] -fn the_format_list_shows_every_format_when_the_window_has_room() { - fn walk(shape: &egui::Shape, clip: egui::Rect, texts: &mut Vec<(String, egui::Rect, egui::Rect)>, bars: &mut Vec) { - match shape { - egui::Shape::Text(t) => texts.push((t.galley.text().into(), t.visual_bounding_rect(), clip)), - egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect), - egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, texts, bars)), - _ => {} - } - } - let labels: Vec<&str> = - fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).map(|f| f.label).chain(["DWG (use DXF)"]).collect(); - for (width, height) in [(1280.0, 900.0), (1000.0, 856.0)] { - let case = format!("{width}×{height}"); - let (mut app, _) = app(1); - app.run("file.exportAs", json!({"format": "png"})).unwrap(); - let ctx = egui::Context::default(); - theme::install_fonts(&ctx); - theme::apply(&ctx, Default::default()); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, height)); - let mut time = 0.0; - let popup = std::cell::RefCell::new(vec![]); - // The texts and bars painted on the open list (without the dialog under it), and every text. - let mut run = |app: &mut VectorcraftApp, events: Vec| { - time += 0.25; - let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, time: Some(time), ..Default::default() }, |ui| { - show(app, ui.ctx()); - popup.replace(crate::widgets::top_popup_shapes(ui.ctx())); - }); - out.textures_delta.clear(); - let (mut texts, mut bars, mut all) = (vec![], vec![], vec![]); - popup.take().iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts, &mut bars)); - out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut all, &mut vec![])); - (texts, bars, all) - }; - let away = egui::Event::PointerMoved(egui::pos2(1.0, 1.0)); - run(&mut app, vec![away.clone()]); - let (_, _, all) = run(&mut app, vec![]); - let field = all.iter().find(|(s, ..)| s == "PNG").map(|(_, r, _)| r.center()).expect("the Format field shows PNG"); - let click = |pressed| egui::Event::PointerButton { pos: field, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - run(&mut app, vec![egui::Event::PointerMoved(field), click(true)]); - run(&mut app, vec![click(false)]); - run(&mut app, vec![away.clone()]); - let list_rect = || { - ctx.memory(|m| { - m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id)) - }) - }; - // A plug-in format that another test installs or removes changes the list's height, and the - // list is placed for its new height on the pass after. Read it once it keeps its rect. - let (mut texts, mut bars, mut list) = (vec![], vec![], None); - for _ in 0..12 { - (texts, bars, _) = run(&mut app, vec![]); - let now = list_rect(); - if now.is_some() && now == list { - break; +#[allow(clippy::type_complexity)] +fn a_format_continues_in_its_options_dialog() { + let cases: [(&str, usize, Value, &str, Vec<&str>, Option, Option<(f64, f64)>); 3] = [ + ( + "svg with artboards", + 2, + json!({"format": "svg", "useArtboards": true}), + "svgOptions", + vec!["/out/Untitled-1-Artboard-1.svg", "/out/Untitled-1-Artboard-2.svg"], + None, + None, + ), + ("pdf of the art", 2, json!({"format": "pdf"}), "savePdf", vec!["/out/Untitled-1.pdf"], Some(1), Some((30.0, 20.0))), + ( + "pdf of two artboards", + 3, + json!({"format": "pdf", "useArtboards": true, "range": "2-3"}), + "savePdf", + vec!["/out/Untitled-1.pdf"], + Some(2), + None, + ), + ]; + for (case, boards, params, options, files, pages, bounds) in cases { + let (mut app, written) = app(boards); + app.run("file.exportAs", params).unwrap(); + confirm(&mut app); + assert_eq!(kind(&app).as_deref(), Some(options), "{case}: its options follow"); + assert!(fields(&app)["path"].as_str().is_some_and(|p| p.starts_with("/out/Untitled-1.")), "{case}: {}", fields(&app)); + assert!(written.borrow().is_empty(), "{case}: nothing is written before OK"); + frame(&mut app); + confirm(&mut app); + assert!(kind(&app).is_none(), "{case}"); + assert_eq!(names(&written), files, "{case}"); + if let Some(pages) = pages { + let pdf = vectorcraft_pdf::import(&written.borrow()[0].1).unwrap(); + assert_eq!(pdf.artboards.len(), pages, "{case}: one page each"); + if let Some(size) = bounds { + let rect = pdf.artboards[0].rect; + assert_eq!((rect.width().round(), rect.height().round()), size, "{case}: the ellipse's bounds"); } - list = now; } - let list = list.expect("the Format list is open"); - assert!(screen.contains_rect(list), "{case}: the list {list:?} is inside the window"); - let whole: Vec<&str> = labels - .iter() - .copied() - .filter(|name| { - texts.iter().any(|(s, r, clip)| s == name && list.contains_rect(*r) && r.top() >= clip.top() && r.bottom() <= clip.bottom()) - }) - .collect(); - assert_eq!(whole, labels, "{case}: every format shows whole in {list:?}"); - assert!(bars.is_empty(), "{case}: a list that shows every format draws no scroll bar: {bars:?}"); } } -#[test] -fn svg_continues_in_svg_options() { - let (mut app, written) = app(2); - app.run("file.exportAs", json!({"format": "svg", "useArtboards": true})).unwrap(); - confirm(&mut app).unwrap(); - assert_eq!(kind(&app), Some("svgOptions"), "the SVG options follow"); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.str("path"), d.bool("useArtboards"), d.str("range")), ("/out/Untitled-1.svg".into(), true, "all".into())); - frame(&mut app); - confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); - assert_eq!(names(&written), ["/out/Untitled-1-Artboard-1.svg", "/out/Untitled-1-Artboard-2.svg"]); -} - -/// Without Use Artboards, a PDF continues in Save PDF too, without its artboard choice, and the -/// file is one page of the art's bounds. Its options apply: a drawing 10 m long is written at -/// full size in points with "Write pages longer than 200 in at full size in points" (on by -/// default), and with a `UserUnit` without it. -#[test] -fn pdf_art_continues_in_the_save_pdf_dialog() { - let (mut app, written) = app(2); - app.run("file.exportAs", json!({"format": "pdf"})).unwrap(); - confirm(&mut app).unwrap(); - assert_eq!(kind(&app), Some("savePdf"), "the PDF options follow"); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("path"), "/out/Untitled-1.pdf"); - assert!(written.borrow().is_empty()); - frame(&mut app); - assert_eq!(confirm(&mut app).unwrap()["path"], "/out/Untitled-1.pdf"); - let pdf = vectorcraft_pdf::import(&written.borrow()[0].1).unwrap(); - assert_eq!(pdf.artboards.len(), 1); - assert_eq!((pdf.artboards[0].rect.width().round(), pdf.artboards[0].rect.height().round()), (30.0, 20.0), "the ellipse's bounds"); - - app.run("shape.rectangle", json!({"x": 0, "y": 100, "width": 28_346.46, "height": 50})).unwrap(); - app.run("file.exportAs", json!({"format": "pdf"})).unwrap(); - confirm(&mut app).unwrap(); - frame(&mut app); - confirm(&mut app).unwrap(); - let bytes = written.borrow()[1].1.clone(); - assert!(!String::from_utf8_lossy(&bytes).contains("/UserUnit")); - let width = vectorcraft_pdf::import(&bytes).unwrap().artboards[0].rect.width(); - assert!((28_346.0..28_350.0).contains(&width), "{width}"); - - app.run("file.exportAs", json!({"format": "pdf"})).unwrap(); - confirm(&mut app).unwrap(); - set(&mut app, "longPagesInPoints", json!(false)); - frame(&mut app); - confirm(&mut app).unwrap(); - let bytes = written.borrow()[2].1.clone(); - assert!(String::from_utf8_lossy(&bytes).contains("/UserUnit")); - let width = vectorcraft_pdf::import(&bytes).unwrap().artboards[0].rect.width(); - assert!((28_346.0..28_350.0).contains(&width), "{width}"); -} - -#[test] -fn jpeg_and_webp_options_draw_and_export() { - let (mut app, written) = app(1); - app.run("file.exportAs", json!({"format": "jpg"})).unwrap(); - confirm(&mut app).unwrap(); - assert_eq!(kind(&app), Some("jpgOptions")); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.str("background"), d.f64("quality", 0.0)), ("white".into(), 90.0)); - assert_eq!(d.fields["__size"], json!([30.0, 20.0]), "the art's bounds"); - frame(&mut app); - set(&mut app, "background", json!("#204080")); - set(&mut app, "quality", json!(70)); - frame(&mut app); - assert_eq!(confirm(&mut app).unwrap()["path"], "/out/Untitled-1.jpg"); - let img = craft_image_codecs::decode(&written.borrow()[0].1) - .map(|__cimg| { - let (__w, __h) = __cimg.dimensions(); - match (__cimg.layout(), __cimg.sample_type()) { - (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { - image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) - } - (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { - image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) - } - (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { - image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) - } - _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), - } - }) - .unwrap() - .to_rgb8(); - assert_eq!(img.dimensions(), (30, 20)); - let px = img.get_pixel(0, 0); - assert!(px[2] > 100 && px[0] < 60, "the background colour: {px:?}"); - - app.run("file.exportAs", json!({"format": "webp", "useArtboards": true})).unwrap(); - confirm(&mut app).unwrap(); - assert_eq!(kind(&app), Some("webpOptions")); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["__size"], json!([60.0, 40.0]), "the one artboard"); - set(&mut app, "__otherPpi", json!(true)); - set(&mut app, "ppi", json!(36)); - frame(&mut app); - confirm(&mut app).unwrap(); - let (path, bytes) = written.borrow().last().cloned().unwrap(); - assert_eq!(path, "/out/Untitled-1.webp", "one artboard is one file, named as picked"); - assert_eq!( - craft_image_codecs::decode(&bytes) - .map(|__cimg| { - let (__w, __h) = __cimg.dimensions(); - match (__cimg.layout(), __cimg.sample_type()) { - (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { - image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) - } - (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { - image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) - } - (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { - image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) - } - _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), - } - }) - .unwrap() - .width(), - 30 - ); -} - #[test] fn old_ids_and_agents_export_directly_with_a_path() { let (mut app, written) = app(2); @@ -563,7 +254,7 @@ fn old_ids_and_agents_export_directly_with_a_path() { assert_eq!(r["path"], "/x/a.png"); let r = app.run("file.exportAs", json!({"path": "/x/b.webp", "useArtboards": true})).unwrap(); assert_eq!(r["files"], json!(["/x/b-Artboard-1.webp", "/x/b-Artboard-2.webp"])); - assert!(app.ui.dialog.is_none()); + assert!(kind(&app).is_none()); assert_eq!(written.borrow().len(), 3); assert_eq!(&written.borrow()[0].1[16..20], 120u32.to_be_bytes(), "60 pt at 144 ppi"); assert!(crate::menus::enabled(&app, "file.exportAs")); @@ -576,13 +267,13 @@ fn nothing_to_export_keeps_export_as_open_before_the_save_dialog() { app.run("select.all", json!({})).unwrap(); app.run("edit.clear", json!({})).unwrap(); app.run("file.exportAs", json!({})).unwrap(); - assert!(confirm(&mut app).unwrap_err().contains("no visible art")); - assert_eq!(kind(&app), Some("exportAs")); + confirm(&mut app); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); // With Use Artboards the empty artboard is exported. set(&mut app, "useArtboards", json!(true)); app.services.pick_save = Some(Box::new(|p: &crate::FilePick| Some(format!("/out/{}", p.name)))); - confirm(&mut app).unwrap(); - assert_eq!(kind(&app), Some("pngOptions")); + confirm(&mut app); + assert_eq!(kind(&app).as_deref(), Some("pngOptions")); assert!(written.borrow().is_empty()); } @@ -595,27 +286,12 @@ fn art_a_plot_leaves_out_keeps_hpgl_export_as_open_before_the_save_dialog() { app.run("select.all", json!({})).unwrap(); app.run("transparency.set", json!({"opacity": 0})).unwrap(); app.run("file.exportAs", json!({"format": "hpgl"})).unwrap(); - assert!(confirm(&mut app).unwrap_err().contains("no visible art")); - assert_eq!(kind(&app), Some("exportAs")); + confirm(&mut app); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); app.services.pick_save = Some(Box::new(|p: &crate::FilePick| Some(format!("/out/{}", p.name)))); set(&mut app, "format", json!("png")); - confirm(&mut app).unwrap(); - assert_eq!(kind(&app), Some("pngOptions")); -} - -#[test] -fn pdf_artboards_continue_in_the_save_pdf_dialog() { - let (mut app, written) = app(3); - app.run("file.exportAs", json!({"format": "pdf", "useArtboards": true, "range": "2-3"})).unwrap(); - confirm(&mut app).unwrap(); - assert_eq!(kind(&app), Some("savePdf"), "the PDF options follow"); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.str("path"), d.str("range")), ("/out/Untitled-1.pdf".into(), "2-3".into())); - assert!(written.borrow().is_empty()); - frame(&mut app); - confirm(&mut app).unwrap(); - let pdf = vectorcraft_pdf::import(&written.borrow()[0].1).unwrap(); - assert_eq!(pdf.artboards.len(), 2, "one page per artboard in the range"); + confirm(&mut app); + assert_eq!(kind(&app).as_deref(), Some("pngOptions")); } /// #546, #550: Export As with Use Artboards and a range writes the chosen artboard alone in every @@ -629,12 +305,14 @@ fn export_as_writes_only_the_chosen_artboard_in_every_format() { set(&mut app, "useArtboards", json!(true)); set(&mut app, "all", json!(false)); set(&mut app, "range", json!(range)); - confirm(&mut app).unwrap(); - // The format's own options, then the file. - while app.ui.dialog.is_some() { - frame(&mut app); - confirm(&mut app).unwrap(); + // Export As, the format's own options, then the file. + for _ in 0..4 { + if kind(&app).is_none() { + break; + } + confirm(&mut app); } + assert!(kind(&app).is_none(), "{format} {range}: every dialog confirmed"); assert_eq!(names(&written), [format!("/out/Untitled-1.{format}")], "{format} {range}"); if !ellipse.is_empty() { let text = String::from_utf8_lossy(&written.borrow()[0].1).into_owned(); @@ -643,51 +321,3 @@ fn export_as_writes_only_the_chosen_artboard_in_every_format() { } } } - -/// The Enter that closed the save panel, still held as the format's options open, doesn't write -/// the file; Enter pressed again after it is let go does. So for every options dialog Export As -/// opens after its panel, an exporter plug-in's included (as Save As's options). -#[test] -fn the_enter_that_closed_the_save_panel_does_not_confirm_the_options() { - let params = r#"{"speed":{"type":"number","min":1,"max":100,"default":40}}"#; - let module = wat::parse_str(vectorcraft_plugins::wat::returning( - &vectorcraft_plugins::wat::exporter("test.ui.held", r#"["tuh"]"#, params), - r#"{"dataBase64":"SGk="}"#, - )) - .unwrap(); - let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; - let ctx = egui::Context::default(); - theme::install_fonts(&ctx); - let frame = |app: &mut VectorcraftApp, events: Vec| { - let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui.ctx())); - out.textures_delta.clear(); - }; - // Each format whose options follow the panel (PDF's: Save PDF, with Use Artboards on or off). - let formats = [ - ("png", false), - ("svg", false), - ("pdf", true), - ("pdf", false), - ("txt", false), - ("dxf", false), - ("eps", false), - ("plugin.test.ui.held", false), - ]; - for (format, artboards) in formats { - let (mut app, written) = app(1); - app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap(); - app.run("file.exportAs", json!({"format": format})).unwrap(); - set(&mut app, "useArtboards", json!(artboards)); - confirm(&mut app).unwrap(); - let options = kind(&app).map(str::to_string); - assert!(options.as_deref().is_some_and(|k| k != "exportAs"), "{format}: its options follow the panel, not {options:?}"); - frame(&mut app, vec![enter(true)]); - assert_eq!(kind(&app).map(str::to_string), options, "{format}: the Enter still held isn't the options'"); - assert!(written.borrow().is_empty(), "{format}: nothing written"); - frame(&mut app, vec![enter(false)]); - frame(&mut app, vec![enter(true)]); - assert!(app.ui.dialog.is_none(), "{format}: Enter pressed again confirms"); - assert!(!written.borrow().is_empty(), "{format}: and writes"); - } - vectorcraft_plugins::registry::remove("test.ui.held"); -} diff --git a/crates/ui-egui/src/dialogs/tests_export_selection.rs b/crates/ui-egui/src/dialogs/tests_export_selection.rs index 0500a55760..b13c3d194d 100644 --- a/crates/ui-egui/src/dialogs/tests_export_selection.rs +++ b/crates/ui-egui/src/dialogs/tests_export_selection.rs @@ -7,7 +7,7 @@ use std::rc::Rc; use serde_json::json; use vectorcraft_plugins::wat::{self as tpl, Echo}; -use super::tests_export::{Written, app_saving, frame, kind, names, set}; +use super::tests_export::{Written, app_saving, confirm, fields, frame, kind, names, rgba, set}; use super::*; /// The last file written, as text. @@ -32,55 +32,32 @@ fn paths_in(bytes: &[u8]) -> usize { String::from_utf8_lossy(vectorcraft_format::json_part(bytes)).matches("\"anchors\"").count() } -/// A PDF continues in Save PDF, without its artboard choice, and its options apply: the page is -/// the selected 10 m rectangle's crop (not the art's bounds, which take in the ellipse), with a -/// `UserUnit` once "Write pages longer than 200 in at full size in points" is turned off. +/// Every format with an options dialog shows it after the save panel, writes nothing before its OK, and OK +/// writes the selection alone, cropped to the selected 10×5 pt rectangle: the PDF's page, the PNG at 72 ppi, +/// the SVG's view box, the EPS bounding box and the DXF's extents. #[test] -fn export_selection_to_pdf_continues_in_save_pdf() { - let (mut app, written) = app_saving(2, |_| "/out/sel.pdf".into()); - app.run("shape.rectangle", json!({"x": 0, "y": 100, "width": 28_346.46, "height": 50})).unwrap(); - app.run("document.exportSelection", json!({})).unwrap(); - assert_eq!(kind(&app), Some("savePdf"), "the PDF options follow"); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.str("path"), "/out/sel.pdf"); - assert!(d.bool("__artBounds") && d.bool(export_as::SELECTION_FIELD)); - assert!(written.borrow().is_empty(), "nothing is written before OK"); - set(&mut app, "longPagesInPoints", json!(false)); - frame(&mut app); - assert_eq!(confirm(&mut app).unwrap()["path"], "/out/sel.pdf"); - assert!(app.ui.dialog.is_none()); - let bytes = written.borrow()[0].1.clone(); - assert!(String::from_utf8_lossy(&bytes).contains("/UserUnit"), "the dialog's option applies"); - let pdf = vectorcraft_pdf::import(&bytes).unwrap(); - assert_eq!(pdf.artboards.len(), 1); - let page = pdf.artboards[0].rect; - assert!((28_346.0..28_350.0).contains(&page.width()), "{}", page.width()); - assert_eq!(page.height().round(), 50.0, "the selection's crop"); -} - -/// Every format with an options dialog shows it after the save panel, and OK writes the -/// selection alone, cropped to the selected 10×5 pt rectangle: the PNG at 72 ppi, the SVG's view -/// box, the EPS bounding box and the DXF's extents. The mark is not kept with the options -/// remembered for the next export. -#[test] -fn export_selection_continues_in_each_format_s_options() { +fn export_selection_continues_in_each_formats_options() { let (mut app, written) = app_saving(2, |_| String::new()); app.run("shape.rectangle", json!({"x": 40, "y": 30, "width": 10, "height": 5})).unwrap(); - for (ext, options) in [("svg", "svgOptions"), ("png", "pngOptions"), ("eps", "epsOptions"), ("dxf", "dxfOptions")] { + for (ext, options) in [("pdf", "savePdf"), ("svg", "svgOptions"), ("png", "pngOptions"), ("eps", "epsOptions"), ("dxf", "dxfOptions")] { let path = format!("/out/sel.{ext}"); + let before = names(&written).len(); picking(&mut app, &path); app.run("document.exportSelection", json!({})).unwrap(); - assert_eq!(kind(&app), Some(options), "{ext}"); - assert!(app.ui.dialog.as_ref().unwrap().bool(export_as::SELECTION_FIELD), "{ext}"); - if ext == "png" { - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["__size"], json!([10.0, 5.0]), "the selection's size"); - } + assert_eq!(kind(&app).as_deref(), Some(options), "{ext}"); + assert_eq!(names(&written).len(), before, "{ext}: nothing is written before OK"); frame(&mut app); - confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none(), "{ext}"); + confirm(&mut app); + assert!(kind(&app).is_none(), "{ext}"); assert_eq!(names(&written).last(), Some(&path), "{ext}"); let text = last_text(&written); match ext { + "pdf" => { + let pdf = vectorcraft_pdf::import(&written.borrow().last().unwrap().1).unwrap(); + assert_eq!(pdf.artboards.len(), 1, "{ext}"); + let page = pdf.artboards[0].rect; + assert_eq!((page.width().round(), page.height().round()), (10.0, 5.0), "the selection's crop, not the art's bounds"); + } "png" => assert_eq!(png_size(&written.borrow().last().unwrap().1), (10, 5), "10×5 pt at 72 ppi"), "svg" => assert!(text.contains(r#"viewBox="0 0 10 5""#), "{text}"), "eps" => assert!(text.contains("%%BoundingBox: 0 0 10 5"), "{text}"), @@ -92,9 +69,7 @@ fn export_selection_continues_in_each_format_s_options() { } } } - assert_eq!(names(&written).len(), 4, "one file each"); - assert!(app.ui.eps_options.get(export_as::SELECTION_FIELD).is_none(), "EPS Options does not remember the mark"); - assert!(app.ui.svg_options.get(export_as::SELECTION_FIELD).is_none()); + assert_eq!(names(&written).len(), 5, "one file each"); } /// Text Export Options opens with Selection Only on, and OK writes the selected type alone. @@ -104,10 +79,10 @@ fn export_selection_to_text_writes_the_selected_type() { app.run("text.create", json!({"x": 10, "y": 10, "text": "Left out"})).unwrap(); app.run("text.create", json!({"x": 10, "y": 30, "text": "Selected"})).unwrap(); app.run("document.exportSelection", json!({})).unwrap(); - assert_eq!(kind(&app), Some("txtOptions")); - assert!(app.ui.dialog.as_ref().unwrap().bool("selectionOnly")); + assert_eq!(kind(&app).as_deref(), Some("txtOptions")); + assert_eq!(fields(&app)["selectionOnly"], json!(true)); frame(&mut app); - confirm(&mut app).unwrap(); + confirm(&mut app); assert_eq!(names(&written), ["/out/sel.txt"]); assert_eq!(last_text(&written), "Selected\n"); } @@ -119,12 +94,12 @@ fn export_selection_to_svg_keeps_the_remembered_use_artboards() { let (mut app, _) = app_saving(2, |_| "/out/sel.svg".into()); app.run("file.export.svg", json!({})).unwrap(); set(&mut app, "useArtboards", json!(true)); - confirm(&mut app).unwrap(); + confirm(&mut app); assert_eq!(app.ui.svg_options["useArtboards"], true); app.run("shape.rectangle", json!({"x": 40, "y": 30, "width": 10, "height": 5})).unwrap(); app.run("document.exportSelection", json!({})).unwrap(); - assert_eq!(kind(&app), Some("svgOptions")); - confirm(&mut app).unwrap(); + assert_eq!(kind(&app).as_deref(), Some("svgOptions")); + confirm(&mut app); assert_eq!(app.ui.svg_options["useArtboards"], true, "{}", app.ui.svg_options); } @@ -138,7 +113,7 @@ fn export_selection_without_a_dialog_and_to_plug_ins_writes_the_selection() { let all = paths_in(&written.borrow().last().unwrap().1); picking(&mut app, "/out/sel.vectorcraft"); app.run("document.exportSelection", json!({})).unwrap(); - assert!(app.ui.dialog.is_none(), "written at once"); + assert!(kind(&app).is_none(), "written at once"); assert_eq!(names(&written).last().map(String::as_str), Some("/out/sel.vectorcraft")); let selected = paths_in(&written.borrow().last().unwrap().1); assert!(selected >= 1 && selected < all, "{selected} of {all} paths"); @@ -151,11 +126,11 @@ fn export_selection_without_a_dialog_and_to_plug_ins_writes_the_selection() { picking(&mut app, &format!("/out/sel.{ext}")); app.run("document.exportSelection", json!({})).unwrap(); if params != "{}" { - assert_eq!(kind(&app), Some(plugin::EXPORT_KIND), "{id} asks for its parameters"); + assert!(kind(&app).is_some(), "{id} asks for its parameters"); frame(&mut app); - confirm(&mut app).unwrap(); + confirm(&mut app); } - assert!(app.ui.dialog.is_none(), "{id}"); + assert!(kind(&app).is_none(), "{id}"); assert_eq!(names(&written).last(), Some(&format!("/out/sel.{ext}"))); let given = paths_in(&written.borrow().last().unwrap().1); app.run("plugin.remove", json!({"id": id})).unwrap(); @@ -173,11 +148,12 @@ fn export_selection_after_the_question_before_losing_writes_the_selection() { st.imported_from = Some("/out/sel.png".into()); st.import_losses = vec!["hidden type".into()]; app.run("document.exportSelection", json!({})).unwrap(); - assert_eq!(kind(&app), Some("pngOptions")); + assert_eq!(kind(&app).as_deref(), Some("pngOptions")); frame(&mut app); - assert_eq!(confirm(&mut app).unwrap()["pending"], super::confirm::KIND); + confirm(&mut app); + assert!(kind(&app).is_some(), "the question is open"); assert!(written.borrow().is_empty(), "nothing is written before OK"); - confirm(&mut app).unwrap(); + confirm(&mut app); assert_eq!(names(&written), ["/out/sel.png"]); assert_eq!(png_size(&written.borrow()[0].1), (10, 5), "the selection's crop"); } @@ -204,29 +180,7 @@ fn rich_black_reaches_files_from_the_export_dialogs() { app.run("paint.setStroke", json!({"none": true})).unwrap(); app.run("paint.setFill", json!({"color": {"c": 0, "m": 0, "y": 0, "k": 1}})).unwrap(); app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 30})).unwrap(); - let px = |w: &Written| { - let w = w.borrow(); - craft_image_codecs::decode(&w.last().unwrap().1) - .map(|__cimg| { - let (__w, __h) = __cimg.dimensions(); - match (__cimg.layout(), __cimg.sample_type()) { - (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => { - image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) - } - (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => { - image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) - } - (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => { - image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap()) - } - _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()), - } - }) - .unwrap() - .to_rgba8() - .get_pixel(10, 10) - .0 - }; + let px = |w: &Written| rgba(&w.borrow().last().unwrap().1).get_pixel(10, 10).0; app.run("file.exportAs", json!({"path": "/out/all.png"})).unwrap(); let accurate = px(&written); assert!(accurate[0] > 10, "accurate: dark grey, {accurate:?}"); @@ -235,7 +189,7 @@ fn rich_black_reaches_files_from_the_export_dialogs() { assert_eq!(px(&written), [0, 0, 0, 255], "Export As"); app.run("document.exportSelection", json!({})).unwrap(); frame(&mut app); - confirm(&mut app).unwrap(); + confirm(&mut app); assert_eq!(names(&written).last().map(String::as_str), Some("/out/sel.png")); assert_eq!(px(&written), [0, 0, 0, 255], "Export Selection"); } @@ -253,5 +207,5 @@ fn nothing_selected_stops_before_the_save_panel() { })); let e = app.run("document.exportSelection", json!({})).unwrap_err(); assert!(e.contains("select something to export"), "{e}"); - assert!(!asked.get() && app.ui.dialog.is_none() && written.borrow().is_empty()); + assert!(!asked.get() && kind(&app).is_none() && written.borrow().is_empty()); } diff --git a/crates/ui-egui/src/dialogs/tests_metafile.rs b/crates/ui-egui/src/dialogs/tests_metafile.rs index 6147aa6c4a..6b2c1cb36f 100644 --- a/crates/ui-egui/src/dialogs/tests_metafile.rs +++ b/crates/ui-egui/src/dialogs/tests_metafile.rs @@ -3,8 +3,7 @@ use serde_json::json; -use super::tests_export::{app, frame, kind, names, set}; -use super::*; +use super::tests_export::{app, confirm, fields, frame, kind, names, set}; /// Does `b` carry the EMF header's signature, or start with the placeable WMF key? fn is_emf(b: &[u8]) -> bool { @@ -19,18 +18,19 @@ fn is_wmf(b: &[u8]) -> bool { fn export_as_lists_emf_and_wmf_and_writes_them() { let (mut app, written) = app(2); app.run("file.exportAs", json!({"format": "emf"})).unwrap(); - assert_eq!(kind(&app), Some("exportAs")); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("format"), "emf"); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); + assert_eq!(fields(&app)["format"], "emf"); frame(&mut app); - let r = confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none(), "no options dialog follows"); - assert_eq!(r["path"], "/out/Untitled-1.emf"); + confirm(&mut app); + assert!(kind(&app).is_none(), "no options dialog follows"); + assert_eq!(names(&written), ["/out/Untitled-1.emf"]); assert!(is_emf(&written.borrow()[0].1)); // WMF, one file per artboard. app.run("file.exportAs", json!({"format": "wmf"})).unwrap(); set(&mut app, "useArtboards", json!(true)); frame(&mut app); - confirm(&mut app).unwrap(); + confirm(&mut app); + assert!(kind(&app).is_none()); let n = names(&written); assert_eq!(&n[1..], ["/out/Untitled-1-Artboard-1.wmf", "/out/Untitled-1-Artboard-2.wmf"]); assert!(written.borrow()[1..].iter().all(|(_, b)| is_wmf(b))); diff --git a/crates/ui-egui/src/dialogs/text_export.rs b/crates/ui-egui/src/dialogs/text_export.rs index 12e7b5d425..27d990ae67 100644 --- a/crates/ui-egui/src/dialogs/text_export.rs +++ b/crates/ui-egui/src/dialogs/text_export.rs @@ -2,55 +2,56 @@ //! endings, selection only) for a picked `.txt` path. Fields are `document.export` params //! (`format`, `path`…). -use serde_json::{Value, json}; +use craft_ui::contract::Bind; +use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft_ui::runtime::env::Label; +use serde_json::Value; -use super::png_options::choice; -use super::{DialogSpec, form}; -use crate::state::Dialog; -use crate::theme::Tokens; +use super::export_host::{self, After, Export, Open, options}; +use super::form; use crate::{VectorcraftApp, io}; pub(crate) const KIND: &str = "txtOptions"; -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("Text Export Options").into(), body, confirm, ok: Some("Export"), min_width: 340.0, ..DialogSpec::FORM }; - const ENCODINGS: [&str; 2] = ["utf8", "utf16"]; const ENCODING_LABELS: [&str; 2] = ["UTF-8", "UTF-16 (Unicode)"]; const LINE_ENDINGS: [&str; 2] = ["lf", "crlf"]; const LINE_ENDING_LABELS: [&str; 2] = ["LF (macOS, Linux)", "CRLF (Windows)"]; -/// Open the options for exporting the document's text to `path`. -pub fn open(app: &mut VectorcraftApp, path: &str) { - // The platform's own line endings by default. - let eol = if cfg!(windows) { LINE_ENDINGS[1] } else { LINE_ENDINGS[0] }; - let fields = json!({"format": "txt", "path": path, "encoding": ENCODINGS[0], "lineEndings": eol, "selectionOnly": false}); - app.ui.dialog = Some(Dialog::new(KIND, fields)); +/// The rows. Selection Only is always disabled without a selection to limit the export to (`can_select`). +fn params(can_select: bool) -> Vec { + let mut selection_only = Param::new("selectionOnly", tl!("Selection Only"), ParamKind::bool(false)); + if !can_select { + // An empty list of values never matches, so the row stays disabled. + selection_only = selection_only.enabled_when_in("encoding", std::iter::empty::()); + } + vec![ + Param::new("encoding", tl!("Encoding:"), ParamKind::choice(options(&ENCODINGS, &ENCODING_LABELS), Some(ENCODINGS[0].into()))), + Param::new("lineEndings", tl!("Line Endings:"), ParamKind::choice(options(&LINE_ENDINGS, &LINE_ENDING_LABELS), None)), + selection_only, + ] } -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let t = Tokens::get(ui.ctx()); - let label = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(text).color(t.text_dim)); - egui::Grid::new("text-export").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| { - label(ui, tl!("Encoding:")); - choice(ui, d, "encoding", &ENCODINGS, &ENCODING_LABELS); - ui.end_row(); - label(ui, tl!("Line Endings:")); - choice(ui, d, "lineEndings", &LINE_ENDINGS, &LINE_ENDING_LABELS); - ui.end_row(); - }); - ui.add_space(8.0); +/// Open the options for exporting the document's text to `path`; `selection` when Export Selection opened them. +pub fn open(app: &mut VectorcraftApp, path: &str, selection: bool) -> Result<(), String> { + let ctx = app.ui_ctx.clone().ok_or("no window")?; // Export Selection keeps Selection Only on. - let selected = app.session.active().is_some_and(|st| !st.selection.objects.is_empty()) && !d.bool(super::export_as::SELECTION_FIELD); - ui.add_enabled_ui(selected, |ui| form::check(ui, d, "selectionOnly", tl!("Selection Only"))); - false + let can_select = !selection && app.session.active().is_some_and(|st| !st.selection.objects.is_empty()); + // The platform's own line endings by default. + let eol = if cfg!(windows) { LINE_ENDINGS[1] } else { LINE_ENDINGS[0] }; + let mut fields = DialogFields::from_pairs([("format", "txt"), ("path", path), ("encoding", ENCODINGS[0]), ("lineEndings", eol)]); + fields.set("selectionOnly", selection); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { + ParamDialog::new(KIND, tl!("Text Export Options"), params(can_select)).values(Bind::bound(fields)).ok_label(Label::from("Export")) + }); + export_host::open(app, Export::Text, selection, dialog).map(|_| ()).ok_or_else(|| "no window".into()) } /// Write the text file (the command runs first, so a bad option keeps the dialog open). Opened by /// Export Selection, it writes `document.exportSelection`'s text. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let mut params = form::params(d); - let id = if d.bool(super::export_as::SELECTION_FIELD) { +pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result { + let mut params = Value::Object(form::json_of(¶ms(true), fields)); + let id = if open.selection { if let Some(o) = params.as_object_mut() { o.remove("selectionOnly"); } @@ -58,7 +59,6 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } else { "document.export" }; - let path = io::save_command_output(app, id, "txt", params)?; - app.ui.dialog = None; - Ok(json!({ "path": path })) + io::save_command_output(app, id, "txt", params)?; + Ok(None) }