diff --git a/crates/ui-egui/src/dialogs/dxf_import.rs b/crates/ui-egui/src/dialogs/dxf_import.rs index 8567dd90dc..ede980f69d 100644 --- a/crates/ui-egui/src/dialogs/dxf_import.rs +++ b/crates/ui-egui/src/dialogs/dxf_import.rs @@ -3,37 +3,300 @@ //! drawing units: by default the drawing at 1:1 in its own unit), whether lineweights scale with //! it, whether it is centred, and whether its layers merge into one. //! -//! Fields: `mode` (`open` | `place`), `name`, `path?`, `layouts` (model space first), `units` and -//! `version` (what the drawing declares), and the `dxf` options of `document.open`: `layout`, -//! `fit`, `unit` (a unit name), `scale`, `scaleLineweights`, `center`, `mergeLayers`. `__place` -//! keeps the other `file.place` params. The file's bytes stay in -//! [`crate::state::UiState::dialog_file`]. OK opens or places the drawing and remembers the fit, -//! lineweight, centring and layer choices for the next one; errors keep the dialog open. +//! Fields: `mode` (`open` | `place`), `layouts` (model space first), `units` and `version` (what +//! the drawing declares), and the `dxf` options of `document.open`: `layout`, `fit`, `unit` (a +//! unit name), `scale`, `scaleLineweights`, `center`, `mergeLayers`. The file, its name and path +//! and the other `file.place` params stay with the dialog's OK, which opens or places the drawing +//! and remembers the fit, lineweight, centring and layer choices for the next one; errors keep +//! the dialog open. +use std::sync::Arc; + +use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; +use craft_ui::display::{Picture, PictureSize, Text}; +use craft_ui::form::{Field, FieldGroup}; +use craft_ui::layout_components::{Row, Stack}; +use craft_ui::list::ThumbSize; +use craft_ui::pickers::Select; +use craft_ui::primitives::textures::Revision; +use craft_ui::runtime::env::Label; +use craft_ui::runtime::overlay::CloseReason; +use craft_ui::text::NumberField; +use egui::{Color32, ColorImage, Ui}; use serde_json::{Value, json}; +use vectorcraft_doc::Unit; use vectorcraft_engine::cmd::fileio; -use super::DialogSpec; -use super::document_setup::{LABEL, check, choice}; -use super::import_pdf::{DialogFile, other_place_params, place_source, preview_texture, show_preview, with_file}; -use crate::state::Dialog; -use crate::{VectorcraftApp, io, widgets}; +use super::host::{HoldsOk, open_held}; +use super::import_pdf::{DialogFile, other_place_params, place_source, render_preview, with_file}; +use crate::{VectorcraftApp, io}; pub const KIND: &str = "dxfImport"; -pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |d| if d.str("mode") == "place" { tl!("Place DXF") } else { tl!("DXF Import Options") }.into(), - body, - confirm, - min_width: 560.0, - ..DialogSpec::FORM -}; - -/// The longest side of the layout preview (pt). -const PREVIEW: f32 = 170.0; /// The choices the next drawing starts from (the scale belongs to each drawing's units). const REMEMBERED: [&str; 4] = ["fit", "scaleLineweights", "center", "mergeLayers"]; +/// What DXF Import Options answers with. +#[derive(Clone, PartialEq)] +pub struct DxfChoices { + /// The layout to import: `Model` or a paper layout's name. + pub layout: String, + /// Scale to Fit Artboard. + pub fit: bool, + /// The unit of the art in `1 unit = scale drawing units`. + pub unit: Unit, + /// The drawing units one unit of the art stands for. + pub scale: f64, + /// Whether lineweights scale with the drawing. + pub scale_lineweights: bool, + /// Whether the art is centred. + pub center: bool, + /// Whether the layers merge into one. + pub merge_layers: bool, +} + +impl Default for DxfChoices { + fn default() -> Self { + DxfChoices { layout: "Model".into(), fit: false, unit: Unit::Millimeters, scale: 1.0, scale_lineweights: false, center: true, merge_layers: false } + } +} + +/// What the dialog's OK needs besides its choices. +struct Source { + /// The `file.place` params the drawing is placed with; `None` opens it. + place: Option, + name: String, + path: Option, + file: Arc, +} + +/// The DXF Import Options dialog: the layout preview and what the drawing declares on the left, the +/// choices on the right. OK files the choices for the app, which imports and answers; an error stays +/// under the choices until one changes. +pub struct DxfImportDialog { + id: DialogId, + placing: bool, + file: Arc, + layouts: Vec, + units: String, + version: String, + choices: DxfChoices, + opening: DxfChoices, + /// The picture of the layout the pump rendered last, with the layout's revision. + preview: Option<(Revision, Arc)>, + held: HeldAnswer, +} + +impl DxfImportDialog { + /// The dialog for `file`'s `info`, starting from `choices`. + fn new(placing: bool, file: Arc, info: &vectorcraft_cad::DxfInfo, choices: DxfChoices) -> Self { + let text = |v: Value| match v { + Value::String(s) => s, + other => other.to_string(), + }; + DxfImportDialog { + id: dialog_id(KIND), + placing, + file, + layouts: info.layouts.clone(), + units: text(json!(info.units)), + version: text(json!(info.version)), + opening: choices.clone(), + choices, + preview: None, + held: HeldAnswer::new(), + } + } + + /// The revision of the shown layout while its picture has not been handed over ([`set_preview`](Self::set_preview)). + pub fn wanted_preview(&self) -> Option { + let wanted = Revision::of(&self.choices.layout); + self.preview.as_ref().is_none_or(|(shown, _)| *shown != wanted).then_some(wanted) + } + + /// Hands over the picture of the layout whose revision is `key`. + pub fn set_preview(&mut self, key: Revision, image: Arc) { + self.preview = Some((key, image)); + } +} + +impl StackDialog for DxfImportDialog { + type Result = DxfChoices; + + fn id(&self) -> DialogId { + self.id + } + + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + // The app accepted the held OK: this pass closes the dialog with it. A measuring run closes nothing. + let finish = self.held.is_accepted() && !craft_ui::runtime::measure::active(ui.ctx()); + let refusal = self.held.refusal().map(|(reason, refused)| (reason.clone(), refused.clone())); + let title = if self.placing { tl!("Place DXF") } else { tl!("DXF Import Options") }; + let layouts: Vec> = self.layouts.iter().map(|l| Entry::new(l.clone(), l.clone())).collect(); + let units: Vec> = Unit::ALL.iter().filter(|u| **u != Unit::FeetInches).map(|u| Entry::new(*u, u.label())).collect(); + let (revision, image) = match &self.preview { + Some((revision, image)) => (*revision, Some(image.clone())), + None => (Revision::default(), None), + }; + let picture = || image.as_ref().map_or_else(|| ColorImage::filled([1, 1], Color32::TRANSPARENT), |i| ColorImage::clone(i)); + let declared = format!("DXF {} · {}", self.version, self.units); + let (token, scale_range) = (self.file.token, *vectorcraft_cad::SCALE_RANGE.start()..=*vectorcraft_cad::SCALE_RANGE.end()); + let shown = craft_ui::patterns::form_dialogs::FormDialog::new(title, Bind::bound(&mut self.choices)) + .opening(self.opening.clone()) + .accept_stays_open(true) + .ok_enabled(!self.held.is_waiting()) + .show(ui, |ui, form, c| { + Row::new().show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { + Picture::new(tl!("Preview"), token, &picture).revision(revision).extent(PictureSize::Thumb(ThumbSize::Large)).show(ui); + Text::new(declared.clone()).show(ui); + }); + Stack::new().show(ui, |ui, _| { + Field::new(tl!("Layout")).show(ui, |ui, _| { + if let Some(layout) = Select::new(tl!("Layout"), Bind::given(c.layout.clone()), &layouts).show(ui).value().cloned() { + c.layout = layout; + } + }); + FieldGroup::new(tl!("Scaling")).show(ui, |ui, _| { + if let Some(fit) = craft_ui::choice::Checkbox::new(Bind::given(c.fit)).label(tl!("Scale to Fit Artboard")).show(ui).value().copied() { + c.fit = fit; + } + Field::new(tl!("Scale")).show(ui, |ui, _| { + Row::new().show(ui, |ui, _| { + Text::new("1").show(ui); + if let Some(unit) = Select::new(tl!("Unit"), Bind::given(c.unit), &units).enabled(!c.fit).show(ui).value().copied() { + c.unit = unit; + } + Text::new("=").show(ui); + let scale = NumberField::new(tl!("Scale"), Bind::given(Some(c.scale))) + .range(scale_range.clone()) + .enabled(!c.fit) + .show(ui) + .edit + .value() + .copied() + .flatten(); + if let Some(scale) = scale { + c.scale = scale; + } + Text::new(tl!("Units")).show(ui); + }); + }); + if let Some(on) = craft_ui::choice::Checkbox::new(Bind::given(c.scale_lineweights)) + .label(tl!("Scale Lineweights")) + .show(ui) + .value() + .copied() + { + c.scale_lineweights = on; + } + }); + FieldGroup::new(tl!("Options")).show(ui, |ui, _| { + if let Some(on) = craft_ui::choice::Checkbox::new(Bind::given(c.center)).label(tl!("Center Artwork")).show(ui).value().copied() { + c.center = on; + } + if let Some(on) = + craft_ui::choice::Checkbox::new(Bind::given(c.merge_layers)).label(tl!("Merge Layers")).show(ui).value().copied() + { + c.merge_layers = on; + } + }); + }); + }); + if let Some((reason, _)) = refusal.as_ref().filter(|(_, refused)| refused == c) { + Text::new(reason.clone()).show(ui); + } + if finish { + form.request_close_as(CloseReason::Activated); + } + true + }); + if self.held.refusal().is_some_and(|(_, refused)| *refused != self.choices) { + self.held.clear_refusal(); + } + // The pass reports a press only in the pass that took the input, so a second pass of the frame files nothing. + if shown.picked == Some(0) && !self.held.is_waiting() { + self.held.file(self.choices.clone()); + } + if finish && shown.closed == Some(CloseReason::Activated) { + return Some(self.held.finish().map_or(DialogResult::Cancel, DialogResult::Ok)); + } + shown.closed.map(|_| DialogResult::Cancel) + } + + fn key(&self) -> Option<&str> { + Some(KIND) + } + + /// OK as the button: files the choices and answers none, and answers the held choices once the app + /// accepted them. + fn confirm(&mut self, _: &egui::Context) -> Option { + if self.held.is_accepted() { + return self.held.finish(); + } + if self.held.is_waiting() { + return None; + } + self.held.file(self.choices.clone()); + None + } + + fn held_state(&self) -> Option { + self.held.state() + } + + fn json_fields(&self) -> Option { + let c = &self.choices; + Some(json!({ + "mode": if self.placing { "place" } else { "open" }, + "layouts": self.layouts, + "layout": c.layout, + "units": self.units, + "version": self.version, + "fit": c.fit, + "unit": c.unit.label(), + "scale": c.scale, + "scaleLineweights": c.scale_lineweights, + "center": c.center, + "mergeLayers": c.merge_layers, + })) + } + + /// The layout is kept as typed: a layout the file lacks is refused when OK imports, with the + /// dialog still open. + fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: Value) -> Result<(), String> { + let rejected = || FieldRefusal::Rejects(&value).message(field); + let flag = || value.as_bool().ok_or_else(rejected); + let c = &mut self.choices; + match field { + "layout" => c.layout = value.as_str().ok_or_else(rejected)?.to_owned(), + "unit" => c.unit = value.as_str().and_then(Unit::named).ok_or_else(rejected)?, + "scale" => c.scale = value.as_f64().ok_or_else(rejected)?.clamp(*vectorcraft_cad::SCALE_RANGE.start(), *vectorcraft_cad::SCALE_RANGE.end()), + "fit" => c.fit = flag()?, + "scaleLineweights" => c.scale_lineweights = flag()?, + "center" => c.center = flag()?, + "mergeLayers" => c.merge_layers = flag()?, + _ => return Err(format!("unknown field `{field}`")), + } + ctx.request_repaint(); + Ok(()) + } +} + +// PLAN: assumed `HoldsOk { type Answer; fn take_ok(&mut self) -> Option; fn answer_ok(&mut self, Result<(), Label>) }` (wg.A17). +impl HoldsOk for DxfImportDialog { + type Answer = DxfChoices; + + fn take_ok(&mut self) -> Option { + self.held.take() + } + + fn answer_ok(&mut self, answer: Result<(), Label>) { + self.held.answer(answer); + } +} + /// Open `bytes` (or place them with the `file.place` params `place`) through the dialog when they /// are a DXF drawing; false when they aren't (or can't be read: the loader then says why). pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option, place: Option<&Value>) -> bool { @@ -41,36 +304,29 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option Value { Value::Object(REMEMBERED.iter().filter_map(|k| last?.get(*k).filter(|v| v.is_boolean()).map(|v| (k.to_string(), v.clone()))).collect()) } -/// The `dxf` options of `document.open` and `file.place` the fields set. -fn options(d: &Dialog) -> Value { - let fit = d.bool("fit"); +/// The `dxf` options of `document.open` and `file.place` the choices set. +fn options(c: &DxfChoices) -> Value { let mut o = json!({ - "layout": d.str("layout"), - "fit": fit, - "scaleLineweights": d.bool("scaleLineweights"), - "center": d.bool("center"), - "mergeLayers": d.bool("mergeLayers"), + "layout": c.layout, + "fit": c.fit, + "scaleLineweights": c.scale_lineweights, + "center": c.center, + "mergeLayers": c.merge_layers, }); - if !fit { - o["unit"] = json!(d.str("unit")); - o["scale"] = json!(d.f64("scale", 1.0)); + if !c.fit { + o["unit"] = json!(c.unit.label()); + o["scale"] = json!(c.scale); } o } -/// OK: open or place the drawing with the options. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let file = app.ui.dialog_file.clone().ok_or("the drawing is no longer loaded")?; - let dxf = options(d); +/// OK: open or place the drawing with the choices; an error keeps the dialog open. +fn confirm(app: &mut VectorcraftApp, source: &Source, choices: &DxfChoices) -> Result<(), String> { + let dxf = options(choices); app.ui.dxf_import = Value::Object(REMEMBERED.iter().map(|k| (k.to_string(), dxf[*k].clone())).collect()); - let r = if d.str("mode") == "place" { - let mut p = with_file(d.fields.get("__place"), d, &file); - p["dxf"] = dxf; - crate::place::run_for_user(app, &p).map(|_| ()) - } else { - let path = d.fields.get("path").and_then(Value::as_str).map(str::to_string); - io::open_document(app, &d.str("name"), &file.bytes, path, &json!({ "dxf": dxf })).map(|_| ()) - }; - match r { - Ok(()) => { - // Placing may have opened another dialog; only this one closes. - if app.ui.dialog.as_ref().is_some_and(|x| x.kind == KIND) { - app.ui.dialog = None; - } - Ok(Value::Null) - } - Err(e) => { - app.ui.dialog = Some(d.clone()); - Err(e) + match &source.place { + Some(place) => { + let mut p = with_file(place, source.path.as_deref(), &source.name, &source.file); + p["dxf"] = dxf; + crate::place::run_for_user(app, &p).map(|_| ()) } + None => io::open_document(app, &source.name, &source.file.bytes, source.path.clone(), &json!({ "dxf": dxf })).map(|_| ()), } } -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - ui.horizontal_top(|ui| { - ui.vertical(|ui| { - show_preview(ui, preview(app, ui.ctx(), d).as_ref(), PREVIEW); - ui.add_space(6.0); - widgets::dim_label(ui, &format!("DXF {} · {}", d.str("version"), d.str("units"))); - }); - ui.add_space(14.0); - ui.vertical(|ui| { - let layouts: Vec = - d.fields.get("layouts").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); - let rows: Vec<(&str, &str)> = layouts.iter().map(|l| (l.as_str(), l.as_str())).collect(); - choice(ui, d, "layout", tl!("Layout:"), &rows); - ui.add_space(10.0); - widgets::subheader(ui, tl!("Scaling")); - check(ui, d, "fit", tl!("Scale to Fit Artboard")); - ui.add_enabled_ui(!d.bool("fit"), |ui| super::dxf_options::scale_row(ui, d)); - ui.horizontal(|ui| { - ui.add_space(LABEL + 8.0); - check(ui, d, "scaleLineweights", tl!("Scale Lineweights")); - }); - ui.add_space(10.0); - widgets::subheader(ui, tl!("Options")); - check(ui, d, "center", tl!("Center Artwork")); - check(ui, d, "mergeLayers", tl!("Merge Layers")); - }); +/// Renders the picture of the layout the open dialog wants, once per layout. A layout that can't be +/// read gets an empty picture, so it isn't read again. +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + let Some(windows) = app.dialogs() else { return }; + let wanted = windows.with(|h| { + let dialog = h.get::()?; + Some((dialog.wanted_preview()?, dialog.file.clone(), dialog.choices.layout.clone())) + }); + let Some((key, file, layout)) = wanted else { return }; + let o = vectorcraft_cad::ImportOptions { layout: Some(layout), fit: true, ..Default::default() }; + // PLAN: assumed `render_preview(app, doc, key: Revision) -> Arc` (files-w17, decided with `Revision` as the key). + let image = match vectorcraft_cad::import(&file.bytes, &o) { + Ok(imported) => render_preview(app, imported.document, key), + Err(_) => Arc::new(ColorImage::filled([1, 1], Color32::TRANSPARENT)), + }; + windows.with(|h| { + if let Some(dialog) = h.get_mut::() { + dialog.set_preview(key, image); + } }); - false -} - -/// The chosen layout fitted to the preview, rendered once per drawing and layout. -fn preview(app: &mut VectorcraftApp, ctx: &egui::Context, d: &Dialog) -> Option { - let file = app.ui.dialog_file.clone()?; - let layout = d.str("layout"); - let key = egui::Id::unique(("dxf-preview", file.token, layout.as_str())); - let o = vectorcraft_cad::ImportOptions { layout: Some(layout.clone()), fit: true, ..Default::default() }; - // A layout that can't be read shows an empty preview (and isn't read again). - preview_texture(app, ctx, key, "dxf-preview", PREVIEW, || vectorcraft_cad::import(&file.bytes, &o).ok().map(|r| r.document)) } #[cfg(test)] mod tests { - use vectorcraft_engine::Session; use vectorcraft_engine::doc::NodeKind; + use super::super::text_import::test_support as host; use super::*; /// A millimetre drawing: a line in model space and a circle on a paper layout. @@ -221,43 +444,23 @@ mod tests { pairs.iter().map(|(c, v)| format!("{c:>3}\n{v}\n")).collect::().into_bytes() } - fn frame(app: &mut VectorcraftApp) -> String { - crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) - } - - fn set(app: &mut VectorcraftApp, k: &str, v: Value) { - app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); + fn set(app: &VectorcraftApp, k: &str, v: Value) { + host::set(app, KIND, k, v); } #[test] fn opening_a_drawing_asks_for_the_import_options() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = host::app(); io::open_bytes(&mut app, "plan.dxf", &drawing(), None).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.kind.as_str(), d.str("mode"), d.str("layout"), d.str("unit")), (KIND, "open".into(), "Model".into(), "Millimeters".into())); - assert_eq!(d.fields["layouts"], json!(["Model", "Layout1"])); - let text = frame(&mut app); - for label in [ - "DXF Import Options", - "Layout:", - "Scaling", - "Scale to Fit Artboard", - "Scale:", - "Scale Lineweights", - "Center Artwork", - "Merge Layers", - "Millimeters", - "OK", - ] { - assert!(text.contains(label), "{label} in {text}"); - } - // Fit greys out the ratio; a paper layout previews and opens. - set(&mut app, "fit", json!(true)); - set(&mut app, "layout", json!("Layout1")); - set(&mut app, "mergeLayers", json!(true)); - frame(&mut app); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + let f = host::fields(&app, KIND); + assert_eq!((&f["mode"], &f["layout"], &f["unit"]), (&json!("open"), &json!("Model"), &json!("Millimeters"))); + assert_eq!(f["layouts"], json!(["Model", "Layout1"])); + // A paper layout with its layers merged opens. + set(&app, "fit", json!(true)); + set(&app, "layout", json!("Layout1")); + set(&app, "mergeLayers", json!(true)); + host::confirm(&mut app, KIND).unwrap(); + assert!(!host::is_open(&app, KIND)); let st = app.session.doc().unwrap(); let mut circles = 0; st.doc.walk(|n| circles += usize::from(matches!(n.kind, NodeKind::Path { .. }))); @@ -265,40 +468,38 @@ mod tests { assert_eq!(st.doc.layers.len(), 1); // The next drawing starts from these choices, its own scale. io::open_bytes(&mut app, "plan.dxf", &drawing(), None).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert!(d.bool("fit") && d.bool("mergeLayers")); - assert_eq!(d.str("layout"), "Model"); + let f = host::fields(&app, KIND); + assert!(f["fit"] == true && f["mergeLayers"] == true); + assert_eq!(f["layout"], "Model"); } #[test] fn bad_options_keep_the_dialog_open() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = host::app(); io::open_bytes(&mut app, "plan.dxf", &drawing(), None).unwrap(); - set(&mut app, "layout", json!("Sheet 9")); - assert!(super::super::confirm(&mut app).is_err()); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); - set(&mut app, "layout", json!("Model")); - set(&mut app, "unit", json!("Points")); - set(&mut app, "scale", json!(1)); - super::super::confirm(&mut app).unwrap(); + set(&app, "layout", json!("Sheet 9")); + assert!(host::confirm(&mut app, KIND).is_err()); + assert!(host::is_open(&app, KIND)); + assert_eq!(host::fields(&app, KIND)["layout"], "Sheet 9", "the typed values stay"); + set(&app, "layout", json!("Model")); + set(&app, "unit", json!("Points")); + set(&app, "scale", json!(1)); + host::confirm(&mut app, KIND).unwrap(); let w = app.session.doc().unwrap().doc.artboards[0].rect.width(); assert_eq!(w, 100.0, "1 pt = 1 unit"); } #[test] fn placing_a_drawing_asks_then_places_one_group() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = host::app(); app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); let p = json!({"name": "plan.dxf", "dataBase64": vectorcraft_format::base64_encode(&drawing()), "template": false}); crate::place::run(&mut app, &p).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.kind.as_str(), d.str("mode")), (KIND, "place".into())); - assert_eq!(d.fields["__place"], json!({"template": false})); - assert!(frame(&mut app).contains("Place DXF")); - set(&mut app, "fit", json!(true)); + assert_eq!(host::fields(&app, KIND)["mode"], "place"); + set(&app, "fit", json!(true)); let undo = app.session.doc().unwrap().history.undo.len(); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + host::confirm(&mut app, KIND).unwrap(); + assert!(!host::is_open(&app, KIND)); let st = app.session.doc().unwrap(); assert_eq!(st.history.undo.len(), undo + 1); let id = st.selection.objects[0]; @@ -308,6 +509,6 @@ mod tests { let mut p = p.clone(); p["dxf"] = json!({}); crate::place::run(&mut app, &p).unwrap(); - assert!(app.ui.dialog.is_none()); + assert!(!host::is_open(&app, KIND)); } } diff --git a/crates/ui-egui/src/dialogs/psd_import.rs b/crates/ui-egui/src/dialogs/psd_import.rs index c5a4c905a0..e2270d2e80 100644 --- a/crates/ui-egui/src/dialogs/psd_import.rs +++ b/crates/ui-egui/src/dialogs/psd_import.rs @@ -7,34 +7,66 @@ //! the starting choices, Import Slices applying to both conversions and remembering the choices //! are VectorCraft's own. //! -//! Fields: `mode` (`open` | `place`), `name`, `path?`, `width`, `height` (the canvas, px), -//! `layers`, `hidden` and `slices` (counts, from `document.psdInfo`), `convert` (`objects` | -//! `flatten`), `hiddenLayers` and `importSlices`. `__place` keeps the other `file.place` params. -//! The file's bytes stay in [`crate::state::UiState::dialog_file`]. OK opens or places the file -//! with `layers`, `hiddenLayers` and (for a file with slices) `importSlices`, and remembers the -//! choices for the next file; errors keep the dialog open. +//! Fields: `convert` (`objects` | `flatten`), `hiddenLayers` and `importSlices`, and `hasSlices`, +//! which no row shows and which enables Import Slices. The file, its name and path and the other +//! `file.place` params stay with the dialog's OK, which opens or places the file with `layers`, +//! `hiddenLayers` and (for a file with slices) `importSlices`, and remembers the choices for the +//! next file; errors keep the dialog open. +//! +//! PLAN: no `pump`: `open_held`'s `ok` closure runs the import, so fl.A9's `psd_import::pump` +//! line has no work to call. +use std::sync::Arc; + +use craft_ui::contract::Bind; +use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio; -use super::DialogSpec; +use super::host::open_held; use super::import_pdf::{DialogFile, other_place_params, place_source, with_file}; -use crate::state::Dialog; -use crate::{VectorcraftApp, io, widgets}; +use crate::{VectorcraftApp, io}; pub const KIND: &str = "psdImport"; -pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |d| if d.str("mode") == "place" { tl!("Place PSD") } else { tl!("PSD Import Options") }.into(), - body, - confirm, - min_width: 380.0, - ..DialogSpec::FORM -}; - /// The fewest layers a file has for the dialog to ask. const MIN_LAYERS: usize = 2; +/// What the dialog's OK needs besides its values. +struct Source { + /// Whether the file is placed (the `file.place` params in `place`) rather than opened. + place: Option, + name: String, + path: Option, + file: Arc, + has_slices: bool, +} + +/// The rows of the dialog, over the `summary` line of the file's size and layer count. +fn params(summary: &str) -> Vec { + let option = |id: &str, label: &str| (id.to_string(), label.into()); + vec![ + Param::read_only_text("summary", "", summary.to_string()).full_width(), + Param::new( + "convert", + tl!("Layers"), + ParamKind::radio( + vec![option("objects", tl!("Convert Layers to Objects")), option("flatten", tl!("Flatten Layers to a Single Image"))], + Some("objects".into()), + ), + ), + Param::new("hiddenLayers", tl!("Import Hidden Layers"), ParamKind::bool(false)).enabled_when("convert", "objects"), + // Offered only for a file with slices, with either conversion. + Param::new("importSlices", tl!("Import Slices"), ParamKind::bool(true)).enabled_when("hasSlices", true), + ] +} + +/// The dialog over its values. +fn build<'b>(fields: &'b mut DialogFields, placing: bool, summary: &str) -> ParamDialog<'b> { + let title = if placing { tl!("Place PSD") } else { tl!("PSD Import Options") }; + ParamDialog::new(KIND, title, params(summary)).values(Bind::bound(fields)) +} + /// Open `bytes` (or place them with the `file.place` params `place`) through the dialog when they /// are a PSD or PSB file with [`MIN_LAYERS`] layers or more, or with slices; false when they aren't /// (the loader then opens or places the file, or says why it can't). @@ -43,28 +75,25 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option 0; + let mut fields = DialogFields::new(); + fields.set("convert", FieldValue::Text(if layers { "objects" } else { "flatten" }.into())); + fields.set("hiddenLayers", FieldValue::Bool(hidden)); + fields.set("importSlices", FieldValue::Bool(slices)); + fields.set("hasSlices", FieldValue::Bool(has_slices)); + let summary = format!("{} × {} px · {} {}", info.width, info.height, crate::i18n::colon(tl!("Layers")), info.layers); + let placing = place.is_some(); + let source = Source { + place: place.map(|p| other_place_params(p, &["layers", "hiddenLayers", "importSlices"])), + name: name.to_string(), + path, + file: DialogFile::new(bytes.to_vec()), + has_slices, + }; + let ctx = app.ui_ctx.clone().unwrap_or_default(); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| build(fields, placing, &summary)).held_ok(); + open_held(app, dialog, move |app, result| confirm(app, &source, result)).is_some() } /// `file.place` with params `p` asks first (true) when they embed a PSD or PSB file (`link: false`, @@ -118,86 +147,49 @@ pub fn last_options(app: &VectorcraftApp, p: &mut Value) { } } -/// OK: open or place the file with the choices. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let file = app.ui.dialog_file.clone().ok_or("the file is no longer loaded")?; - let layers = d.str("convert") != "flatten"; - let hidden = layers && d.bool("hiddenLayers"); +/// OK: open or place the file with the choices; an error keeps the dialog open. +fn confirm(app: &mut VectorcraftApp, source: &Source, result: &ParamResult) -> Result<(), String> { + let fields = &result.fields; + let layers = fields.text("convert") != Some("flatten"); + let import_hidden = fields.bool("hiddenLayers").unwrap_or(false); + let hidden = layers && import_hidden; // Import Slices is a choice only for a file with slices; otherwise the one made last stays. - let has_slices = d.fields.get("slices").and_then(Value::as_u64).unwrap_or(0) > 0; - let slices = if has_slices { d.bool("importSlices") } else { last_choices(app).2 }; - app.ui.psd_import = json!({ "layers": layers, "hiddenLayers": d.bool("hiddenLayers"), "importSlices": slices }); - let r = if d.str("mode") == "place" { - let mut p = with_file(d.fields.get("__place"), d, &file); - p["layers"] = json!(layers); - if layers || has_slices { - // Layers and slices are always embedded; a file from bytes may carry the Place dialog's - // Link. - p["link"] = json!(false); - } - if hidden { - p["hiddenLayers"] = json!(true); - } - if has_slices { - p["importSlices"] = json!(slices); - } - crate::place::run_for_user(app, &p).map(|_| ()) - } else { - let path = d.fields.get("path").and_then(Value::as_str).map(str::to_string); - let mut p = json!({ "layers": layers, "hiddenLayers": hidden }); - if has_slices { - p["importSlices"] = json!(slices); - } - io::open_document(app, &d.str("name"), &file.bytes, path, &p).map(|_| ()) - }; - match r { - Ok(()) => { - // Placing may have opened another dialog; only this one closes. - if app.ui.dialog.as_ref().is_some_and(|x| x.kind == KIND) { - app.ui.dialog = None; + let has_slices = source.has_slices; + let slices = if has_slices { fields.bool("importSlices").unwrap_or(true) } else { last_choices(app).2 }; + app.ui.psd_import = json!({ "layers": layers, "hiddenLayers": import_hidden, "importSlices": slices }); + match &source.place { + Some(place) => { + let mut p = with_file(place, source.path.as_deref(), &source.name, &source.file); + p["layers"] = json!(layers); + if layers || has_slices { + // Layers and slices are always embedded; a file from bytes may carry the Place dialog's + // Link. + p["link"] = json!(false); } - Ok(Value::Null) + if hidden { + p["hiddenLayers"] = json!(true); + } + if has_slices { + p["importSlices"] = json!(slices); + } + crate::place::run_for_user(app, &p).map(|_| ()) } - Err(e) => { - app.ui.dialog = Some(d.clone()); - Err(e) + None => { + let mut p = json!({ "layers": layers, "hiddenLayers": hidden }); + if has_slices { + p["importSlices"] = json!(slices); + } + io::open_document(app, &source.name, &source.file.bytes, source.path.clone(), &p).map(|_| ()) } } } -fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).unwrap_or(0); - widgets::dim_label(ui, &format!("{} × {} px · {} {}", count("width"), count("height"), crate::i18n::colon(tl!("Layers")), count("layers"))); - // Offered only for a file with slices, with either conversion. - let sliced = count("slices") > 0; - ui.add_space(8.0); - let convert = d.str("convert") != "flatten"; - if widgets::radio(ui, tl!("Convert Layers to Objects"), convert, true) { - d.fields.insert("convert".into(), json!("objects")); - } - ui.horizontal(|ui| { - ui.add_space(22.0); - let on = d.bool("hiddenLayers"); - if widgets::check(ui, tl!("Import Hidden Layers"), on && convert, convert) { - d.fields.insert("hiddenLayers".into(), json!(!on)); - } - }); - if widgets::radio(ui, tl!("Flatten Layers to a Single Image"), !convert, true) { - d.fields.insert("convert".into(), json!("flatten")); - } - ui.add_space(8.0); - let on = d.bool("importSlices"); - if widgets::check(ui, tl!("Import Slices"), on && sliced, sliced) { - d.fields.insert("importSlices".into(), json!(!on)); - } - false -} - #[cfg(test)] mod tests { use vectorcraft_engine::Session; use vectorcraft_engine::doc::NodeKind; + use super::super::text_import::test_support as host; use super::*; /// A PSD file of three layers, the middle one hidden, written by `document.export`. @@ -219,64 +211,47 @@ mod tests { vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap() } - fn app() -> VectorcraftApp { - VectorcraftApp::new(Session::new(), Default::default()) - } - - fn frame(app: &mut VectorcraftApp) -> String { - crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) - } - - fn set(app: &mut VectorcraftApp, k: &str, v: Value) { - app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); + fn set(app: &VectorcraftApp, k: &str, v: Value) { + host::set(app, KIND, k, v); } fn layer_names(app: &VectorcraftApp) -> Vec<(String, bool)> { app.session.doc().unwrap().doc.layers.iter().map(|l| (l.name.clone().unwrap_or_default(), l.visible)).collect() } + /// The options of a Place dialog that places without Link or with it. + // PLAN: assumed `PlaceOptions { link, template, show_import_options }` and `place::confirm(app, Vec, PlaceOptions)` (files-w14). + fn place_options(link: bool, show_import_options: bool) -> crate::place::PlaceOptions { + crate::place::PlaceOptions { link, template: false, show_import_options } + } + #[test] fn opening_a_layered_file_asks_for_the_import_options() { let psd = layered(); - let mut app = app(); + let mut app = host::app(); io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.kind.as_str(), d.str("mode"), d.str("convert"), d.bool("hiddenLayers")), (KIND, "open".into(), "objects".into(), false)); - assert_eq!((&d.fields["layers"], &d.fields["hidden"], &d.fields["width"]), (&json!(3), &json!(1), &json!(20))); + let f = host::fields(&app, KIND); + assert_eq!((&f["convert"], &f["hiddenLayers"], &f["hasSlices"]), (&json!("objects"), &json!(false), &json!(false))); assert!(app.session.active().is_none(), "nothing opens before OK"); - let text = frame(&mut app); - for label in [ - "PSD Import Options", - "20 × 20 px", - "Layers: 3", - "Convert Layers to Objects", - "Import Hidden Layers", - "Flatten Layers to a Single Image", - "OK", - ] { - assert!(text.contains(label), "{label} in {text}"); - } // Layers as objects, hidden ones left out. - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + host::confirm(&mut app, KIND).unwrap(); + assert!(!host::is_open(&app, KIND)); assert_eq!(layer_names(&app), [("Back".to_string(), true), ("Front".to_string(), true)]); // With Import Hidden Layers the hidden layer comes in hidden. io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap(); - set(&mut app, "hiddenLayers", json!(true)); - frame(&mut app); - super::super::confirm(&mut app).unwrap(); + set(&app, "hiddenLayers", json!(true)); + host::confirm(&mut app, KIND).unwrap(); assert_eq!(layer_names(&app), [("Back".to_string(), true), ("Middle".to_string(), false), ("Front".to_string(), true)]); // Flatten opens one image, and the next file starts from the choices made last. io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap(); - assert!(app.ui.dialog.as_ref().unwrap().bool("hiddenLayers"), "remembered"); - set(&mut app, "convert", json!("flatten")); - frame(&mut app); - super::super::confirm(&mut app).unwrap(); + assert_eq!(host::fields(&app, KIND)["hiddenLayers"], true, "remembered"); + set(&app, "convert", json!("flatten")); + host::confirm(&mut app, KIND).unwrap(); let st = app.session.doc().unwrap(); assert_eq!(st.doc.layers.len(), 1); assert!(matches!(st.doc.layers[0].children().map(Vec::as_slice), Some([one]) if matches!(one.kind, NodeKind::Image(_)))); io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().str("convert"), "flatten"); + assert_eq!(host::fields(&app, KIND)["convert"], "flatten"); } #[test] @@ -288,9 +263,9 @@ mod tests { let flat = s.execute("document.export", &json!({"format": "psd", "layers": false})).unwrap(); for r in [one, flat] { let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); - let mut app = app(); + let mut app = host::app(); io::open_bytes(&mut app, "one.psd", &bytes, None).unwrap(); - assert!(app.ui.dialog.is_none()); + assert!(!host::is_open(&app, KIND)); assert!(app.session.active().is_some()); } } @@ -298,15 +273,13 @@ mod tests { #[test] fn placing_without_link_asks_and_places_the_layers_as_a_group() { let b64 = vectorcraft_format::base64_encode(&layered()); - let mut app = app(); + let mut app = host::app(); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let r = crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64, "at": [50, 50]})).unwrap(); assert_eq!(r["dialog"], KIND); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.str("mode"), &d.fields["__place"]), ("place".into(), &json!({"at": [50, 50]}))); - assert!(frame(&mut app).contains("Place PSD")); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + assert!(host::is_open(&app, KIND)); + host::confirm(&mut app, KIND).unwrap(); + assert!(!host::is_open(&app, KIND)); let st = app.session.doc().unwrap(); let [id] = st.selection.objects[..] else { panic!("one object is selected") }; let g = st.doc.node(id).unwrap(); @@ -315,8 +288,8 @@ mod tests { assert_eq!(names, ["Back", "Front"]); // Flatten places the merged image. crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64})).unwrap(); - set(&mut app, "convert", json!("flatten")); - super::super::confirm(&mut app).unwrap(); + set(&app, "convert", json!("flatten")); + host::confirm(&mut app, KIND).unwrap(); let st = app.session.doc().unwrap(); let [id] = st.selection.objects[..] else { panic!("one object is selected") }; assert!(matches!(st.doc.node(id).unwrap().kind, NodeKind::Image(_))); @@ -329,7 +302,7 @@ mod tests { fn a_dropped_files_ok_places_in_the_document_it_was_dropped_on() { use crate::place::{DropAt, DropTarget}; let psd = layered(); - let mut app = app(); + let mut app = host::app(); for _ in 0..2 { app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); } @@ -338,30 +311,29 @@ mod tests { let st = app.session.doc().unwrap(); let target = DropTarget::Place(DropAt { doc: st.uid, reverts: st.reverts, at: vectorcraft_geom::Point::new(50.0, 50.0), embed: true }); crate::place::drop_files(app, vec![(target, ("poster.psd".into(), None, psd.clone()))]); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + assert!(host::is_open(app, KIND)); // Another document becomes active while the dialog is open. app.session.set_active(1); }; let objects = |app: &VectorcraftApp, i: usize| app.session.documents()[i].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::(); drop_on_first(&mut app); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + host::confirm(&mut app, KIND).unwrap(); + assert!(!host::is_open(&app, KIND)); assert_eq!((objects(&app, 0), objects(&app, 1)), (1, 0), "placed in the document it was dropped on"); assert_eq!(app.session.active_index(), Some(0), "which is active again"); // Reverted meanwhile: the dialog stays open with the reason, and nothing is placed. drop_on_first(&mut app); let first = app.session.documents()[0].uid; app.session.document_mut(first).unwrap().reverts += 1; - let e = super::super::confirm(&mut app).unwrap_err(); - assert!(e.contains("was reverted"), "{e}"); + assert!(host::confirm(&mut app, KIND).is_err()); + assert!(host::is_open(&app, KIND)); assert_eq!((objects(&app, 0), objects(&app, 1)), (1, 0)); // Closed meanwhile. - app.ui.dialog = None; + host::cancel(&app, KIND); drop_on_first(&mut app); app.session.close_document(0); - let e = super::super::confirm(&mut app).unwrap_err(); - assert!(e.contains("was closed"), "{e}"); + assert!(host::confirm(&mut app, KIND).is_err()); assert_eq!(objects(&app, 0), 0); } @@ -380,9 +352,8 @@ mod tests { // Place both through the Place dialog, then click the cursor once for each: what was placed. let place_two = |app: &mut VectorcraftApp, link: bool| -> Vec { let files: Vec = paths.iter().map(|p| json!({ "path": p })).collect(); - let d = Dialog::new(crate::dialogs::place::KIND, json!({"files": files, "link": link, "template": false})); - crate::place::confirm(app, &d).unwrap(); - assert!(app.ui.dialog.is_none(), "the cursor loads without asking"); + crate::place::confirm(app, files, place_options(link, false)).unwrap(); + assert!(!host::is_open(app, KIND), "the cursor loads without asking"); let view = vectorcraft_engine::ViewInfo::default(); (0..2) .map(|_| { @@ -400,7 +371,7 @@ mod tests { .collect() }; let visible = |n: &vectorcraft_engine::doc::Node| -> Vec { n.children().unwrap().iter().map(|c| c.visible).collect() }; - let mut app = app(); + let mut app = host::app(); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); // At first, Convert Layers to Objects without hidden layers. for n in place_two(&mut app, false) { @@ -473,39 +444,39 @@ mod tests { let r = s.execute("document.export", &json!({"format": "psd"})).unwrap(); // One layer: without slices it opens at once, with them it asks. let psd = sliced(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); - let mut app = app(); + let mut app = host::app(); io::open_bytes(&mut app, "one.psd", &psd, None).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.kind.as_str(), &d.fields["slices"], d.bool("importSlices")), (KIND, &json!(1), true)); - assert!(frame(&mut app).contains("Import Slices")); - // Flatten keeps Import Slices: the merged image opens with the slice. - set(&mut app, "convert", json!("flatten")); - super::super::confirm(&mut app).unwrap(); + let f = host::fields(&app, KIND); + assert_eq!((&f["hasSlices"], &f["importSlices"]), (&json!(true), &json!(true))); + // Flatten keeps Import Slices: the choice is offered, and the merged image opens with the slice. + set(&app, "convert", json!("flatten")); + set(&app, "importSlices", json!(true)); + host::confirm(&mut app, KIND).unwrap(); assert_eq!(slice_names(&app), ["cell"]); // Left off, the slice stays out, and the next file starts from that choice. io::open_bytes(&mut app, "one.psd", &psd, None).unwrap(); - set(&mut app, "importSlices", json!(false)); - super::super::confirm(&mut app).unwrap(); + set(&app, "importSlices", json!(false)); + host::confirm(&mut app, KIND).unwrap(); assert!(slice_names(&app).is_empty()); io::open_bytes(&mut app, "one.psd", &psd, None).unwrap(); - assert!(!app.ui.dialog.as_ref().unwrap().bool("importSlices"), "remembered"); - // A layered file without slices keeps the choice made last for the next sliced one. - app.ui.dialog = None; + assert_eq!(host::fields(&app, KIND)["importSlices"], false, "remembered"); + // A layered file without slices takes no Import Slices choice and keeps the one made last. + host::cancel(&app, KIND); io::open_bytes(&mut app, "poster.psd", &layered(), None).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["slices"], json!(0)); - set(&mut app, "importSlices", json!(true)); - super::super::confirm(&mut app).unwrap(); + assert_eq!(host::fields(&app, KIND)["hasSlices"], false); + assert!(host::try_set(&app, KIND, "importSlices", json!(true)).is_err(), "the row takes no input"); + host::confirm(&mut app, KIND).unwrap(); assert_eq!(app.ui.psd_import["importSlices"], json!(false)); } #[test] fn placing_a_sliced_file_without_link_brings_its_slices_with_the_art() { let b64 = vectorcraft_format::base64_encode(&sliced(&layered())); - let mut app = app(); + let mut app = host::app(); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64, "at": [50, 50]})).unwrap(); - assert!(app.ui.dialog.as_ref().unwrap().bool("importSlices")); - super::super::confirm(&mut app).unwrap(); + assert_eq!(host::fields(&app, KIND)["importSlices"], true); + host::confirm(&mut app, KIND).unwrap(); let st = app.session.doc().unwrap(); assert_eq!(st.doc.slices.len(), 1); assert_eq!(st.doc.slices[0].rect, vectorcraft_geom::Rect::new(40.0, 40.0, 50.0, 50.0)); @@ -519,7 +490,7 @@ mod tests { #[test] fn placing_with_show_import_options_off_takes_the_last_choices() { let b64 = vectorcraft_format::base64_encode(&sliced(&layered())); - let mut app = app(); + let mut app = host::app(); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); // The file's bytes carry the Place dialog's Link, which they have no file for. let place = |app: &mut VectorcraftApp, slices: Option| { @@ -528,7 +499,7 @@ mod tests { p["importSlices"] = json!(s); } crate::place::run_for_user(app, &p).unwrap(); - assert!(app.ui.dialog.is_none(), "placed without asking"); + assert!(!host::is_open(app, KIND), "placed without asking"); let st = app.session.doc().unwrap(); let [id] = st.selection.objects[..] else { panic!("one object is selected") }; (st.doc.node(id).unwrap().kind.clone(), st.doc.slices.len()) @@ -553,15 +524,14 @@ mod tests { #[test] fn files_from_bytes_placed_with_link_take_the_last_choices() { let files: Vec = ["a.psd", "b.psd"].iter().map(|n| json!({ "name": n })).collect(); - let mut app = app(); + let mut app = host::app(); for n in ["a.psd", "b.psd"] { app.place.picked.push((n.to_string(), sliced(&layered()))); } app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); // The dialog's Link is on, but files from bytes have no file to link to. - let d = Dialog::new(crate::dialogs::place::KIND, json!({"files": files, "link": true, "template": false, "showImportOptions": false})); - crate::place::confirm(&mut app, &d).unwrap(); - assert!(app.ui.dialog.is_none(), "the cursor loads without asking"); + crate::place::confirm(&mut app, files, place_options(true, false)).unwrap(); + assert!(!host::is_open(&app, KIND), "the cursor loads without asking"); let view = vectorcraft_engine::ViewInfo::default(); for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] { for r in app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, 10.0, 10.0), view).unwrap() { @@ -591,13 +561,12 @@ mod tests { .collect(); let files: Vec = paths.iter().map(|p| json!({ "path": p })).collect(); let services = crate::Services { read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), ..Default::default() }; - let mut app = VectorcraftApp::new(Session::new(), services); + let mut app = host::with_window(VectorcraftApp::new(Session::new(), services)); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); // The choices made last would place the layers without asking with Show Import Options off. app.ui.psd_import = json!({"layers": true, "importSlices": true}); - let d = Dialog::new(crate::dialogs::place::KIND, json!({"files": files, "link": false, "template": false, "showImportOptions": true})); - crate::place::confirm(&mut app, &d).unwrap(); - assert!(app.ui.dialog.is_none(), "the cursor loads without asking"); + crate::place::confirm(&mut app, files, place_options(false, true)).unwrap(); + assert!(!host::is_open(&app, KIND), "the cursor loads without asking"); assert_eq!(app.session.tool_options()["count"], 2); // A click on the canvas: the file the cursor's request names asks. let view = vectorcraft_engine::ViewInfo::default(); @@ -608,21 +577,21 @@ mod tests { } } } - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the clicked file asks"); + assert!(host::is_open(&app, KIND), "the clicked file asks"); std::fs::remove_dir_all(&dir).ok(); } #[test] fn scripted_places_and_places_that_give_layers_dont_ask() { let b64 = vectorcraft_format::base64_encode(&layered()); - let mut app = app(); + let mut app = host::app(); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); // `file.place` run as a command places at once, as before. let r = crate::place::run(&mut app, &json!({"name": "poster.psd", "dataBase64": b64})).unwrap(); - assert!(app.ui.dialog.is_none()); + assert!(!host::is_open(&app, KIND)); assert_eq!(r["format"], "psd"); // The user's place with `layers` given doesn't ask either. crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64, "layers": false})).unwrap(); - assert!(app.ui.dialog.is_none()); + assert!(!host::is_open(&app, KIND)); } } diff --git a/crates/ui-egui/src/dialogs/text_import.rs b/crates/ui-egui/src/dialogs/text_import.rs index f0fe62b40d..b2f336df4f 100644 --- a/crates/ui-egui/src/dialogs/text_import.rs +++ b/crates/ui-egui/src/dialogs/text_import.rs @@ -4,24 +4,24 @@ //! starts from them, and is placed with them when Show Import Options is off. //! //! Fields: `platform` (`windows` | `mac`), `characterSet` (one of [`CHARACTER_SETS`]), -//! `removeLineReturns`, `removeParagraphReturns`, `replaceSpaces` (on or off), `spaces` (how many -//! spaces make a tab, 2–100), and `__params` (the `file.place` params naming the file). +//! `removeLineReturns`, `removeParagraphReturns`, `replaceSpaces` (on or off) and `spaces` (how +//! many spaces make a tab, 2–100). The `file.place` params naming the file stay with the dialog's +//! OK, which places the file and keeps the dialog open with the error when that fails. +//! +//! PLAN: no `pump`: `open_held`'s `ok` closure runs the import, so fl.A9's `text_import::pump` +//! line has no work to call. +use craft_ui::contract::Bind; +use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft_ui::runtime::env::Label; use serde_json::{Value, json}; -use super::{DialogSpec, form}; -use crate::state::Dialog; -use crate::{VectorcraftApp, widgets}; +use super::host::open_held; +use crate::VectorcraftApp; /// The dialog kind of Text Import Options. pub const KIND: &str = "textImport"; -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("Text Import Options").into(), body, confirm, min_width: 340.0, ..DialogSpec::FORM }; - -/// The label column of the Encoding rows. -const LABEL: f32 = 104.0; - /// The Character Set choices: `file.place`'s `text.characterSet` value and the menu label. const CHARACTER_SETS: [(&str, &str); 11] = [ ("unicode", "Unicode"), @@ -37,41 +37,67 @@ const CHARACTER_SETS: [(&str, &str); 11] = [ ("centralEuropean", "Central European"), ]; +/// The platforms a file can come from: `file.place`'s `text.platform` value and the menu label. +const PLATFORMS: [(&str, &str); 2] = [("windows", "Windows"), ("mac", "Mac")]; + +/// The fewest and most spaces that make a tab. +const SPACES: std::ops::RangeInclusive = 2..=100; + /// Is the file `p` names (`path` or `name`) a text file? pub fn is_text(p: &Value) -> bool { let name = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).unwrap_or_default(); vectorcraft_engine::cmd::fileio::TEXT_EXTS.contains(&vectorcraft_engine::cmd::fileio::extension(name).as_str()) } +/// The rows of the dialog. +fn params() -> Vec { + let choices = |pairs: &[(&str, &str)]| -> Vec<(String, Label)> { pairs.iter().map(|(id, label)| ((*id).to_string(), (*label).into())).collect() }; + vec![ + Param::section(tl!("Encoding")), + Param::new("platform", tl!("Platform"), ParamKind::choice(choices(&PLATFORMS), None)), + Param::new("characterSet", tl!("Character Set"), ParamKind::choice(choices(&CHARACTER_SETS), None)), + Param::section(tl!("Line Breaks")), + Param::new("removeLineReturns", tl!("Join the lines of each paragraph"), ParamKind::bool(false)), + Param::new("removeParagraphReturns", tl!("Remove blank lines between paragraphs"), ParamKind::bool(false)), + Param::section(tl!("Spaces")), + Param::new("replaceSpaces", tl!("Replace"), ParamKind::bool(false)), + Param::new("spaces", tl!("or more spaces with a tab"), ParamKind::int(Some(*SPACES.start()), Some(*SPACES.end()), 3)) + .enabled_when("replaceSpaces", true), + ] +} + +/// The dialog over its values. +fn build(fields: &mut DialogFields) -> ParamDialog<'_> { + ParamDialog::new(KIND, tl!("Text Import Options"), params()).values(Bind::bound(fields)) +} + +/// The values the dialog opens with: the options confirmed last where they are ones the dialog offers +/// (a remembered value from another version falls back to the default). +fn starting_fields(app: &VectorcraftApp) -> DialogFields { + let last = &app.ui.text_import; + let text = |key: &str, offered: &[(&str, &str)], default: &str| { + last.get(key).and_then(Value::as_str).filter(|v| offered.iter().any(|(id, _)| id == v)).unwrap_or(default).to_string() + }; + let flag = |key: &str| last.get(key).and_then(Value::as_bool).unwrap_or(false); + let spaces = last.get("replaceSpaces").and_then(Value::as_i64).filter(|n| SPACES.contains(n)); + let mut fields = DialogFields::new(); + let platform = if cfg!(target_os = "macos") { "mac" } else { "windows" }; + fields.set("platform", FieldValue::Text(text("platform", &PLATFORMS, platform))); + fields.set("characterSet", FieldValue::Text(text("characterSet", &CHARACTER_SETS, "unicode"))); + fields.set("removeLineReturns", FieldValue::Bool(flag("removeLineReturns"))); + fields.set("removeParagraphReturns", FieldValue::Bool(flag("removeParagraphReturns"))); + fields.set("replaceSpaces", FieldValue::Bool(spaces.is_some())); + fields.set("spaces", FieldValue::Int(spaces.unwrap_or(3))); + fields +} + /// Ask how to place the text file `params` (`file.place` params) names, starting from the options /// confirmed last. pub fn open(app: &mut VectorcraftApp, params: &Value) -> Value { - let mut fields = json!({ - "platform": if cfg!(target_os = "macos") { "mac" } else { "windows" }, - "characterSet": "unicode", - "removeLineReturns": false, - "removeParagraphReturns": false, - "replaceSpaces": false, - "spaces": 3, - "__params": params, - }); - let last = &app.ui.text_import; - let sets = CHARACTER_SETS.map(|(value, _)| value); - for (k, wanted) in [("platform", &["windows", "mac"][..]), ("characterSet", &sets[..])] { - if let Some(v) = last.get(k).and_then(Value::as_str).filter(|v| wanted.contains(v)) { - fields[k] = json!(v); - } - } - for k in ["removeLineReturns", "removeParagraphReturns"] { - if let Some(v) = last.get(k).and_then(Value::as_bool) { - fields[k] = json!(v); - } - } - if let Some(n) = last.get("replaceSpaces").and_then(Value::as_u64).filter(|n| (2..=100).contains(n)) { - fields["replaceSpaces"] = json!(true); - fields["spaces"] = json!(n); - } - app.ui.dialog = Some(Dialog::new(KIND, fields)); + let ctx = app.ui_ctx.clone().unwrap_or_default(); + let dialog = HostedParamDialog::new(&ctx, KIND, starting_fields(app), build).held_ok(); + let params = params.clone(); + open_held(app, dialog, move |app, result| confirm(app, ¶ms, result)); json!({ "dialog": KIND }) } @@ -81,105 +107,146 @@ pub fn last_options(app: &VectorcraftApp) -> Value { if app.ui.text_import.is_object() { app.ui.text_import.clone() } else { json!({}) } } -fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - widgets::subheader(ui, tl!("Encoding")); - form::choice(ui, d, "platform", tl!("Platform:"), (LABEL, 180.0), &[("windows", "Windows"), ("mac", "Mac")]); - form::choice(ui, d, "characterSet", tl!("Character Set:"), (LABEL, 180.0), &CHARACTER_SETS); - ui.add_space(10.0); - widgets::subheader(ui, tl!("Line Breaks")); - for (key, label) in - [("removeLineReturns", tl!("Join the lines of each paragraph")), ("removeParagraphReturns", tl!("Remove blank lines between paragraphs"))] - { - let on = d.bool(key); - if widgets::check(ui, label, on, true) { - d.fields.insert(key.into(), json!(!on)); - } - } - ui.add_space(10.0); - widgets::subheader(ui, tl!("Spaces")); - let on = d.bool("replaceSpaces"); - ui.horizontal(|ui| { - if widgets::check(ui, tl!("Replace"), on, true) { - d.fields.insert("replaceSpaces".into(), json!(!on)); - } - ui.add_enabled_ui(on, |ui| { - if let Some(n) = widgets::plain_field(ui, "text-import-spaces", d.f64("spaces", 3.0), "", 0, 44.0) { - d.fields.insert("spaces".into(), json!(n.round().clamp(2.0, 100.0))); - } - widgets::dim_label(ui, tl!("or more spaces with a tab")); - }); - }); - false -} - -/// `file.place`'s `text` options from the fields. -fn options(d: &Dialog) -> Value { +/// `file.place`'s `text` options from the answered values. +fn options(fields: &DialogFields) -> Value { let mut o = json!({ - "platform": d.str("platform"), - "characterSet": d.str("characterSet"), - "removeLineReturns": d.bool("removeLineReturns"), - "removeParagraphReturns": d.bool("removeParagraphReturns"), + "platform": fields.text("platform").unwrap_or("windows"), + "characterSet": fields.text("characterSet").unwrap_or("unicode"), + "removeLineReturns": fields.bool("removeLineReturns").unwrap_or(false), + "removeParagraphReturns": fields.bool("removeParagraphReturns").unwrap_or(false), }); - if d.bool("replaceSpaces") { - o["replaceSpaces"] = json!(d.f64("spaces", 3.0).round().clamp(2.0, 100.0) as u64); + if fields.bool("replaceSpaces").unwrap_or(false) { + o["replaceSpaces"] = json!(fields.int("spaces").unwrap_or(3).clamp(*SPACES.start(), *SPACES.end())); } o } -/// Places the file with the options and remembers them for the next text file; closes first, so an -/// error shows in the status bar. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let mut params = d.fields.get("__params").cloned().unwrap_or_else(|| json!({})); - params["text"] = options(d); +/// Places the file `params` name with the options and remembers them for the next text file; an +/// error keeps the dialog open. +fn confirm(app: &mut VectorcraftApp, params: &Value, result: &ParamResult) -> Result<(), String> { + let mut params = params.clone(); + params["text"] = options(&result.fields); app.ui.text_import = params["text"].clone(); - app.ui.dialog = None; - crate::place::run_for_user(app, ¶ms) + crate::place::run_for_user(app, ¶ms).map(|_| ()) +} + +/// What the three import dialogs' tests share: a window for the host, and the open dialog's fields, +/// field sets and held OK by dialog key. +// PLAN: the shared home of these helpers is `dialogs/host.rs` (hub-w2); they live here until it has one. +#[cfg(test)] +pub(super) mod test_support { + use craft_ui::dialog::{HeldOk, OpenDialog}; + use serde_json::Value; + use vectorcraft_engine::Session; + + use crate::VectorcraftApp; + + /// `app` with a window to host dialogs in. + pub fn with_window(mut app: VectorcraftApp) -> VectorcraftApp { + app.ui_ctx = Some(egui::Context::default()); + app + } + + /// An empty app with a window. + pub fn app() -> VectorcraftApp { + with_window(VectorcraftApp::new(Session::new(), Default::default())) + } + + fn ctx(app: &VectorcraftApp) -> egui::Context { + app.ui_ctx.clone().expect("the test app has a window") + } + + /// The open dialog `key` names. + pub fn open_dialog(app: &VectorcraftApp, key: &str) -> Option { + app.dialogs()?.with(|h| h.open_dialogs().into_iter().find(|d| d.key.as_deref() == Some(key))) + } + + /// Whether a dialog `key` names is open. + pub fn is_open(app: &VectorcraftApp, key: &str) -> bool { + open_dialog(app, key).is_some() + } + + /// The fields of the open dialog `key` names, as automation lists them. + pub fn fields(app: &VectorcraftApp, key: &str) -> Value { + open_dialog(app, key).and_then(|d| d.fields).expect("the dialog is open and lists its fields") + } + + /// Sets `field` of the open dialog as the control channel does; `Err` is the dialog's refusal. + pub fn try_set(app: &VectorcraftApp, key: &str, field: &str, value: Value) -> Result<(), String> { + let id = open_dialog(app, key).ok_or("the dialog is not open")?.id; + let windows = app.dialogs().ok_or("no window")?; + windows.with(|h| h.set_json_field(&ctx(app), id, field, value)) + } + + /// [`try_set`] that must succeed. + pub fn set(app: &VectorcraftApp, key: &str, field: &str, value: Value) { + try_set(app, key, field, value).expect("the dialog takes the value"); + } + + /// Presses OK on the open dialog `key` names and lets the host run the import: `Err` is the reason + /// the import refused, with the dialog left open. + pub fn confirm(app: &mut VectorcraftApp, key: &str) -> Result<(), String> { + let id = open_dialog(app, key).ok_or("the dialog is not open")?.id; + let windows = app.dialogs().ok_or("no window")?; + let ctx = ctx(app); + windows.with(|h| h.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(app, &ctx); + let state = windows.with(|h| h.held_state(id)); + match state { + Some(HeldOk::Refused(reason)) => Err(reason.as_str().to_owned()), + Some(HeldOk::Accepted) => { + windows.with(|h| h.confirm_by_id(&ctx, id)); + Ok(()) + } + Some(_) => Err("the import did not answer".into()), + None if is_open(app, key) => Err("OK was not filed".into()), + None => Ok(()), + } + } + + /// Cancels the open dialog `key` names. + pub fn cancel(app: &VectorcraftApp, key: &str) { + let Some(id) = open_dialog(app, key).map(|d| d.id) else { return }; + if let Some(windows) = app.dialogs() { + windows.with(|h| h.cancel_by_id(&ctx(app), id)); + } + } } #[cfg(test)] mod tests { + use super::test_support as host; use super::*; - use vectorcraft_engine::Session; use vectorcraft_engine::doc::NodeKind; - fn frame(app: &mut VectorcraftApp) -> String { - crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + /// The text of the one text object in the active document. + fn placed_text(app: &VectorcraftApp) -> Option { + let mut found = None; + app.session.doc().unwrap().doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + found = Some(t.plain_text()); + } + }); + found } #[test] fn placing_a_text_file_asks_for_the_import_options_then_places_area_type() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = host::app(); app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); let text = b"one\r\ntwo\r\n\r\nthree\r\n"; let file = json!({"name": "notes.txt", "dataBase64": vectorcraft_format::base64_encode(text)}); let r = app.run("file.place", file).unwrap(); assert_eq!(r["dialog"], KIND); - let text = frame(&mut app); - for label in [ - "Text Import Options", - "Encoding", - "Platform:", - "Character Set:", - "Unicode", - "Line Breaks", - "Join the lines of each paragraph", - "Spaces", - "OK", - "Cancel", - ] { - assert!(text.contains(label), "{label} in {text}"); - } - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("removeLineReturns".into(), json!(true)); - d.fields.insert("removeParagraphReturns".into(), json!(true)); - assert_eq!(options(d)["removeLineReturns"], true); - let r = super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); - let st = app.session.doc().unwrap(); - let n = st.doc.node(vectorcraft_engine::doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); - let NodeKind::Text(t) = &n.kind else { panic!("type") }; - assert_eq!(t.plain_text(), "one two\nthree", "one paragraph per block"); - assert_eq!(st.history.undo.len(), 1); + let fields = host::fields(&app, KIND); + assert_eq!((&fields["characterSet"], &fields["replaceSpaces"]), (&json!("unicode"), &json!(false))); + host::set(&app, KIND, "removeLineReturns", json!(true)); + host::set(&app, KIND, "removeParagraphReturns", json!(true)); + host::confirm(&mut app, KIND).unwrap(); + assert!(!host::is_open(&app, KIND)); + assert_eq!(placed_text(&app).as_deref(), Some("one two\nthree"), "one paragraph per block"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), 1); + assert_eq!(app.ui.text_import["removeLineReturns"], true, "remembered for the next file"); } /// Every character set is a choice: one confirmed last comes back on the next text file and @@ -187,32 +254,18 @@ mod tests { /// off the remembered set is the one the file is placed with. #[test] fn a_remembered_character_set_comes_back_and_places_the_file() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = host::app(); app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); let file = json!({"name": "notes.txt", "dataBase64": vectorcraft_format::base64_encode(&[0x93, 0xFA, 0x96, 0x7B])}); app.ui.text_import = json!({"characterSet": "shiftJis", "platform": "windows"}); app.run("file.place", file.clone()).unwrap(); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("characterSet")).as_deref(), Some("shiftJis")); - assert!(frame(&mut app).contains("Shift JIS"), "the remembered set is shown"); - let r = super::super::confirm(&mut app).unwrap(); - let st = app.session.doc().unwrap(); - let n = st.doc.node(vectorcraft_engine::doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); - let NodeKind::Text(t) = &n.kind else { panic!("type") }; - assert_eq!(t.plain_text(), "日本"); + assert_eq!(host::fields(&app, KIND)["characterSet"], "shiftJis"); + host::confirm(&mut app, KIND).unwrap(); + assert_eq!(placed_text(&app).as_deref(), Some("日本")); assert_eq!(last_options(&app)["characterSet"], "shiftJis", "remembered for Show Import Options off"); app.ui.text_import = json!({"characterSet": "latin9"}); app.run("file.place", file).unwrap(); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("characterSet")).as_deref(), Some("unicode")); - let values: Vec<&str> = CHARACTER_SETS.iter().map(|(v, _)| *v).collect(); - let labels: Vec<&str> = CHARACTER_SETS.iter().map(|(_, l)| *l).collect(); - assert_eq!( - values, - ["unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic", "centralEuropean"] - ); - assert_eq!( - labels, - ["Unicode", "ANSI", "Shift JIS", "GB2312", "Chinese Big 5", "Cyrillic", "GB18030", "Greek", "Turkish", "Baltic", "Central European"] - ); + assert_eq!(host::fields(&app, KIND)["characterSet"], "unicode"); } /// A text file dropped on a canvas is placed by the dialog's OK in the document it was dropped @@ -220,7 +273,7 @@ mod tests { #[test] fn a_dropped_text_files_ok_places_in_the_document_it_was_dropped_on() { use crate::place::{DropAt, DropTarget}; - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = host::app(); for _ in 0..2 { app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); } @@ -228,9 +281,9 @@ mod tests { let st = app.session.doc().unwrap(); let target = DropTarget::Place(DropAt { doc: st.uid, reverts: st.reverts, at: vectorcraft_geom::Point::new(100.0, 100.0), embed: true }); crate::place::drop_files(&mut app, vec![(target, ("notes.txt".into(), None, b"one".to_vec()))]); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + assert!(host::is_open(&app, KIND)); app.session.set_active(1); - super::super::confirm(&mut app).unwrap(); + host::confirm(&mut app, KIND).unwrap(); let objects = |i: usize| app.session.documents()[i].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::(); assert_eq!((objects(0), objects(1)), (1, 0), "placed in the document it was dropped on"); assert_eq!(app.session.active_index(), Some(0));