diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 1cf7af0334..436581d546 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -284,7 +284,7 @@ pub fn specs() -> Vec { "Import Metadata Template…", [], None, - "{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)", + "{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text, dataBase64?: XMP bytes (exactly one source; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)", has_doc, super::fileinfo::apply_template ), diff --git a/crates/engine/src/cmd/fileinfo.rs b/crates/engine/src/cmd/fileinfo.rs index b6b1643ea4..b72068706a 100644 --- a/crates/engine/src/cmd/fileinfo.rs +++ b/crates/engine/src/cmd/fileinfo.rs @@ -213,7 +213,7 @@ enum Merge { Append, } -/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`. +/// File Info › Import: `file.info.applyTemplate {path?|name?|data?|dataBase64?, mode, apply?, base?}`. pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result { let mode = match text_param(p, "mode", APPLY)? { Some("replace") => Merge::Replace, @@ -236,15 +236,14 @@ pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result { Ok(out) } -/// The bytes of the template `p` names: `path`, `name` (in the metadata templates folder) or -/// `data`, exactly one, at most [`MAX_TEMPLATE_FILE`] long. +/// Reads one template source from `p` up to [`MAX_TEMPLATE_FILE`] bytes. fn template_bytes(s: &Session, p: &Value) -> Result> { - let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?]; + let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?, text_param(p, "dataBase64", APPLY)?]; // At most one byte past the limit is read, so a huge file is never read whole. let read = |path: &str| super::fileio::read_file_head(path, MAX_TEMPLATE_FILE + 1); let bytes = match given { - [Some(path), None, None] => read(path)?, - [None, Some(name), None] => { + [Some(path), None, None, None] => read(path)?, + [None, Some(name), None, None] => { let dir = s.metadata_templates_dir().ok_or_else(|| bad(APPLY, "no metadata templates folder here"))?; let mut path = template_path(dir, name, APPLY)?; // A template `file.info.templates` lists: by its `file` first, then by its `name` with @@ -268,9 +267,15 @@ fn template_bytes(s: &Session, p: &Value) -> Result> { // The app's own folder: no root applies. crate::file_access::unconfined(|| read(&path))? } - [None, None, Some(data)] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)), - [None, None, Some(data)] => data.as_bytes().to_vec(), - _ => return Err(bad(APPLY, "give one of `path`, `name` and `data`")), + [None, None, Some(data), None] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)), + [None, None, Some(data), None] => data.as_bytes().to_vec(), + [None, None, None, Some(data)] => { + if data.len() > MAX_TEMPLATE_FILE.div_ceil(3) * 4 { + return Err(too_big(APPLY)); + } + vectorcraft_format::base64_decode(data).ok_or_else(|| bad(APPLY, "dataBase64 is not base64"))? + } + _ => return Err(bad(APPLY, "give one of `path`, `name`, `data` or `dataBase64`")), }; if bytes.len() > MAX_TEMPLATE_FILE { return Err(too_big(APPLY)); diff --git a/crates/engine/src/tests/fileinfo.rs b/crates/engine/src/tests/fileinfo.rs index d573235335..268471a995 100644 --- a/crates/engine/src/tests/fileinfo.rs +++ b/crates/engine/src/tests/fileinfo.rs @@ -708,12 +708,17 @@ fn metadata_template_errors() { assert!(e.to_string().contains("larger than 8 MB"), "{e}"); let e = s.execute("file.info.applyTemplate", &json!({"data": " ".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1), "mode": "keep"})).unwrap_err(); assert!(e.to_string().contains("larger than 8 MB"), "{e}"); + let encoded = "A".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES.div_ceil(3) * 4 + 1); + let e = s.execute("file.info.applyTemplate", &json!({"dataBase64": encoded, "mode": "keep"})).unwrap_err(); + assert!(e.to_string().contains("larger than 8 MB"), "{e}"); for bad in [ json!({"data": xmp, "mode": "merge"}), json!({"data": xmp}), json!({"data": xmp, "mode": 3}), json!({"mode": "keep"}), json!({"data": xmp, "path": not_xmp.to_str().unwrap(), "mode": "keep"}), + json!({"data": xmp, "dataBase64": "SGVsbG8=", "mode": "keep"}), + json!({"dataBase64": "!", "mode": "keep"}), json!({"path": dir.join("missing.xmp").to_str().unwrap(), "mode": "keep"}), json!({"path": not_xmp.to_str().unwrap(), "mode": "keep"}), json!({"path": big.to_str().unwrap(), "mode": "keep"}), diff --git a/crates/render/src/changed.rs b/crates/render/src/changed.rs index cea07dab35..9a580a1b11 100644 --- a/crates/render/src/changed.rs +++ b/crates/render/src/changed.rs @@ -94,6 +94,15 @@ impl crate::Renderer { /// renderer draws copies of the objects (`proof::prepare`), so they are measured afresh and /// nothing is held. pub fn changed(&mut self, old: &Document, new: &Document, opts: &crate::RenderOptions) -> Changed { + // Trim View clips each draw when blending reaches the page and clips one composited + // layer otherwise. Changing modes can change unchanged art at an artboard edge. + if opts.trim && !old.artboards.is_empty() { + let before = crate::proof::prepare(old, opts, &mut self.proof_art); + let after = crate::proof::prepare(new, opts, &mut self.proof_art); + if self.children_blend(&before.layers) != self.children_blend(&after.layers) { + return Changed::Everything; + } + } let renderer = (!crate::proof::overprints(opts)).then_some(self); changed_with(old, new, renderer, opts) } diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 8021e701de..cafc8ec35b 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -134,6 +134,9 @@ impl Renderer { // During a drag, a larger shadow on a multithreaded context is filtered within the // drag's budget (`with_filters`), and no raster is kept. if f.opts.dragging && f.mt && w * h > DRAG_PIXEL_BUDGET { + // The fallback can differ from a still raster (a glow blurs soft alpha here). + // A patch over a still frame cannot splice these pictures together. + self.stats.view_sized += 1; return None; } let (w, h) = (w as u16, h as u16); diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 1832f18580..1090c937ad 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -1581,6 +1581,31 @@ fn a_drag_renders_raster_effects_within_the_drag_budget() { assert!(after == threaded().render(&scaled, 1600, 1000, view, &still).pixels, "the frame after the drag"); } +#[test] +fn a_drag_glow_fallback_cannot_be_spliced_into_a_still_frame() { + let doc = doc_with( + Rect::new(20.0, 20.0, 40.0, 40.0), + Color::BLACK, + vec![ + ("stylize.outerGlow", json!({"blur": 1.3, "color": "#ff0000", "opacity": 100, "mode": "normal"})), + ("stylize.outerGlow", json!({"blur": 1.0, "color": "#0000ff", "opacity": 100, "mode": "normal"})), + ], + ); + let view = Affine::translate((600.0, 600.0)) * Affine::scale(40.0) * Affine::translate((-30.0, -30.0)); + let mut still = Renderer::new(); + still.threads = 2; + let still_pixels = still.render(&doc, 1200, 1200, view, &RenderOptions::default()).pixels; + assert_eq!(still.stats.view_sized, 0, "the still frame draws both whole rasters"); + + let mut drag = Renderer::new(); + drag.threads = 2; + let opts = RenderOptions { interacting: true, dragging: true, ..Default::default() }; + let drag_pixels = drag.render(&doc, 1200, 1200, view, &opts).pixels; + assert_eq!(drag.stats.previewed, 0, "the fallback filter fits the drag budget without downsampling"); + assert!(drag_pixels != still_pixels, "a glow over the first glow differs from the fallback filter"); + assert!(drag.stats.view_sized > 0, "the fallback must replace the whole frame"); +} + /// While interacting, a group holding a symbol instance whose art lies outside the 20 × 20 /// square around the origin draws its drop shadow from the raster of an earlier frame. The /// shadow is made from the instance's art, which the renderer measures the group's content by. diff --git a/crates/render/src/tests/changed.rs b/crates/render/src/tests/changed.rs index 07251df938..3650d2208a 100644 --- a/crates/render/src/tests/changed.rs +++ b/crates/render/src/tests/changed.rs @@ -99,6 +99,42 @@ fn area(c: Changed) -> Rect { } } +#[test] +fn removing_the_last_blend_in_trim_view_repaints_the_artboard_edges() { + use vectorcraft_color::BlendMode; + + let mut before = Document::new(110.0, 80.0); + let layer = before.layers[0].id; + for color in [Color::BLACK, Color::WHITE] { + let shape = rect(&mut before, Rect::new(-10.0, 18.0, 25.0, 44.0), color); + before.insert(Some(layer), usize::MAX, shape).unwrap(); + } + let mut blend = rect(&mut before, Rect::new(70.0, 35.0, 85.0, 50.0), Color::rgb(0.7, 0.4, 0.3)); + blend.blend = BlendMode::Multiply; + let id = before.insert(Some(layer), usize::MAX, blend).unwrap(); + let mut after = before.clone(); + after.node_mut(id).unwrap().blend = BlendMode::Normal; + + let opts = RenderOptions { trim: true, ..Default::default() }; + let mut r = Renderer::new(); + let first = r.render(&before, W, H, view(), &opts); + let change = r.changed(&before, &after, &opts); + let last = Renderer::new().render(&after, W, H, view(), &opts); + patched(&mut r, &first, &after, change, &last, &opts); + assert_eq!(change, Changed::Everything); + assert!(matches!(r.changed(&before, &after, &RenderOptions::default()), Changed::Area(_))); + + // An overprinting fill gets its blend while preparing the proof. + let mut overprinting = after.clone(); + overprinting.node_mut(id).unwrap().appearance.fill_mut().unwrap().overprint = true; + let proof = RenderOptions { overprint_preview: true, ..opts }; + let first = r.render(&overprinting, W, H, view(), &proof); + let change = r.changed(&overprinting, &after, &proof); + let last = Renderer::new().render(&after, W, H, view(), &proof); + patched(&mut r, &first, &after, change, &last, &proof); + assert_eq!(change, Changed::Everything, "the proofed fill changes the clipping mode"); +} + #[test] fn moving_an_object_changes_where_it_was_and_is() { let (old, [loose, ..]) = document(); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b7502126e1..6db68a7371 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -120,7 +120,7 @@ impl VectorcraftApp { last_ms: 0.0, moved: false, from_worker: false, - worker_parts: false, + whole_frames: false, reused: None, waits_for_still: cfg!(target_arch = "wasm32"), still: None, @@ -242,6 +242,7 @@ impl VectorcraftApp { three_d_dialog: None, three_d: Default::default(), export_dialogs: Default::default(), + package_document: None, web_export: Default::default(), flattener_preview: Default::default(), flatten_dialog: Default::default(), diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 08b15cddc5..1be3cbe933 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -25,10 +25,11 @@ pub struct CanvasCache { /// The frame shown was rendered on the worker: an interaction's frames stay there /// ([`canvas::show`]). pub from_worker: bool, - /// The worker's frame shown drew art in a way that depends on its size, or a part of it drawn - /// again on this thread would not have matched the frame around it: until the worker's next - /// frame is shown, edits of the frame shown render on the worker ([`canvas::show`]). - pub worker_parts: bool, + /// The frame shown drew art in a way that depends on its size, or a part of it drawn again on + /// this thread would not have matched the frame around it: until the next whole frame is shown, + /// edits of the frame shown render whole, on the worker when the frame is heavy + /// ([`canvas::show`]). + pub whole_frames: bool, /// The frame shown holds pixels the worker copied from its last frame, and when it was shown /// (seconds, egui's input time): it renders whole once it has been shown for /// [`canvas::STILL_SECS`] with the view unmoved. diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index f3f96171c0..709aee2c5c 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -173,7 +173,9 @@ impl Component for CanvasDrops<'_> { let panel = Target::new(rect, view, covered, |p: &PanelDrag| (!matches!(p, PanelDrag::Art { .. })).then(|| Payload::Panel(p.clone()))); let style = Target::new(rect, view, covered, |d: &StyleDrag| (d.document == self.document).then(|| Payload::Style(d.clone()))); let symbol = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Symbol(d.grabbed.clone()))); - let brush = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Brush(d.grabbed.clone()))); + let brush = Target::new(rect, view, covered, |d: &ListDrag| { + (d.grabbed.doc == self.document).then(|| Payload::Brush(d.grabbed.clone())) + }); let library = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Library(d.grabbed.clone()))); let panel = cx.drop_target::(&panel); let style = cx.drop_target::(&style); @@ -336,7 +338,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), Payload::Panel(PanelDrag::LibraryGraphic { library, item }) => { run(app, "library.use", json!({"library": library, "kind": "graphic", "item": item, "center": [at.x, at.y]})) } - Payload::Brush(key) => match hit() { + Payload::Brush(key) if app.session.active().is_some_and(|st| st.uid == key.doc) => match hit() { None if brush_has_art(app, key) => run(app, "brush.placeArt", json!({"name": key.name, "x": at.x, "y": at.y})), None => Ok(()), Some(hit) => { @@ -344,13 +346,14 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), run(app, "brush.apply", json!({"name": key.name, "ids": [owner]})) } }, + Payload::Brush(_) => Ok(()), Payload::Style(style) if app.session.active().is_some_and(|st| st.uid == style.document) => { let Some(hit) = hit() else { return Ok(()) }; let top = top_object(app, &hit)?; run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy})) } Payload::Style(_) => Ok(()), - Payload::Panel(PanelDrag::Paint { params, paint, .. }) if !params.is_null() => { + Payload::Panel(PanelDrag::Paint { params, paint, rows, .. }) if !params.is_null() => { if let Some(color) = paint.color() && crate::panels::proxy_cmd(app, false) == "paint.setFill" && let Some((id, points)) = selected_mesh_drop(app, at, zoom) @@ -359,7 +362,14 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), return run(app, "object.mesh.setPointColor", params); } let Some(hit) = hit() else { return Ok(()) }; - let mut params = params.clone(); + let mut params = if let Some(rows) = rows.as_ref().filter(|rows| rows.unlinked_process_color) + && app.session.active().is_some_and(|st| st.uid != rows.document) + && let Some(color) = paint.color() + { + json!({"color": crate::panels::color_json(&color), "keepModel": true}) + } else { + params.clone() + }; params["ids"] = json!([owner(app, &hit)?]); params["focus"] = json!(false); let cmd = crate::panels::proxy_cmd(app, false); diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index 358c01f385..6060043515 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -10,7 +10,7 @@ use vectorcraft_engine::Session; use vectorcraft_geom::Point; use super::{CarriedArt, Dropped, Payload, apply_drop}; -use crate::panel_drag::PanelDrag; +use crate::panel_drag::{PanelDrag, SwatchRows}; use crate::panels::brushes::{BrushKey, BrushLibraries}; use crate::panels::graphic_styles::StyleDrag; use crate::panels::library_panel::{self, LibraryKey, LibraryKind as _}; @@ -202,6 +202,32 @@ fn a_drop_runs_the_effect_of_its_payload() { symbol_at(&app, empty); } +#[test] +fn a_foreign_brush_drop_never_applies_or_places_a_same_named_brush() { + let (mut app, ctx) = app_with_canvas(); + let make_brush = |app: &mut VectorcraftApp, width| { + app.run("shape.rectangle", json!({"x": 15, "y": 15, "width": width, "height": 30})).unwrap(); + app.run("brush.new", json!({"name": "Shared Brush", "type": "art"})).unwrap(); + }; + make_brush(&mut app, 30); + let document = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + make_brush(&mut app, 60); + app.run("brush.setCurrent", json!({"name": null})).unwrap(); + let path = NodeId(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 350, "y": 200}]})).unwrap()["id"].as_u64().unwrap()); + frame(&mut app, &ctx, vec![]); + + let brush_of = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(path).unwrap().appearance.stroke().and_then(|s| s.brush.clone()); + let before = brush_of(&app); + assert!(before.is_none()); + let history = undo_len(&app); + let payload = Payload::Brush(BrushKey { doc: document, name: "Shared Brush".into(), group: false }); + drop_at(&mut app, payload.clone(), Point::new(200.0, 200.0), DropOperation::Move).unwrap(); + assert_eq!(brush_of(&app), before, "the foreign drop leaves the path's stroke alone"); + drop_at(&mut app, payload, Point::new(200.0, 260.0), DropOperation::Move).unwrap(); + assert_eq!(undo_len(&app), history, "no artwork is placed on empty canvas either"); +} + /// A symbol of another document is added here and placed in one undo step, the source is unchanged, and a symbol of /// a closed document places nothing. #[test] @@ -230,6 +256,81 @@ fn a_symbol_from_another_document_is_added_and_placed_in_one_step() { /// A colour dropped on a selected mesh recolors the point under the pointer, else the patch's four points; the same /// colour again records no step. +#[test] +fn a_process_swatch_canvas_drop_keeps_its_color_in_another_document() { + let (mut app, ctx) = app_with_canvas(); + let name = "Shared Swatch"; + let at = Point::new(250.0, 70.0); + let add_target = |app: &mut VectorcraftApp| { + NodeId(app.run("shape.rectangle", json!({"x": 200, "y": 20, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()) + }; + let fill = |app: &VectorcraftApp, target| app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(); + + app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); + let source = app.session.active().unwrap(); + let paint = source.doc.swatch(name).unwrap().paint.clone(); + let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true }; + let payload = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None }; + + let local_target = add_target(&mut app); + app.run("swatch.edit", json!({"name": name, "color": "#ff8800"})).unwrap(); + let edited = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone(); + drop_at(&mut app, Payload::Panel(payload.clone()), at, DropOperation::Move).unwrap(); + assert_eq!(fill(&app, local_target), edited, "a same-document drop still resolves the swatch by name"); + assert_ne!(edited, paint); + + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap(); + let destination = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone(); + let target = add_target(&mut app); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + frame(&mut app, &ctx, vec![]); + + drop_at(&mut app, Payload::Panel(payload), at, DropOperation::Move).unwrap(); + assert_eq!(fill(&app, target), paint); + assert_eq!(app.session.active().unwrap().doc.swatch(name).unwrap().paint, destination); +} + +#[test] +fn a_swatch_drag_keeps_its_color_after_next_document() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let name = "Shared Swatch"; + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); + let source = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap(); + let target = NodeId(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("window.previousDocument", json!({})).unwrap(); + + let mut panel = Panel::new(app, |app, ui| { + app.sync_views(); + ui.allocate_ui_with_layout(egui::vec2(280.0, 480.0), egui::Layout::top_down(egui::Align::Min), |ui| { + crate::panels::swatches::show(app, ui); + }); + canvas::show(app, ui); + }); + let label = "Shared Swatch, #ff0000"; + let from = panel.rect(label).center(); + let to = panel.app().canvas_view().unwrap().to_screen(Point::new(100.0, 100.0)); + panel.drag_hold_role(label, Role::LIST_ITEM, to - from); + assert!(drag::active::(panel.ctx()).is_some(), "the Swatches row starts a paint drag"); + panel.key(Key::F6, Modifiers::COMMAND); + assert_eq!(panel.app().session.active().unwrap().uid, destination); + assert!(drag::active::(panel.ctx()).is_some(), "the drag stays held during Next Document"); + panel.release(); + + let app = panel.app(); + assert_eq!(app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(), source); +} + #[test] fn a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it() { use vectorcraft_doc::GradientMesh; diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 780dd5f7a8..1c1d17c00d 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -55,12 +55,15 @@ pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::Colo /// frame. A frame the worker rendered is drawn again here too, so an edit (a Pen drag's curve) /// shows in the frame it is made in, when the part's share of the frame's last whole render time /// is at most 8 ms, and except when that frame drew raster effects from rasters made before their -/// objects moved ([`crate::CanvasCache::moved`]), holds pixels copied from the worker's last frame -/// ([`crate::CanvasCache::reused`]), drew art in a way that depends on its size, or a part drawn -/// again here since it arrived would have differed from it ([`crate::CanvasCache::worker_parts`]): -/// the worker's renderer keeps the rasters of the art's effects, and this thread's doesn't. What -/// changed is measured by this thread's renderer: it keeps what it measures (a 3D effect's art) to -/// draw the part again. +/// objects moved ([`crate::CanvasCache::moved`]) or holds pixels copied from the worker's last frame +/// ([`crate::CanvasCache::reused`]): the worker's renderer keeps the rasters of the art's effects, +/// and this thread's doesn't. No frame that drew art in a way that depends on its size, or that a +/// part drawn again here since it was shown would have differed from, is drawn again in part +/// ([`crate::CanvasCache::whole_frames`]). A frame that drew nothing from moved rasters or at a +/// drag's lower resolution can supply the unchanged pixels when a Pen press starts an interaction +/// over a worker frame, even when [`CacheKey::interacting`] and [`CacheKey::dragging`] change. +/// Leaving an interaction still replaces the whole frame. What changed is measured by this thread's renderer: it keeps what +/// it measures (a 3D effect's art) to draw the part again. pub(super) fn changed_pixels( app: &mut VectorcraftApp, key: &CacheKey, @@ -70,14 +73,20 @@ pub(super) fn changed_pixels( w: u32, h: u32, ) -> Option> { - let (shown, _) = app.canvas.shown.as_ref().filter(|(_, o)| o == opts)?; + let shown_key = app.canvas.key.as_ref()?; + // The worker keeps its still rasters while the UI thread draws the first edit. Rendering only + // part of a UI-thread frame could evict its own still rasters before a drag needs them. + let starting = app.canvas.from_worker && !app.canvas.moved && key.interacting && !shown_key.interacting; + let (shown, _) = app.canvas.shown.as_ref().filter(|(_, o)| { + o == opts || starting && vectorcraft_render::RenderOptions { interacting: opts.interacting, dragging: opts.dragging, ..o.clone() } == *opts + })?; // A viewed opacity mask shows its coverage wherever its art reaches, past its object's bounds. if opts.mask_view.is_some() { return None; } - let shown_key = app.canvas.key.as_ref()?; - let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, ..key.clone() }; - let worker_kept = app.canvas.from_worker && (app.canvas.moved || app.canvas.worker_parts || app.canvas.reused.is_some()); + let (interacting, dragging) = if starting { (shown_key.interacting, shown_key.dragging) } else { (key.interacting, key.dragging) }; + let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, interacting, dragging, ..key.clone() }; + let worker_kept = app.canvas.from_worker && (app.canvas.moved || app.canvas.reused.is_some()); // A frame on its way of an older revision is not shown when it arrives ([`show_worker_frame`]). let on_its_way = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|p| p.doc != key.doc || p.revision >= key.revision); if !same_view || app.canvas.texture.is_none() || worker_kept || on_its_way { @@ -92,11 +101,12 @@ pub(super) fn changed_pixels( vectorcraft_render::Changed::Nothing => Some(None), vectorcraft_render::Changed::Area(area) => match vectorcraft_render::view_pixels(area, view, w, h) { None => Some(None), - Some([x0, y0, x1, y1]) => { + Some([x0, y0, x1, y1]) if !app.canvas.whole_frames => { let ((x0, x1), (y0, y1)) = (in_steps(x0, x1, w), in_steps(y0, y1, h)); let share = (f64::from(x1 - x0) * f64::from(y1 - y0)) / (f64::from(w) * f64::from(h)); (share <= budget.min(0.5)).then_some(Some([x0, y0, x1, y1])) } + Some(_) => None, }, vectorcraft_render::Changed::Everything => None, } @@ -597,7 +607,7 @@ fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate: app.canvas.reused = done.reused.then(|| frame::clock(ctx)); app.canvas.moved = done.moved > 0; app.canvas.from_worker = true; - app.canvas.worker_parts = done.view_sized; + app.canvas.whole_frames = done.view_sized; } /// The size and view matrix of the frame to render: the pixel region in Pixel Preview, else the whole canvas. @@ -686,11 +696,12 @@ pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::f /// key: only the document changed since the frame shown, in that part of it /// ([`changed_pixels`]). `None`: nothing in view changed. `last_ms` stays the whole frame's. /// -/// Over a frame the worker rendered, a part that drew raster effects from rasters made before -/// their objects moved or at a drag's lower resolution ([`vectorcraft_render::FrameStats::moved`]), -/// or art in a way that depends on the frame's size ([`vectorcraft_render::FrameStats::view_sized`]), -/// would not match the frame around it: it is not drawn, false is returned, and the edits after it -/// render on the worker until the worker's next frame is shown ([`crate::CanvasCache::worker_parts`]). +/// A part that drew art in a way that depends on the frame's size +/// ([`vectorcraft_render::FrameStats::view_sized`]), draws effects at a drag's lower resolution +/// ([`vectorcraft_render::FrameStats::previewed`]), or uses this thread's moved rasters over a +/// worker frame, could differ from the frame around it. It is not drawn, false is returned, +/// and the edits after it render whole until the next whole frame is +/// shown ([`crate::CanvasCache::whole_frames`]). fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]>) -> bool { let Frame { key, doc, effects, view, opts, pixel, .. } = frame; let t0 = monotonic_ms(); @@ -703,8 +714,8 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4] let renderer = &mut app.canvas.renderer; let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * *view; let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, opts)); - if app.canvas.from_worker && (renderer.stats.moved > 0 || renderer.stats.view_sized > 0) { - app.canvas.worker_parts = true; + if renderer.stats.view_sized > 0 || renderer.stats.previewed > 0 || app.canvas.from_worker && renderer.stats.moved > 0 { + app.canvas.whole_frames = true; return false; } let width = part.width; @@ -824,6 +835,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { app.perf.render_ms = monotonic_ms() - t0; app.canvas.last_ms = app.perf.render_ms; app.canvas.moved = app.canvas.renderer.stats.moved > 0; + app.canvas.whole_frames = app.canvas.renderer.stats.view_sized > 0 || app.canvas.renderer.stats.previewed > 0; app.canvas.from_worker = false; app.canvas.reused = None; } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d560fd2b6b..c9e44fd207 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -964,6 +964,72 @@ fn an_edit_renders_only_its_part_of_the_canvas() { assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "a new view renders all of it"); } +/// An edit over art that a part of the canvas would draw with other pixels than the whole canvas +/// does ([`vectorcraft_render::FrameStats::view_sized`]) renders all of it, on this thread too, +/// and shows what a fresh renderer draws: a blur cropped to the view, which the frame shown drew, +/// and an inner glow that fits the view but not the part the edit changed. +#[test] +fn an_edit_over_art_drawn_for_the_frames_size_renders_all_of_it() { + keeping_color_settings(an_edit_over_art_drawn_for_the_frames_size); +} + +fn an_edit_over_art_drawn_for_the_frames_size() { + for cropped in [true, false] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.canvas.worker_started = true; // every frame on this thread, however long it takes + app.canvas.renderer.threads = 2; + let (rect, effect) = if cropped { + (json!({"x": 0, "y": 0, "width": 400, "height": 300}), json!({"effect": "blur.gaussian", "params": {"radius": 8}})) + } else { + (json!({"x": 150, "y": 110, "width": 100, "height": 80}), json!({"effect": "stylize.innerGlow", "params": {"blur": 8}})) + }; + let art = app.run("shape.rectangle", rect).unwrap()["id"].clone(); + let mut effect = effect; + effect["ids"] = json!([art]); + app.run("effect.apply", effect).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 145, "y": 105, "width": 10, "height": 10})).unwrap()["id"].clone(); + let outside = app.run("shape.rectangle", json!({"x": 5000, "y": 5000, "width": 10, "height": 10})).unwrap()["id"].clone(); + app.run("select.none", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + shapes(&mut app, &ctx); + // A new view: the next frame renders whole. + if let Some(vm) = app.view_mut() { + (vm.zoom, vm.center) = if cropped { (16.0, Point::new(150.0, 110.0)) } else { (1.5, Point::new(200.0, 150.0)) }; + } + // Where the canvas texture changed in a frame, and its pixels there. + let canvas = |app: &VectorcraftApp, mut delta: egui::TexturesDelta| { + let tex = app.canvas.texture.as_ref().map(|t| t.id()); + let set = delta.set.iter().find(|(t, _)| tex == Some(**t)).and_then(|(_, d)| d.last()).map(|d| { + let egui::ImageData::Color(img) = &d.image; + (d.pos, img.pixels.clone()) + }); + delta.clear(); + set + }; + let (_, delta) = frame_output(&mut app, &ctx); + assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "the first frame renders all of it"); + assert_eq!(app.canvas.renderer.stats.view_sized > 0, cropped, "the frame shown drew art for its size: {cropped}"); + assert_eq!(app.canvas.whole_frames, cropped, "the frame records whether its art depends on its size"); + app.run("paint.setFill", json!({"color": "#00ff00", "ids": [outside]})).unwrap(); + let (_, delta) = frame_output(&mut app, &ctx); + assert!(canvas(&app, delta).is_none(), "an edit outside the view does not upload a new canvas"); + app.run("paint.setFill", json!({"color": "#ff0000", "ids": [id]})).unwrap(); + let (_, delta) = frame_output(&mut app, &ctx); + let (pos, edited) = canvas(&app, delta).expect("the edit shows"); + assert!(pos.is_none(), "the edit renders all of it, cropped: {cropped}"); + assert_eq!(app.canvas.whole_frames, cropped, "the replacement records its own render stats"); + app.canvas.renderer = vectorcraft_render::Renderer::new(); + app.canvas.renderer.threads = 2; + app.canvas.key = None; + let (_, delta) = frame_output(&mut app, &ctx); + let fresh = canvas(&app, delta).map(|(_, px)| px); + assert!(fresh.as_ref() == Some(&edited), "what a fresh renderer draws, cropped {cropped}: {}", differing(&edited, fresh.as_deref())); + } +} + /// A canvas more device pixels across than the largest texture side the display supports renders /// its art at fewer pixels a point, within that size, and draws it over the whole canvas. Pixel /// Preview's region of document pixels stays within it too. @@ -1737,10 +1803,15 @@ fn dragging_with_raster_effects() { /// without a drag, renders without `dragging` and draws the same. #[test] fn a_drag_on_the_canvas_draws_raster_effects_at_a_lower_resolution() { - keeping_color_settings(a_drag_at_a_lower_resolution); + keeping_color_settings(|| a_drag_at_a_lower_resolution(false)); } -fn a_drag_at_a_lower_resolution() { +#[test] +fn a_whole_drag_preview_keeps_the_next_canvas_render_whole() { + keeping_color_settings(|| a_drag_at_a_lower_resolution(true)); +} + +fn a_drag_at_a_lower_resolution(fits_frame: bool) { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; // render on this thread @@ -1763,7 +1834,7 @@ fn a_drag_at_a_lower_resolution() { }; run(&mut app, vec![]); if let Some(vm) = app.view_mut() { - (vm.zoom, vm.center) = (32.0, Point::new(200.0, 155.0)); + (vm.zoom, vm.center) = (if fits_frame { 6.4 } else { 32.0 }, Point::new(200.0, 155.0)); } let still = run(&mut app, vec![]).expect("the zoomed view renders"); assert_eq!(app.canvas.renderer.stats.previewed, 0, "a still frame"); @@ -1771,10 +1842,19 @@ fn a_drag_at_a_lower_resolution() { let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; run(&mut app, vec![egui::Event::PointerMoved(at)]); run(&mut app, vec![button(at, true)]); + if fits_frame { + // Force the first move to draw a whole frame without a previous effect raster. + app.canvas.renderer = vectorcraft_render::Renderer::new(); + app.canvas.key = None; + } for step in [1.0, 2.0] { let drawn = run(&mut app, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]).expect("each frame of the drag renders"); assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && k.dragging), "step {step}"); assert_eq!(app.canvas.renderer.stats.previewed, 1, "the filtered content, step {step}"); + if fits_frame { + assert_eq!(app.canvas.renderer.stats.view_sized, 0, "only the drag budget reduced the raster"); + assert!(app.canvas.whole_frames, "a whole drag preview cannot accept a full-resolution patch"); + } assert!(app.canvas.moved); assert!(drawn != still, "the rectangle moved, step {step}"); } @@ -1788,9 +1868,15 @@ fn a_drag_at_a_lower_resolution() { assert!(fresh.as_ref() == Some(&after), "the frame after the drag is what a fresh renderer draws: {}", differing(&after, fresh.as_deref())); // A dialog's preview: an interaction, and no drag. app.session.begin_interaction("Texturizer").unwrap(); - assert!(run(&mut app, vec![]) == Some(after), "a dialog's preview draws the effect at full resolution"); + app.session.preview("effect.setParams", &json!({"index": 0, "item": null, "ids": [id], "params": {"relief": 20}})).unwrap(); + let preview = run(&mut app, vec![]).expect("the preview renders"); + assert!(preview != after, "the preview changes the art"); assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && !k.dragging)); assert_eq!(app.canvas.renderer.stats.previewed, 0); + app.canvas.renderer = vectorcraft_render::Renderer::new(); + app.canvas.key = None; + let fresh = run(&mut app, vec![]); + assert!(fresh.as_ref() == Some(&preview), "a dialog's preview draws the effect at full resolution: {}", differing(&preview, fresh.as_deref())); } /// Where frame `b` differs from `a`: how many pixels, the first, and the largest channel difference. @@ -1885,10 +1971,10 @@ fn a_drag_over_a_wide_blur() { } } -/// An interaction's frames stay on the worker once it drew the frame shown, however fast that -/// frame was: the worker's renderer keeps the effect rasters that made it fast, and this -/// thread's renderer, without them, would draw the next frame slowly. Without a frame from the -/// worker, a fast frame renders on this thread as before. +/// An interaction's whole frames (here after a new zoom) stay on the worker once it drew the frame +/// shown, however fast that frame was: the worker's renderer keeps the effect rasters that made it +/// fast, and this thread's renderer, without them, would draw the next frame slowly. Without a +/// frame from the worker, a fast frame renders on this thread as before. #[test] fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -1901,6 +1987,9 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); (app.canvas.from_worker, app.canvas.last_ms) = (from_worker, 1.0); app.session.begin_interaction("Preview").unwrap(); + if let Some(vm) = app.view_mut() { + vm.zoom *= 1.25; + } shapes(&mut app, &ctx); let pending = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|k| k.interacting); assert_eq!(pending, from_worker, "sent to the worker: {from_worker}"); @@ -1913,9 +2002,9 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { } } -/// A Pen drag over a frame the worker drew draws each move's curve into that frame, here, in the -/// frame of the move: once the press's frame arrives from the worker, every move shows the -/// document's revision and queues nothing on the worker. When the frame shown drew effect rasters +/// A Pen drag over a frame the worker drew draws the press's anchor and each move's curve into +/// that frame, here, in the frame of the press or the move: each shows the document's revision and +/// queues nothing on the worker. When the frame shown drew effect rasters /// from before their objects moved, when a part drawn here would have differed from it, or when /// the part's share of the whole frame's time is over 8 ms, the next move renders on the worker, /// and the moves after the worker's frame are drawn here again. A frame of an older revision on @@ -1936,6 +2025,14 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() { let (worker, mut side) = WorkerSide::start(); app.canvas.worker = Some(worker); app.canvas.last_ms = 50.0; + // A new zoom: the frame shown is the worker's. + if let Some(vm) = app.view_mut() { + vm.zoom *= 1.25; + } + frame(&mut app, &ctx, vec![]); + assert!(side.render()); + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.from_worker, "the worker drew the frame shown"); app.select_tool("pen"); let revision = |app: &VectorcraftApp| Some(app.session.active().unwrap().revision); let shown = |app: &VectorcraftApp| app.canvas.key.as_ref().map(|k| k.revision); @@ -1943,8 +2040,9 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() { let mut at = app.canvas_view().unwrap().to_screen(Point::new(105.0, 155.0)); frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); frame(&mut app, &ctx, vec![button(at, true)]); - assert!(shown(&app) < revision(&app), "the press's frame, the first of the drag, renders on the worker"); - assert!(side.render()); + assert_eq!(shown(&app), revision(&app), "the press's anchor, the first frame of the drag, is drawn in its own frame"); + assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting), "the press's frame is the interaction's"); + assert!(side.jobs.try_recv().is_err(), "the press queues nothing on the worker"); let mut drag = |app: &mut VectorcraftApp| { at += vec2(9.0, 5.0); frame(app, &ctx, vec![egui::Event::PointerMoved(at)]); @@ -1957,7 +2055,7 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() { for case in ["moved", "differs", "slow"] { match case { "moved" => app.canvas.moved = true, - "differs" => app.canvas.worker_parts = true, + "differs" => app.canvas.whole_frames = true, _ => app.canvas.last_ms = 10_000.0, } drag(&mut app); @@ -1965,26 +2063,26 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() { assert!(side.render(), "{case}: the move renders on the worker"); drag(&mut app); assert_eq!(shown(&app), revision(&app), "{case}: after the worker's frame, the next move is drawn here"); - assert!(!app.canvas.worker_parts, "{case}"); + assert!(!app.canvas.whole_frames, "{case}"); } // A worker's frame that drew art in a way that depends on its size: the move after it renders // on the worker too. - app.canvas.worker_parts = true; + app.canvas.whole_frames = true; drag(&mut app); let job = side.jobs.try_iter().last().expect("the move is on the worker"); let done = crate::render_worker::render(&mut side.renderer, &mut side.kept, job); side.done.send(crate::render_worker::Done { ms: 50.0, view_sized: true, ..done }).unwrap(); drag(&mut app); - assert!(app.canvas.worker_parts, "the frame shown drew art that depends on its size"); + assert!(app.canvas.whole_frames, "the frame shown drew art that depends on its size"); assert!(shown(&app) < revision(&app) && side.render(), "the move after it renders on the worker"); drag(&mut app); assert_eq!(shown(&app), revision(&app), "after the next worker frame, the move is drawn here"); // A frame on its way of an older revision: the next move is drawn here, and that frame is not // shown when it arrives. - app.canvas.worker_parts = true; + app.canvas.whole_frames = true; drag(&mut app); assert!(app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()), "a frame is on its way"); - app.canvas.worker_parts = false; + app.canvas.whole_frames = false; for late in [false, true] { if late { assert!(side.render()); diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index 4d66df8ecb..310eba4a6a 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -163,12 +163,13 @@ pub fn open(app: &mut VectorcraftApp, name: Option<&str>) -> Result, object_keys: Option<&[&str]>) -> Result { + let source = app.session.active().ok_or("no document open")?; + let document = source.uid; let ty = f.get("__type").and_then(Value::as_str).unwrap_or_default(); let object = object_keys.is_some(); let ctx = app.ui_ctx.clone().ok_or("no window")?; // Modal: no edit changes the document while the dialog is open, so the previews read this snapshot. - let doc = app.session.active().map(|st| st.doc.clone()); - let rows = rows(ty, object, doc, crate::canvas::rulers::unit_kind(app.session.general_unit())); + let rows = rows(ty, object, Some(source.doc.clone()), crate::canvas::rulers::unit_kind(app.session.general_unit())); let title = Label::from(title(ty, object)); let mut initial = form::fields_of(&rows, f); // The hidden values the rows read whole stay JSON: an untagged read makes an array a list of values. @@ -192,7 +193,15 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map, object_keys: Op } }) .held_ok(); - app.ui.brush_options = Some(host::open_held(app, dialog, ok).ok_or("no window")?); + app.ui.brush_options = Some( + host::open_held(app, dialog, move |app, result: &ParamResult| { + if !object && app.session.active().is_none_or(|st| st.uid != document) { + return Err(tl!("Return to the original drawing to edit its brush").into()); + } + ok(app, result) + }) + .ok_or("no window")?, + ); Ok(Value::Null) } @@ -672,3 +681,27 @@ fn confirm(app: &mut VectorcraftApp, d: &DialogFields) -> Result<(), String> { #[cfg(test)] mod tests; + +#[cfg(test)] +mod document_tests { + use super::*; + use crate::dialogs::tests_export; + + #[test] + fn brush_options_does_not_rename_the_other_drawings_brush() { + let (mut app, _) = tests_export::app(1); + open(&mut app, Some("Diamonds")).unwrap(); + tests_export::set(&mut app, "name", json!("Source diamonds")); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let previous = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + let error = tests_export::try_confirm(&mut app).expect_err("Brush Options must refuse the other drawing"); + assert!(error.contains("original drawing"), "{error}"); + assert_eq!(app.run("brush.get", json!({"name": "Diamonds"})).unwrap(), previous); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(tests_export::fields(&app)["name"], "Source diamonds"); + app.run("document.activate", json!({"index": 0})).unwrap(); + tests_export::try_confirm(&mut app).unwrap(); + assert_eq!(app.run("brush.get", json!({"name": "Source diamonds"})).unwrap()["name"], "Source diamonds"); + } +} diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index c82918426b..76a5e62ad0 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -51,6 +51,8 @@ const GLOBAL: &str = "global"; pub(crate) struct Open { /// The dialog's id on the host. pub id: DialogId, + /// The document whose art the dialog can adjust. + document: Option, /// The preview the dialog's values run as one interaction. pub preview: LivePreview, } @@ -85,22 +87,28 @@ impl Adjust { fn try_open(self, app: &mut VectorcraftApp) -> Result<(), String> { const NO_WINDOW: &str = "no window to open the dialog in"; let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?; - if let Some(old) = (self.slot)(&mut app.color_dialogs).take() { + let document = app.session.active().map(|st| st.uid); + if let Some(old) = (self.slot)(&mut app.color_dialogs).take() + && old.document == document + { old.preview.cancel(app); } let dialog = HostedParamDialog::new(&ctx, self.kind, (self.initial)(), move |fields| { ParamDialog::new(self.kind, self.label, (self.rows)()).values(Bind::bound(fields)).previews(true) }); let id = host::open_held(app, dialog, move |app, answer| self.commit(app, answer)).ok_or(NO_WINDOW)?; - *(self.slot)(&mut app.color_dialogs) = Some(Open { id, preview: LivePreview::default() }); + *(self.slot)(&mut app.color_dialogs) = Some(Open { id, document, preview: LivePreview::default() }); Ok(()) } /// OK: keeps the preview as one undo step; an `Err` keeps the dialog open with the reason. fn commit(self, app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { - let live = (self.slot)(&mut app.color_dialogs).as_ref().map(|open| open.preview.clone()).unwrap_or_default(); - // PLAN: assumed `LivePreview::commit(self, ..)` as the contract row says; the clone keeps the record when it fails. - live.commit(app, self.cmd, (self.params)(&answer.fields))?; + let document = app.session.active().map(|st| st.uid); + let open = (self.slot)(&mut app.color_dialogs) + .as_ref() + .filter(|open| open.document == document) + .ok_or(tl!("This adjustment can only apply to the document where it was opened."))?; + open.preview.clone().commit(app, self.cmd, (self.params)(&answer.fields))?; *(self.slot)(&mut app.color_dialogs) = None; Ok(()) } @@ -108,17 +116,22 @@ impl Adjust { /// Once per frame: previews the dialog's values while its Preview box is on, and rolls the preview back once the /// dialog is gone without OK. pub(super) fn pump(self, app: &mut VectorcraftApp) { - let Some(Open { id, mut preview }) = (self.slot)(&mut app.color_dialogs).take() else { return }; + let Some(mut open) = (self.slot)(&mut app.color_dialogs).take() else { return }; + let on_its_document = app.session.active().map(|st| st.uid) == open.document; let shown = app.dialogs().and_then(|dialogs| { - dialogs.with(|host| host.get_mut_by_id::(id).map(|dialog| (dialog.is_previewing(), (self.params)(dialog.fields())))) + dialogs.with(|host| host.get_by_id::(open.id).map(|dialog| (dialog.is_previewing(), (self.params)(dialog.fields())))) }); - match shown { - Some((on, params)) => { + if let Some((on, params)) = shown { + if on_its_document { // `run` reports a failed preview to the status line itself. - let _ = preview.run(app, on, self.label, self.cmd, ¶ms); - *(self.slot)(&mut app.color_dialogs) = Some(Open { id, preview }); + let _ = open.preview.run(app, on, self.label, self.cmd, ¶ms); + } else { + // Switching documents rolled back the original interaction. + open.preview = LivePreview::default(); } - None => preview.cancel(app), + *(self.slot)(&mut app.color_dialogs) = Some(open); + } else if on_its_document { + open.preview.cancel(app); } } } @@ -222,7 +235,7 @@ fn rows() -> Vec { #[cfg(test)] mod tests { - use craft::ui::dialog::dialog_id; + use craft::ui::dialog::{HeldOk, dialog_id}; use vectorcraft_engine::Session; use super::*; @@ -250,6 +263,92 @@ mod tests { host::pump(app, ctx); } + fn two_documents(color: &str) -> (VectorcraftApp, egui::Context, [u64; 2]) { + let (mut app, ctx) = app(); + let ids = [0, 1].map(|_| { + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"color": color})).unwrap(); + id + }); + app.run("document.activate", json!({"index": 0})).unwrap(); + (app, ctx, ids) + } + + #[test] + fn color_adjustment_stays_in_its_opening_document_with_preview_on() { + let (mut app, ctx, [source, destination]) = two_documents("#808080"); + let id = dialog_id(KIND); + let dialogs = app.dialogs().unwrap(); + let source_undo = app.session.active().unwrap().history.undo.len(); + open(&mut app); + set(&app, &ctx, "r", json!(20)); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, source), "#b38080"); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, destination), "#808080", "another document is not previewed"); + assert!(!app.session.in_interaction()); + confirm(&mut app, &ctx); + assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + app.run("document.activate", json!({"index": 0})).unwrap(); + confirm(&mut app, &ctx); + assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Accepted))); + assert_eq!(fill_hex(&app, source), "#b38080"); + assert_eq!(app.session.active().unwrap().history.undo.len(), source_undo + 1); + } + + #[test] + fn color_adjustment_stays_in_its_opening_document_with_preview_off() { + let (mut app, ctx, [source, destination]) = two_documents("#cc6666"); + let id = dialog_id(crate::dialogs::saturate::KIND); + let dialogs = app.dialogs().unwrap(); + crate::dialogs::saturate::open(&mut app); + dialogs.with(|host| { + host.set_json_field(&ctx, id, "intensity", json!(-100)).unwrap(); + host.set_json_field(&ctx, id, "preview", json!(false)).unwrap(); + }); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, source), "#cc6666"); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, destination), "#cc6666", "another document is not adjusted"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + host::pump(&mut app, &ctx); + assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Accepted))); + assert_ne!(fill_hex(&app, source), "#cc6666"); + } + + #[test] + fn color_adjustment_cancel_leaves_the_new_documents_interaction_intact() { + let (mut app, ctx, [source, destination]) = two_documents("#808080"); + let id = dialog_id(KIND); + let dialogs = app.dialogs().unwrap(); + open(&mut app); + set(&app, &ctx, "r", json!(20)); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, source), "#b38080"); + + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Change fill").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + dialogs.with(|host| host.cancel_by_id(&ctx, id)); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, destination), "#00ff00", "cancelling the old dialog leaves the new edit intact"); + assert!(app.session.in_interaction()); + } + #[test] fn previews_live_and_commits_one_undo_step() { let (mut app, ctx) = app(); diff --git a/crates/ui-egui/src/dialogs/composite_fonts.rs b/crates/ui-egui/src/dialogs/composite_fonts.rs index 8580b7085a..0142a0070f 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts.rs @@ -60,7 +60,7 @@ use vectorcraft_engine::cmd::compositefonts::{EXTS, file_bytes}; use vectorcraft_text::FontDb; use crate::VectorcraftApp; -use crate::file_asks::{Owner, ask, open_params, save}; +use crate::file_asks::{Owner, ask_while, open_params, save}; use crate::font_menu::{PickerHold, family_picker, family_sets}; mod sample; @@ -156,6 +156,8 @@ pub struct CompositeFontsDialog { held: HeldAnswer>, /// The file dialog a Load…, Replace… or Save… asked for, which [`pump`] takes. file: Option, + /// Identifies the draft that opened a Load or Replace picker. + file_owner: Arc<()>, /// Why the last action on the fonts or sets was refused. refusal: Option, /// The words of the file status line, kept from the last pass for [`pump`]. @@ -255,6 +257,7 @@ impl CompositeFontsDialog { hold, held: HeldAnswer::new(), file: None, + file_owner: Arc::new(()), refusal: None, words: None, } @@ -848,25 +851,32 @@ impl StackDialog for CompositeFontsDialog { /// Runs once per frame after the shell pass: answers OK's held fonts with the command's result, and takes the /// file dialog a Load…, Replace… or Save… asked for. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { - let Some((held, request)) = with_dialog(app, |d| (d.held.take(), d.file.take())) else { return }; + let Some((held, request)) = with_dialog(app, |d| { + let held = d.held.take(); + let request = d.file.take().map(|request| (request, Arc::clone(&d.file_owner))); + (held, request) + }) else { + return; + }; if let Some(fonts) = held { // A name two fonts share or a value out of range keeps the dialog open with the reason. let answer = app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from); with_dialog(app, |d| d.held.answer(answer)); } - if let Some(request) = request { - ask_file(app, request); + if let Some((request, owner)) = request { + ask_file(app, request, owner); } } -/// Asks for the file `request` names; the answer reaches the dialog by [`with_dialog`]. -fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest) { +/// Asks for the file `request` names. Open answers belong to the draft that requested them. +fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest, owner: Arc<()>) { // The pick's answer comes back through the continuation, so the immediate `{pending}` value says nothing more. match request.clone() { PresetFileRequest::Open { purpose, filter, extensions, replace, .. } => { let exts: Vec<&str> = extensions.iter().map(String::as_str).collect(); let pick = PickRequest::open(purpose).filter(filter, &exts); - ask(app, pick, Owner::Free, move |app, picked| load_file(app, &request, replace, &picked)); + let current = move |app: &VectorcraftApp| with_dialog(app, |draft| Arc::ptr_eq(&draft.file_owner, &owner)).unwrap_or(false); + ask_while(app, pick, Owner::Free, current, move |app, picked| load_file(app, &request, replace, &picked)); } PresetFileRequest::Save { purpose, filter, extensions, file_name, bytes, .. } => { let exts: Vec<&str> = extensions.iter().map(String::as_str).collect(); diff --git a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs index cbfd379b71..04af573087 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs @@ -61,6 +61,42 @@ fn names(app: &VectorcraftApp) -> Vec { app.session.active().unwrap().doc.composite_fonts.iter().map(|f| f.name.clone()).collect() } +#[test] +fn delayed_load_and_replace_leave_the_reopened_composite_fonts_draft_alone() { + let choices: [(PresetCommands, &[&str]); 2] = [(PresetCommands::Load, &["New draft", "From file"]), (PresetCommands::Replace, &["From file"])]; + for (command, expected_live) in choices { + let mut app = app(); + let picker = scripted(&mut app); + let ctx = ctx(&app); + open(&mut app).unwrap(); + let bytes = dialog(&mut app, |d| { + d.new_font("From file".into()); + file_bytes(&d.fonts).unwrap() + }); + let dir = vectorcraft_testkit::TempDir::new("composite-fonts-late-picker"); + let file = dir.join("picked.vccomposite"); + std::fs::write(&file, bytes).unwrap(); + let path = file.to_str().unwrap(); + request(&mut app, command, None); + assert_eq!(picker.requests().len(), 1); + cancel(&mut app); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("New draft".into())); + + picker.answer(&[path]); + poll(&mut app, &ctx); + let draft_names = |app: &mut VectorcraftApp| dialog(app, |d| d.fonts.iter().map(|font| font.name.clone()).collect::>()); + assert_eq!(draft_names(&mut app), ["New draft"], "the stale picker leaves the new draft alone"); + + request(&mut app, command, None); + assert_eq!(picker.requests().len(), 2); + picker.answer(&[path]); + poll(&mut app, &ctx); + assert_eq!(draft_names(&mut app), expected_live, "a picker opened by the new draft still works"); + assert!(names(&app).is_empty(), "a picker only edits the draft"); + } +} + fn steps(app: &VectorcraftApp) -> usize { app.session.active().unwrap().history.undo.len() } diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 72fb9a40a6..c6e5a6780f 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -89,6 +89,8 @@ pub(crate) struct Question(StandardPrompt); struct Asked { command: String, params: Value, + /// The document that must still be active for a document-specific confirmation. + document: Option, /// The automation roots in force when asked: the command runs under them. scope: ScopeHandle, /// Automation asked ([`VectorcraftApp::automation_asked`]): the command runs as automation. @@ -129,6 +131,17 @@ pub(crate) struct ReplaceFiles { /// Ask `message` (with an optional `detail` line), both in the UI language; OK runs `command` /// with `params`. pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, params: Value) { + ask_for(app, None, message, detail, command, params); +} + +/// Ask about the active document. OK is valid only while that document is active. +pub(crate) fn ask_in_document(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, params: Value) { + if let Some(document) = app.session.active().map(|st| st.uid) { + ask_for(app, Some(document), message, detail, command, params); + } +} + +fn ask_for(app: &mut VectorcraftApp, document: Option, message: &str, detail: &str, command: &str, params: Value) { let Some(dialogs) = app.dialogs() else { app.status(format!("{message} (no window to ask in)")); return; @@ -137,7 +150,7 @@ pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, if !detail.is_empty() { prompt = prompt.paragraph(detail.to_string()); } - let asked = Asked { command: command.to_string(), params, scope: ScopeHandle::capture(), automated: app.automation_asked() }; + let asked = Asked { command: command.to_string(), params, document, scope: ScopeHandle::capture(), automated: app.automation_asked() }; let prompt = prompt.button(PromptChoice::Proceed, tl!("OK")).button(PromptChoice::Cancel, tl!("Cancel")).tag(asked); dialogs.with(|host| host.open(Question(prompt))); } @@ -263,10 +276,13 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { }; if let Some(DialogResult::Ok(mut answer)) = dialogs.with(|host| host.take::()) && answer.choice == PromptChoice::Proceed - && let Some(Asked { command, params, scope, automated }) = answer.take_tag::() - && let Err(e) = scope.run(|| crate::file_asks::as_automated(app, automated, |app| app.run(&command, params))) + && let Some(Asked { command, params, document, scope, automated }) = answer.take_tag::() { - app.status(e); + if document.is_some_and(|document| app.session.active().is_none_or(|st| st.uid != document)) { + app.status(tl!("This dialog was opened in a different document.")); + } else if let Err(e) = scope.run(|| crate::file_asks::as_automated(app, automated, |app| app.run(&command, params))) { + app.status(e); + } } // The host opens queued messages in `enqueue` order, so the one closed is the oldest. while dialogs.with(|host| host.take::()).is_some() { diff --git a/crates/ui-egui/src/dialogs/custom_dictionary.rs b/crates/ui-egui/src/dialogs/custom_dictionary.rs index d06fa4640a..5333ad7a35 100644 --- a/crates/ui-egui/src/dialogs/custom_dictionary.rs +++ b/crates/ui-egui/src/dialogs/custom_dictionary.rs @@ -41,6 +41,12 @@ fn state_id() -> egui::Id { egui::Id::unique("custom-dictionary-words") } +#[derive(Clone)] +struct Draft { + original: Vec, + words: Vec, +} + /// The custom dictionary's words. fn dictionary(app: &mut VectorcraftApp) -> Result, String> { let words = app.run(COMMAND, json!({})).map_err(|e| e.to_string())?; @@ -65,7 +71,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { ]; let dialog = HostedListManager::new(COMMAND, tl!("Edit Custom Dictionary"), tl!("Entry:"), actions).entries(entries(&words)).renames(WORD); dialogs.with(|host| host.open(dialog)); - ctx.data_mut(|data| data.insert_temp(state_id(), words)); + ctx.data_mut(|data| data.insert_temp(state_id(), Draft { original: words.clone(), words })); Ok(Value::Null) } @@ -79,7 +85,8 @@ fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, choice: &ListManagerChoi if choice.action == DONE { return save(app, ctx); } - let Some(mut words) = ctx.data(|data| data.get_temp::>(state_id())) else { return }; + let Some(mut draft) = ctx.data(|data| data.get_temp::(state_id())) else { return }; + let words = &mut draft.words; match (choice.action.as_str(), choice.entry.as_deref()) { (ADD, _) => match custom_word(&choice.name) { Some(word) => words.push(word), @@ -100,24 +107,20 @@ fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, choice: &ListManagerChoi if let Some(dialogs) = app.dialogs() { dialogs.with(|host| { if let Some(list) = host.get_dyn_mut(id()).and_then(|d| d.downcast_mut::()) { - list.set_entries(entries(&words)); + list.set_entries(entries(words)); } }); } - ctx.data_mut(|data| data.insert_temp(state_id(), words)); + ctx.data_mut(|data| data.insert_temp(state_id(), draft)); } /// Done: deletes the words no longer in the list and adds the new ones in one /// `text.spelling.editDictionary`, saved once. When it can't be saved, none of it is kept: the /// dialog stays open with the error, its list as edited, and Cancel leaves the dictionary as it was. fn save(app: &mut VectorcraftApp, ctx: &egui::Context) { - let Some(words) = ctx.data(|data| data.get_temp::>(state_id())) else { return }; - let orig = match dictionary(app) { - Ok(orig) => orig, - Err(e) => return app.status(e), - }; - let remove: Vec<&String> = orig.iter().filter(|w| !words.contains(w)).collect(); - let add: Vec<&String> = words.iter().filter(|w| !orig.contains(w)).collect(); + let Some(Draft { original, words }) = ctx.data(|data| data.get_temp::(state_id())) else { return }; + let remove: Vec<&String> = original.iter().filter(|w| words.binary_search(w).is_err()).collect(); + let add: Vec<&String> = words.iter().filter(|w| original.binary_search(w).is_err()).collect(); match app.run(EDIT, json!({ "remove": remove, "add": add })) { Ok(_) => { if let Some(dialogs) = app.dialogs() { @@ -136,8 +139,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { if let Some(choice) = dialogs.with(|host| host.get_mut_by_id::(id()).and_then(HostedListManager::take_choice)) { apply(app, ctx, &choice); } - if dialogs.with(|host| host.take_by_id::(id())).is_some() { - ctx.data_mut(|data| data.remove::>(state_id())); + if dialogs.with(|host| host.take_by_id::(id()).is_some() && host.get_by_id::(id()).is_none()) { + ctx.data_mut(|data| data.remove::(state_id())); } } @@ -190,7 +193,7 @@ mod tests { /// The dialog's list, of `mine` (other tests may have their words in the dictionary meanwhile). fn words(app: &VectorcraftApp, mine: &[&str]) -> Vec { let ctx = app.ui_ctx.clone().expect("a window"); - let all = ctx.data(|data| data.get_temp::>(super::state_id())).unwrap_or_default(); + let all = ctx.data(|data| data.get_temp::(super::state_id())).map(|draft| draft.words).unwrap_or_default(); all.into_iter().filter(|w| mine.contains(&w.as_str())).collect() } @@ -235,6 +238,31 @@ mod tests { forget(&mut app, &[A, B, C]); } + #[test] + fn done_preserves_dictionary_changes_made_after_opening() { + let _dictionary = crate::testing::custom_dictionary(); + const KEPT: &str = "zqvdictoutsideadd"; + const REMOVED: &str = "zqvdictoutsideremove"; + let mut app = app(); + forget(&mut app, &[A, B, KEPT, REMOVED]); + for word in [A, REMOVED] { + app.run("text.spelling.addWord", json!({"word": word})).unwrap(); + } + let mut p = Panel::new(app, draw); + super::open(&mut p.app()).unwrap(); + p.app().run("text.spelling.addWord", json!({"word": KEPT})).unwrap(); + p.app().run("text.spelling.removeWord", json!({"word": REMOVED})).unwrap(); + p.click(A); + p.click("Delete"); + enter(&mut p, B); + p.click("Add"); + p.click("Done"); + let mut app = p.app(); + let final_words = [A, B, KEPT, REMOVED].map(|word| has(&mut app, word)); + forget(&mut app, &[A, B, KEPT, REMOVED]); + assert_eq!(final_words, [false, true, true, false]); + } + /// Done that can't be saved keeps none of the edits: the dialog stays open and Cancel leaves the /// dictionary as it was. #[test] diff --git a/crates/ui-egui/src/dialogs/envelope.rs b/crates/ui-egui/src/dialogs/envelope.rs index 0feb189b8e..a7079a2021 100644 --- a/crates/ui-egui/src/dialogs/envelope.rs +++ b/crates/ui-egui/src/dialogs/envelope.rs @@ -61,6 +61,8 @@ pub(crate) struct Open { pub id: DialogId, /// Which of the three dialogs it is. pub kind: &'static str, + /// The drawing that supplied the selection and defaults at opening. + document: Option, /// The envelope the dialog previews. pub preview: LivePreview, // PLAN: ef.C11's `Open` has no `generation`; the same kind reopened has the same id, so the id cannot tell the held Cancel of the replaced dialog from the new one's. @@ -68,6 +70,18 @@ pub(crate) struct Open { pub generation: u64, } +impl Open { + fn on_original_drawing(&self, app: &VectorcraftApp) -> bool { + app.session.active().map(|st| st.uid) == self.document + } + + fn cancel_preview(self, app: &mut VectorcraftApp) { + if self.on_original_drawing(app) { + self.preview.cancel(app); + } + } +} + /// The dialog's title. fn heading(kind: &str, reset: bool) -> Label { Label::from( @@ -172,10 +186,12 @@ pub fn open(app: &mut VectorcraftApp, id: &str) -> Result { /// Options dialog sets the defaults for new envelopes and has nothing to preview. fn open_dialog(app: &mut VectorcraftApp, kind: &'static str, values: Map, envelope: bool) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; + let document = app.session.active().map(|st| st.uid); if let Some(previous) = app.effect_dialogs.envelope.take() { - previous.preview.cancel(app); + let id = previous.id; + previous.cancel_preview(app); if let Some(dialogs) = app.dialogs() { - dialogs.with(|host| host.cancel_by_id(&ctx, previous.id)); + dialogs.with(|host| host.cancel_by_id(&ctx, id)); } } let fields = fields_of(¶ms(kind, &DialogFields::new()), &values); @@ -188,28 +204,32 @@ fn open_dialog(app: &mut VectorcraftApp, kind: &'static str, values: Map Result<(), String> { - let (cmd, p, _) = command(kind, &json_of(¶ms(kind, &result.fields), &result.fields)); - let Some(Open { id, generation, preview, .. }) = app.effect_dialogs.envelope.take() else { +fn accept(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> { + let Some(open) = app.effect_dialogs.envelope.as_ref().filter(|open| open.id == result.id) else { return Err("the envelope dialog is gone".into()); }; + if !open.on_original_drawing(app) { + return Err(tl!("Return to the original drawing to apply the envelope").into()); + } + let kind = open.kind; + let (cmd, p, _) = command(kind, &json_of(¶ms(kind, &result.fields), &result.fields)); + let Open { id, document, preview, generation, .. } = app.effect_dialogs.envelope.take().ok_or("the envelope dialog is gone")?; match preview.commit(app, cmd, p) { Ok(_) => Ok(()), Err(e) => { // The attempt ended the preview; the next pass starts a new one over the same values. Nothing to undo // when no interaction was open, so the answer is not needed. let _ = app.session.cancel_interaction(); - app.effect_dialogs.envelope = Some(Open { id, kind, preview: LivePreview::default(), generation }); + app.effect_dialogs.envelope = Some(Open { id, kind, document, preview: LivePreview::default(), generation }); Err(e) } } @@ -252,6 +272,10 @@ fn command(kind: &str, f: &Map) -> (&'static str, Value, &'static /// canvas shows them. The dialog's Cancel rolls the preview back through the held record's cancel. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut open) = app.effect_dialogs.envelope.take() else { return }; + if !open.on_original_drawing(app) { + app.effect_dialogs.envelope = Some(open); + return; + } let shown = app .dialogs() .and_then(|dialogs| dialogs.with(|host| host.get_mut_by_id::(open.id).map(|d| (d.is_previewing(), d.fields().clone())))); @@ -465,6 +489,49 @@ mod tests { ); } + #[test] + fn envelope_warp_refuses_preview_and_ok_in_the_other_drawing() { + let (mut app, _) = app_with_rect(); + open(&mut app, MAKE_WARP).unwrap(); + let id = dialog(&app); + set(&app, id, "bend", json!(23)); + pump(&mut app); + app.run("file.new", json!({"width": 300, "height": 150})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + set(&app, id, "bend", json!(31)); + pump(&mut app); + assert!(matches!(envelope(&app).1.kind, NodeKind::Path { .. }), "the other drawing keeps the rectangle"); + let ctx = app.ui_ctx.clone().unwrap(); + host(&app, |h| h.confirm_by_id(&ctx, id)); + pump(&mut app); + assert!( + matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(reason)) if reason.as_str().contains("original drawing")) + ); + assert_eq!(json_fields(&app, id)["bend"], 31.0); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + app.run("document.activate", json!({"index": 0})).unwrap(); + accept(&mut app, id); + let (_, node) = envelope(&app); + assert!(matches!(node.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Warp { bend: 31.0, .. }))); + } + + #[test] + fn cancelling_an_envelope_dialog_keeps_the_other_drawings_active_edit() { + let (mut app, _) = app_with_rect(); + open(&mut app, MAKE_WARP).unwrap(); + let id = dialog(&app); + pump(&mut app); + app.run("file.new", json!({"width": 300, "height": 150})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + dismiss(&mut app, id); + assert!(app.session.in_interaction(), "the other drawing's edit stays active"); + } + #[test] fn reset_items_take_the_make_items_place_while_an_envelope_is_selected() { let labels = |app: &VectorcraftApp| -> Vec { diff --git a/crates/ui-egui/src/dialogs/expand.rs b/crates/ui-egui/src/dialogs/expand.rs index f63e3e1641..0f61119fc8 100644 --- a/crates/ui-egui/src/dialogs/expand.rs +++ b/crates/ui-egui/src/dialogs/expand.rs @@ -154,7 +154,14 @@ fn dialog(app: &VectorcraftApp, info: ExpandInfo) -> Result Result { - crate::dialogs::host::open_held(app, dialog, ok).ok_or("no window")?; + let document = app.session.active().ok_or("no document open")?.uid; + crate::dialogs::host::open_held(app, dialog, move |app, result: &ParamResult| { + if app.session.active().is_none_or(|st| st.uid != document) { + return Err(tl!("Return to the original drawing to expand the artwork").into()); + } + ok(app, result) + }) + .ok_or("no window")?; Ok(Value::Null) } @@ -285,6 +292,24 @@ mod tests { assert!(matches!(children[1].kind, NodeKind::Mesh(_))); } + #[test] + fn expand_keeps_its_draft_when_another_drawing_is_active() { + let mut app = app(); + gradient_rectangle(&mut app); + open(&mut app).unwrap(); + set(&app, "gradient", json!("mesh")).unwrap(); + gradient_rectangle(&mut app); + let undo = app.session.active().unwrap().history.undo.len(); + let before = app.session.active().unwrap().doc.clone(); + assert!(matches!(press_ok(&mut app), Some(HeldOk::Refused(reason)) if reason.as_str().contains("original drawing"))); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &before)); + assert_eq!(fields(&app).text("gradient"), Some("mesh")); + app.run("document.activate", json!({"index": 0})).unwrap(); + ok_and_close(&mut app); + assert!(expanded_to_a_mesh(&app)); + } + #[test] fn expand_gradient_to_is_disabled_for_a_pattern_fill_alone() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index fffa334f21..80439178a8 100644 --- a/crates/ui-egui/src/dialogs/file_info.rs +++ b/crates/ui-egui/src/dialogs/file_info.rs @@ -13,7 +13,7 @@ use std::path::PathBuf; use craft::behavior::IconId; -use craft::host::{Host, PickId, PickKind, PickRequest}; +use craft::host::{Host, PickId, PickKind, PickRequest, Picked}; use craft::theme::variant::Tone; use craft::ui::buttons::{Button, IconButton}; use craft::ui::choice::{Radio, RadioGroup, Rating}; @@ -111,6 +111,8 @@ enum Request { Folder, /// Save the fields as a template at the path the save pick answered. SaveTo(PathBuf), + /// A browser picker returned a template larger than the import limit. + TemplateTooLarge, /// Merge the template `source` into the fields as `mode` says. Import { source: Info, mode: &'static str }, } @@ -151,6 +153,15 @@ impl Templates { && let Some(answer) = cx.take_pick_answer(id) { self.ticket = None; + if let (Pick::Open, Picked::Contents(files)) = (kind, &answer) { + let Some((_, bytes)) = files.first() else { return }; + if bytes.len() > vectorcraft_pdf::MAX_TEMPLATE_BYTES { + self.requests.push(Request::TemplateTooLarge); + } else { + *import = Some(source("dataBase64", vectorcraft_format::base64_encode(bytes))); + } + return; + } let Some(path) = answer.first_path() else { return }; match kind { Pick::Open => *import = Some(source("path", path.to_string_lossy().into_owned())), @@ -602,6 +613,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { Some(fields) => save_template(app, path, fields), None => Ok(()), }, + Request::TemplateTooLarge => Err(tl!("The metadata template is larger than 8 MB.").to_owned()), Request::Import { source, mode } => { dialogs.with(|host| host.get_mut_by_id::(id).map(|d| import(app, d, source, mode))).unwrap_or(Ok(())) } @@ -767,6 +779,54 @@ mod tests { assert_eq!(st.history.undo.len(), 1); } + #[test] + fn browser_picked_templates_enter_the_merge_choice_and_edit_only_the_draft() { + use std::sync::Arc; + + use craft::host::{Files, PickRequest, Picked, ScriptedFiles}; + + let template = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { + description: Some("À l’affiche 版".into()), + rating: Some(3), + ..Default::default() + }); + let utf16 = std::iter::once(0xfeff).chain(template.encode_utf16()).flat_map(u16::to_le_bytes).collect::>(); + for bytes in [template.into_bytes(), utf16] { + let mut app = windowed(); + let files = Arc::new(ScriptedFiles::held()); + crate::tests::picks::install_files(&mut app, files.clone()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "author", json!("Ada")).unwrap(); + let ticket = files.pick(PickRequest::open(super::PURPOSE)); + with_dialog(&app, |d| d.templates.ticket = Some((ticket, super::Pick::Open))).unwrap(); + assert!(files.answer(Picked::Contents(vec![("Studio.xmp".into(), bytes)])).is_some()); + let ctx = app.ui_ctx.clone().unwrap(); + for _ in 0..3 { + crate::tests::synthetic::key_frame(&mut app, &ctx, Vec::new()); + } + with_dialog(&app, |d| { + assert!(d.templates.ticket.is_none(), "the File Info form consumed the picker answer"); + assert!(d.import.is_some(), "a browser-selected template reaches the merge choice"); + assert!(super::choose_mode(&mut d.import_mode, "append")); + super::ask_import(&mut d.templates, &d.import, d.import_mode); + }) + .unwrap(); + + super::pump(&mut app, &ctx); + let fields = with_dialog(&app, |d| d.filed_fields()).unwrap(); + assert_eq!( + (fields["author"].clone(), fields["description"].clone(), fields["rating"].clone()), + (json!("Ada"), json!("À l’affiche 版"), json!(3)) + ); + assert_eq!(app.session.active().unwrap().history.undo.len(), 0, "the template updates the draft before OK"); + assert!(press_ok(&mut app)); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.metadata.description, "À l’affiche 版"); + assert_eq!(st.history.undo.len(), 1); + } + } + #[test] fn ok_waits_for_the_merge_choice_of_a_template_being_imported() { let mut app = windowed(); diff --git a/crates/ui-egui/src/dialogs/find_links.rs b/crates/ui-egui/src/dialogs/find_links.rs index 7324d27184..5fd1426068 100644 --- a/crates/ui-egui/src/dialogs/find_links.rs +++ b/crates/ui-egui/src/dialogs/find_links.rs @@ -311,10 +311,11 @@ pub(super) fn from_missing_links( folder: &str, ) -> Result<(), String> { let mut find = dialog(app, missing.clone(), modified.clone(), true)?; + let document = find["document"].as_u64().ok_or("no document open")?; find.insert("notes".into(), json!(notes)); start_search(app, &mut find, folder)?; open(app, find)?; - app.link_asks = Some(LinkAsk { missing, modified, notes, back: true }); + app.link_asks = Some(LinkAsk { document, missing, modified, notes, back: true }); Ok(()) } diff --git a/crates/ui-egui/src/dialogs/flare_options.rs b/crates/ui-egui/src/dialogs/flare_options.rs index 6b1d6770cd..d479b57368 100644 --- a/crates/ui-egui/src/dialogs/flare_options.rs +++ b/crates/ui-egui/src/dialogs/flare_options.rs @@ -16,6 +16,8 @@ //! (`ObjectDialogs::flare`), not fields. // PLAN: the `craft_ui` paths and `LivePreview`'s home (`form`) are assumed; `general_lengths` is cv.B5b's. +use std::sync::Arc; + use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{HostedParamDialog, Param, ParamDialog, ParamResult}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; @@ -39,6 +41,8 @@ pub const KIND: &str = "flareOptions"; pub(crate) struct Open { /// The hosted dialog. id: DialogId, + opening: Arc<()>, + document: Option, /// Where a click opened it, to draw a flare there on OK. click: Option, /// The selected flares (ids) and the settings the dialog opened with, to change them on OK. @@ -47,6 +51,27 @@ pub(crate) struct Open { preview: Option, } +const PREVIEW_LABEL: &str = "Flare"; + +impl Open { + fn on_original_drawing(&self, app: &VectorcraftApp) -> bool { + self.preview.is_none() || app.session.active().map(|st| st.uid) == self.document + } + + fn cancel_preview(self, app: &mut VectorcraftApp) { + if self.on_original_drawing(app) + && !other_preview(app) + && let Some(preview) = self.preview + { + preview.cancel(app); + } + } +} + +fn other_preview(app: &VectorcraftApp) -> bool { + app.session.active().and_then(|st| st.interaction.as_ref()).is_some_and(|p| p.label != PREVIEW_LABEL) +} + /// Open the Flare Tool Options with the tool's values; `at`: where a click opened them, to draw a /// flare there on OK. Opened without a click while flares are selected, they show the first one's /// settings, to change the selected flares on OK. @@ -91,24 +116,25 @@ pub fn open(app: &mut VectorcraftApp, at: Option) -> Value { return Value::Null; }; // An open the host replaces leaves its preview behind unless it is rolled back here. - if let Some(old) = app.object_dialogs.flare.take() - && let Some(preview) = old.preview - { - preview.cancel(app); + if let Some(old) = app.object_dialogs.flare.take() { + old.cancel_preview(app); } - let cancel: Box = Box::new(|app| { - if let Some(open) = app.object_dialogs.flare.take() - && let Some(preview) = open.preview + let opening = Arc::new(()); + let cancelled = Arc::clone(&opening); + let cancel: Box = Box::new(move |app| { + if app.object_dialogs.flare.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled)) + && let Some(open) = app.object_dialogs.flare.take() { - preview.cancel(app); + open.cancel_preview(app); } }); let held = HeldOptions { parent: None, cancel: Some(cancel) }; let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { ParamDialog::new(KIND, tl!("Flare Tool Options"), params(lengths)).values(Bind::bound(fields)).previews(previews).reset_to(defaults.clone()) }); + let document = app.session.active().map(|st| st.uid); match open_held_with(app, dialog, ok, held) { - Some(id) => app.object_dialogs.flare = Some(Open { id, click: at, edit, preview: previews.then(LivePreview::default) }), + Some(id) => app.object_dialogs.flare = Some(Open { id, opening, document, click: at, edit, preview: previews.then(LivePreview::default) }), None => app.status("no window"), } json!({ "dialog": KIND }) @@ -242,15 +268,27 @@ fn option_values(fields: &Map) -> Map { pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { // PLAN: registered in hub-w2's pump file (wg.A18), one line. let Some(mut open) = app.object_dialogs.flare.take() else { return }; + if !open.on_original_drawing(app) { + app.object_dialogs.flare = Some(open); + return; + } if let Some(mut preview) = open.preview.take() { let state = app .dialogs() .and_then(|host| host.with(|host| host.get_by_id::(open.id).map(|d| (d.is_previewing(), d.fields().clone())))); if let Some((previewing, fields)) = state { let values = form::json_of(¶ms(general_lengths(app)), &fields); - if let Some((cmd, params)) = command(app, &open, &values) { + if previewing + && other_preview(app) + && let Err(e) = app.keep_typing() + { + app.status(e); + } + if !other_preview(app) + && let Some((cmd, params)) = command(app, &open, &values) + { // The preview reports its own failures on the status line. - let _ = preview.run(app, previewing, "Flare", &cmd, ¶ms); + let _ = preview.run(app, previewing, PREVIEW_LABEL, &cmd, ¶ms); } } open.preview = Some(preview); @@ -261,6 +299,16 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// OK: set the tool's options; opened by a click, draw a flare there with them. Opened for the /// selected flares, draw them again with the settings changed, leaving the tool's options. fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> { + let open = app.object_dialogs.flare.as_ref().ok_or("the Flare Tool Options dialog is gone")?; + if !open.on_original_drawing(app) { + return Err(tl!("Return to the original drawing to place or edit the flare").into()); + } + if open.preview.is_some() && other_preview(app) { + app.keep_typing()?; + if other_preview(app) { + return Err(tl!("Finish the current edit before drawing the flare").into()); + } + } let fields = form::json_of(¶ms(general_lengths(app)), &result.fields); let accepted = accept(app, &fields); if accepted.is_ok() { @@ -430,6 +478,23 @@ mod tests { assert_eq!(parts.iter().filter(|p| *p == "Ring").count(), 3, "{parts:?}"); } + #[test] + fn a_pending_flare_click_waits_for_its_original_drawing() { + let mut app = app(); + open(&mut app, Some(Point::new(100.0, 110.0))); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers[0].children().unwrap().len(); + pump(&mut app); + assert_eq!(count(&app), 0, "the other drawing never shows the flare preview"); + press_ok(&mut app); + assert_eq!(count(&app), 0, "the other drawing never keeps the flare"); + assert!(app.object_dialogs.flare.is_some()); + app.run("document.activate", json!({"index": 0})).unwrap(); + press_ok(&mut app); + assert_eq!(count(&app), 1); + assert!(!flare_parts(&app).is_empty()); + } + /// With a flare selected, the toolbar's Flare Tool Options show its settings, and OK draws it /// again with the settings changed, as one undo step, leaving the tool's options. #[test] diff --git a/crates/ui-egui/src/dialogs/indexed_color.rs b/crates/ui-egui/src/dialogs/indexed_color.rs index e864caed06..b823cd2e71 100644 --- a/crates/ui-egui/src/dialogs/indexed_color.rs +++ b/crates/ui-egui/src/dialogs/indexed_color.rs @@ -4,6 +4,8 @@ //! //! Fields: `reduction`, `colors`, `dither`, `ditherAmount` and `preview`. +use std::sync::Arc; + use craft::ui::dialog::dialog_id; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::UnitKind; @@ -21,6 +23,28 @@ const CMD: &str = "edit.colors.toIndexed"; /// The undo step a preview and OK make. const PREVIEW_LABEL: &str = "Convert to Indexed Color"; +pub(crate) struct Open { + document: u64, + opening: Arc<()>, + preview: LivePreview, +} + +impl Open { + fn on_original_drawing(&self, app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|st| st.uid == self.document) + } + + fn cancel_preview(self, app: &mut VectorcraftApp) { + if self.on_original_drawing(app) && !other_preview(app) { + self.preview.cancel(app); + } + } +} + +fn other_preview(app: &VectorcraftApp) -> bool { + app.session.active().and_then(|st| st.interaction.as_ref()).is_some_and(|p| p.label != PREVIEW_LABEL) +} + /// The reductions besides those of a PNG-8 export, as (value, label). const MORE_REDUCTIONS: [(&str, &str); 2] = [("uniform", "Uniform"), ("document", "Document Swatches")]; @@ -62,38 +86,71 @@ pub fn open(app: &mut VectorcraftApp) { app.status("no window".to_string()); return; }; + let Some(document) = app.session.active().map(|st| st.uid) else { + app.status(tl!("Open a drawing to convert its images")); + return; + }; + if let Some(old) = app.object_dialogs.indexed.take() { + old.cancel_preview(app); + } let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::new(), build); - app.object_dialogs.indexed = Some(LivePreview::default()); + let opening = Arc::new(()); + let cancelled = Arc::clone(&opening); let ok = |app: &mut VectorcraftApp, r: &ParamResult| { - let preview = app.object_dialogs.indexed.take().unwrap_or_default(); - let done = preview.commit(app, CMD, params(&r.fields)).map(|_| ()); + let open = app.object_dialogs.indexed.as_ref().ok_or("the Indexed Color dialog is gone")?; + if !open.on_original_drawing(app) { + return Err(tl!("Return to the original drawing to convert its images").into()); + } + if other_preview(app) { + app.keep_typing()?; + if other_preview(app) { + return Err(tl!("Finish the current edit before converting its images").into()); + } + } + let open = app.object_dialogs.indexed.take().ok_or("the Indexed Color dialog is gone")?; + let done = open.preview.commit(app, CMD, params(&r.fields)).map(|_| ()); if done.is_err() { // The dialog stays open and previews again. - app.object_dialogs.indexed = Some(LivePreview::default()); + app.object_dialogs.indexed = Some(Open { preview: LivePreview::default(), ..open }); } done }; - let cancel = Box::new(|app: &mut VectorcraftApp| { - if let Some(preview) = app.object_dialogs.indexed.take() { - preview.cancel(app); + let cancel = Box::new(move |app: &mut VectorcraftApp| { + if app.object_dialogs.indexed.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled)) + && let Some(open) = app.object_dialogs.indexed.take() + { + open.cancel_preview(app); } }); - if open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }).is_none() { - app.object_dialogs.indexed = None; + if open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }).is_some() { + app.object_dialogs.indexed = Some(Open { document, opening, preview: LivePreview::default() }); + } else { app.status("no window".to_string()); } } /// Each frame: show the dialog's values on the canvas while its Preview box is on. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { - let Some(mut preview) = app.object_dialogs.indexed.take() else { return }; + let Some(mut open) = app.object_dialogs.indexed.take() else { return }; + if !open.on_original_drawing(app) { + app.object_dialogs.indexed = Some(open); + return; + } let shown = app .dialogs() .and_then(|h| h.with(|host| host.get_by_id::(dialog_id(KIND)).map(|d| (d.is_previewing(), params(d.fields()))))); if let Some((on, p)) = &shown { - let _ = preview.run(app, *on, PREVIEW_LABEL, CMD, p); + if *on + && other_preview(app) + && let Err(e) = app.keep_typing() + { + app.status(e); + } + if !other_preview(app) { + let _ = open.preview.run(app, *on, PREVIEW_LABEL, CMD, p); + } } - app.object_dialogs.indexed = Some(preview); + app.object_dialogs.indexed = Some(open); } /// Whether reduction `r` takes a number of colors. @@ -125,9 +182,7 @@ mod tests { use super::*; use vectorcraft_engine::Session; - #[test] - fn commits_the_chosen_palette_as_one_step() { - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + fn add_raster(app: &mut VectorcraftApp) -> vectorcraft_doc::NodeId { app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); let img = craft_image_codecs::Image::from_raw( 2, @@ -138,8 +193,7 @@ mod tests { ) .unwrap(); let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); - let id = app - .session + app.session .edit("Place", |d, sel| { d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png)); let id = d.alloc_id(); @@ -156,7 +210,19 @@ mod tests { sel.set([id]); Ok(id) }) - .unwrap(); + .unwrap() + } + + fn palette(app: &VectorcraftApp, id: vectorcraft_doc::NodeId) -> &vectorcraft_doc::ImageBlob { + let st = app.session.doc().unwrap(); + let vectorcraft_doc::NodeKind::Image(im) = &st.doc.node(id).unwrap().kind else { panic!("not an image") }; + &st.doc.images[&im.key] + } + + #[test] + fn commits_the_chosen_palette_as_one_step() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let id = add_raster(&mut app); let undo = app.session.doc().unwrap().history.undo.len(); app.run("ui.indexedColorDialog", json!({})).unwrap(); let ctx = app.ui_ctx.clone().unwrap(); @@ -170,9 +236,33 @@ mod tests { crate::dialogs::host::pump(&mut app, &ctx); let st = app.session.doc().unwrap(); assert_eq!(st.history.undo.len(), undo + 1); - let vectorcraft_doc::NodeKind::Image(im) = &st.doc.node(id).unwrap().kind else { panic!("not an image") }; - let blob = &st.doc.images[&im.key]; + let blob = palette(&app, id); assert!(blob.indexed_png()); assert_eq!(blob.rgba().unwrap().2, [0, 0, 0, 255, 0, 0, 0, 255], "black and white only"); } + + #[test] + fn indexed_color_preview_and_ok_leave_the_other_drawings_pixels_unchanged() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let source = add_raster(&mut app); + open(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + let id = dialog_id(KIND); + host.with(|h| h.set_json_field(&ctx, id, "reduction", json!("blackWhite"))).unwrap(); + let other = add_raster(&mut app); + host.with(|h| h.set_json_field(&ctx, id, "dither", json!("none"))).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(!palette(&app, other).indexed_png(), "the other drawing does not show the preview"); + host.with(|h| h.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(!palette(&app, other).indexed_png(), "the other drawing does not keep the preview"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + app.run("document.activate", json!({"index": 0})).unwrap(); + host.with(|h| h.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(palette(&app, source).indexed_png()); + } } diff --git a/crates/ui-egui/src/dialogs/live_paint_gaps.rs b/crates/ui-egui/src/dialogs/live_paint_gaps.rs index bcbb884bc2..f03b2167e5 100644 --- a/crates/ui-egui/src/dialogs/live_paint_gaps.rs +++ b/crates/ui-egui/src/dialogs/live_paint_gaps.rs @@ -26,6 +26,7 @@ use crate::VectorcraftApp; pub const KIND: &str = "livePaintGapOptions"; const CMD: &str = "livePaint.gapOptions"; +const WRONG_DOCUMENT: &str = "Gap Options can only be applied in the document this dialog was opened for."; /// The undo step the preview and OK make. const PREVIEW_LABEL: &str = "Gap Options"; @@ -51,20 +52,31 @@ pub(super) static SPEC: OptionSpec = OptionSpec { pub(crate) struct Open { /// The dialog the preview belongs to. pub id: DialogId, + /// The document that owns the preview interaction. + document: u64, /// The preview the options run as. pub preview: LivePreview, } +impl Open { + fn cancel(self, app: &mut VectorcraftApp) { + if app.session.active().is_some_and(|active| active.uid == self.document) { + self.preview.cancel(app); + } + } +} + /// Open Gap Options on the selected Live Paint groups, filled in from the first one's options. pub fn open(app: &mut VectorcraftApp) -> Result { - let groups: Vec = app - .session - .doc() - .map(|d| { - let doc = &d.doc; - d.selection.objects.iter().filter(|id| doc.node(**id).is_some_and(vectorcraft_tools::builder::is_live_paint)).map(|id| id.0).collect() - }) - .unwrap_or_default(); + let active = app.session.active().ok_or("select a Live Paint group")?; + let document = active.uid; + let groups: Vec = active + .selection + .objects + .iter() + .filter(|id| active.doc.node(**id).is_some_and(vectorcraft_tools::builder::is_live_paint)) + .map(|id| id.0) + .collect(); let Some(&first) = groups.first() else { return Err("select a Live Paint group".into()) }; let info = app.session.execute("livePaint.info", &json!({ "group": first })).map_err(|e| e.to_string())?; let o = &info["gapOptions"]; @@ -75,10 +87,15 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let fields = [("detect", o["detect"].clone()), ("size", json!(size)), ("custom", custom), ("color", o["color"].clone()), ("closeGaps", json!(false))]; let values = Map::from_iter(fields.map(|(key, value)| (key.to_owned(), value))); - option_form::open(app, &SPEC, values, json!({ "ids": groups })).ok_or("no window")?; + option_form::open(app, &SPEC, values, json!({ "ids": groups, "document": document })).ok_or("no window")?; Ok(Value::Null) } +fn original_document(app: &VectorcraftApp, extra: &Value) -> Option { + let document = extra["document"].as_u64()?; + app.session.active().filter(|active| active.uid == document).map(|_| document) +} + /// `livePaint.gapOptions` parameters from the values and the groups in `extra`. fn params(values: &Map, extra: &Value) -> Value { let size = match values.get("size").and_then(Value::as_str) { @@ -111,24 +128,43 @@ fn body(ui: &mut egui::Ui, rows: &mut Rows<'_>) { /// OK: keep the previewed options as one undo step; with no preview running they run as one. fn run(app: &mut VectorcraftApp, values: &Map, extra: &Value) -> Result { - let preview = app.object_dialogs.gaps.take().map_or_else(LivePreview::default, |open| open.preview); + let document = original_document(app, extra).ok_or_else(|| tl!(WRONG_DOCUMENT).to_owned())?; + let preview = app.object_dialogs.gaps.take().filter(|open| open.document == document).map_or_else(LivePreview::default, |open| open.preview); preview.commit(app, CMD, params(values, extra)) } /// The dialog closed without OK: roll the preview back. fn cancelled(app: &mut VectorcraftApp) { if let Some(open) = app.object_dialogs.gaps.take() { - open.preview.cancel(app); + open.cancel(app); } } /// Runs the open Gap Options' preview as its options stand, once per frame after the shell pass: with Preview on the /// options apply to the groups, off they are rolled back; the gaps a new preview finds are kept for [`overlays`]. /// Nothing runs while an OK waits for its answer, which keeps or refuses the preview that is running. -pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) { +pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let shown = dialogs.with(|host| { - let form = host.get::().filter(|form| form.is(KIND))?; + let form = host.get_mut::().filter(|form| form.is(KIND))?; + let source = form.extra["document"].as_u64()?; + if !app.session.documents().iter().any(|doc| doc.uid == source) { + host.cancel::(ctx); + return None; + } + let document = original_document(app, &form.extra); + let paused = document.is_none(); + if form.preview_paused != paused { + form.preview_paused = paused; + if !paused && form.held.refusal().is_some_and(|(reason, _)| reason.as_str() == tl!(WRONG_DOCUMENT)) { + form.held.clear_refusal(); + } + ctx.request_repaint(); + } + let Some(document) = document else { + form.previewed = Value::Null; + return None; + }; if !form.held.state().is_none_or(|state| matches!(state, HeldOk::Refused(_))) { return None; } @@ -137,17 +173,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) { if form.values.get("color").and_then(Value::as_str).is_some_and(has_alpha) { params["color"] = Value::Null; } - Some((form.id(), params, form.preview)) + Some((form.id(), document, params, form.preview)) }); - let Some((id, params, on)) = shown else { return }; + let Some((id, document, params, on)) = shown else { return }; // A preview of another dialog is rolled back before this one starts its own. let mut open = match app.object_dialogs.gaps.take() { - Some(open) if open.id == id => open, + Some(open) if open.id == id && open.document == document => open, stale => { if let Some(stale) = stale { - stale.preview.cancel(app); + stale.cancel(app); } - Open { id, preview: LivePreview::default() } + Open { id, document, preview: LivePreview::default() } } }; let ran = open.preview.run(app, on, PREVIEW_LABEL, CMD, ¶ms); @@ -177,6 +213,7 @@ pub(crate) fn overlays(app: &VectorcraftApp) -> Vec { let Some(dialogs) = app.dialogs() else { return vec![] }; let shown = dialogs.with(|host| { let form = host.get::().filter(|form| form.is(KIND) && form.preview)?; + original_document(app, &form.extra)?; Some((form.previewed.clone(), form.values.get("color").and_then(Value::as_str)?.to_owned())) }); let Some((gaps, color)) = shown else { return vec![] }; @@ -236,6 +273,71 @@ mod tests { app.run("livePaint.make", json!({})).unwrap()["id"].as_u64().unwrap() } + fn open_with_matching_groups(app: &mut VectorcraftApp) -> u64 { + let group = gapped_group(app); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + assert_eq!(gapped_group(app), group, "the new document reuses the group ID"); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + app.run("ui.livePaintGapOptions", json!({})).unwrap(); + set(app, "detect", json!(true)).unwrap(); + group + } + + #[test] + fn gap_confirmation_stays_with_its_document() { + let mut app = app(); + let group = open_with_matching_groups(&mut app); + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + assert!(!press_ok(&mut app), "the unrelated group cannot take the edit"); + assert_eq!(options(&app, group), GapOptions::default()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + app.run("document.activate", json!({"index": 0})).unwrap(); + pump_all(&mut app); + assert!(held(&app).is_none(), "the stale refusal clears on the original tab"); + assert!(press_ok(&mut app), "the original group's edit can be retried"); + assert!(options(&app, group).detect); + } + + #[test] + fn closing_the_original_document_dismisses_gap_options() { + let mut app = app(); + let group = open_with_matching_groups(&mut app); + app.run("document.activate", json!({"index": 1})).unwrap(); + assert!(app.session.close_document(0)); + pump_all(&mut app); + assert!(!is_open(&app)); + assert_eq!(options(&app, group), GapOptions::default()); + } + + #[test] + fn gap_preview_disappears_in_another_document_and_resumes_on_return() { + let mut app = app(); + let group = open_with_matching_groups(&mut app); + set(&app, "preview", json!(true)).unwrap(); + pump_all(&mut app); + assert!(options(&app, group).detect); + assert!(!overlays(&app).is_empty()); + app.run("document.activate", json!({"index": 1})).unwrap(); + let unrelated_overlays = overlays(&app); + pump_all(&mut app); + let paused = |app: &VectorcraftApp| app.dialogs().unwrap().with(|host| host.get::().unwrap().preview_paused); + assert!(paused(&app)); + assert_eq!(fields(&app)["preview"], json!(true)); + assert_eq!(options(&app, group), GapOptions::default()); + assert!(!app.session.in_interaction()); + assert!(unrelated_overlays.is_empty()); + assert!(overlays(&app).is_empty()); + app.run("document.activate", json!({"index": 0})).unwrap(); + pump_all(&mut app); + assert!(!paused(&app)); + assert!(options(&app, group).detect); + assert!(!overlays(&app).is_empty()); + cancel(&mut app); + assert_eq!(options(&app, group), GapOptions::default()); + } + #[test] fn the_menu_item_opens_gap_options_which_preview_the_gaps_and_ok_keeps_them() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/missing_links.rs b/crates/ui-egui/src/dialogs/missing_links.rs index 662cfa8876..7fe468c4d2 100644 --- a/crates/ui-egui/src/dialogs/missing_links.rs +++ b/crates/ui-egui/src/dialogs/missing_links.rs @@ -105,8 +105,10 @@ impl Asked { /// What the questions about one open's linked files keep between their dialogs: the files still /// asked about, the modified images to offer for update afterwards and the open's notes. -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, PartialEq)] pub(crate) struct LinkAsk { + /// The document that owns the linked-file IDs. + pub(crate) document: u64, /// The missing files still asked about (`[{name, path, ids}]`), the next one first. pub(crate) missing: Vec, /// The ids of the images whose file was modified. @@ -353,7 +355,11 @@ fn questions_for(app: &VectorcraftApp, r: &Value, web: bool) -> (Vec, Ve /// Opens the dialog about the first of `missing`, keeping what the questions after it need /// ([`LinkAsk`]). A window that isn't up has nothing to show a question in. fn open(app: &mut VectorcraftApp, missing: Vec, modified: Vec, notes: &[String]) { - let ask = LinkAsk { missing, modified, notes: notes.to_vec(), back: false }; + let Some(document) = app.session.active().map(|st| st.uid) else { return }; + open_ask(app, LinkAsk { document, missing, modified, notes: notes.to_vec(), back: false }); +} + +fn open_ask(app: &mut VectorcraftApp, ask: LinkAsk) { let Some(dialogs) = app.dialogs() else { return }; let dialog = MissingLinksDialog::new(app, ask.clone()); app.link_asks = Some(ask); @@ -436,9 +442,16 @@ pub(crate) fn changed_on_disk_status(n: usize) -> String { pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let Some(result) = dialogs.with(|h| h.take::()) else { return }; - let ask = app.link_asks.take().unwrap_or_default(); + let Some(ask) = app.link_asks.take() else { return }; let Some(answer) = result.ok() else { return show_notes_again(app, &ask) }; - let LinkAsk { missing, modified, notes, .. } = ask; + if app.session.active().is_none_or(|st| st.uid != ask.document) { + app.status(tl!("This dialog was opened in a different document.")); + if app.session.documents().iter().any(|st| st.uid == ask.document) { + open_ask(app, ask); + } + return; + } + let LinkAsk { document, missing, modified, notes, .. } = ask; let done = match answer { MissingLinksAnswer::FindInFolder(folder) => { super::find_links::from_missing_links(app, missing.clone(), modified.clone(), notes.clone(), &folder).map(|()| None) @@ -450,7 +463,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { Ok(None) => {} Err(e) => { app.status(e); - open(app, missing, modified, ¬es); + open_ask(app, LinkAsk { document, missing, modified, notes, back: false }); } } } @@ -587,6 +600,84 @@ mod tests { json!({ "name": format!("{n}.png"), "path": format!("/gone/{n}.png"), "ids": [n] }) } + fn check_replacing_a_missing_file_stays_in_the_opening_drawing(native_picker: bool) { + let name = if native_picker { "different-drawing-picker" } else { "different-drawing-path" }; + let (mut app, dir, _) = opened_without_links(name); + let missing = drive::fields::(&app)["missing"][0].clone(); + let id = missing["ids"][0].as_u64().unwrap(); + let picker = crate::tests::picks::scripted(&mut app); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let mut second_ids = Vec::new(); + for name in ["second-one.png", "second-two.png"] { + let path = dir.join(name); + std::fs::write(&path, png([0, 200, 0])).unwrap(); + let place = app.run("file.place", json!({"path": path.to_string_lossy()})).unwrap(); + second_ids.push(place["ids"][0].as_u64().unwrap()); + } + assert!(second_ids.contains(&id), "the same ID refers to a different linked file"); + let params = json!({"ids": [id]}); + let original_path = app.run("links.check", params.clone()).unwrap()["links"][0]["path"].clone(); + + app.run("document.activate", json!({"index": 0})).unwrap(); + if native_picker { + drive::answer::(&mut app, &[], true); + assert_eq!(picker.requests().len(), 1); + } + app.run("document.activate", json!({"index": 1})).unwrap(); + let replacement = dir.join("replacement.png"); + std::fs::write(&replacement, png([0, 0, 200])).unwrap(); + let replacement = replacement.to_string_lossy(); + if native_picker { + picker.answer(&[&replacement]); + drive::frame(&mut app); + drive::pump(&mut app); + } else { + drive::answer::(&mut app, &[("path", json!(replacement))], true); + } + + assert_eq!(app.session.active_index(), Some(1)); + let after = app.run("links.check", params).unwrap()["links"][0]["path"].clone(); + assert_eq!(after, original_path, "the second drawing must keep its original link"); + assert_eq!(app.ui.status, "This dialog was opened in a different document."); + assert_eq!(drive::fields::(&app)["missing"][0], missing); + + app.run("document.activate", json!({"index": 0})).unwrap(); + drive::answer::(&mut app, &[("path", json!(replacement))], true); + assert_eq!(app.run("links.check", json!({})).unwrap()["missing"], 1, "the opening drawing can still replace its file"); + assert_eq!(asked_name(&app), "b.png", "the remaining missing file is still offered"); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn typed_missing_file_replacement_keeps_the_other_drawing_untouched() { + check_replacing_a_missing_file_stays_in_the_opening_drawing(false); + } + + #[test] + fn delayed_missing_file_picker_keeps_the_other_drawing_untouched() { + check_replacing_a_missing_file_stays_in_the_opening_drawing(true); + } + + #[test] + fn a_missing_file_folder_search_starts_only_in_the_opening_drawing() { + use crate::dialogs::find_links::FindLinksDialog; + + let (mut app, dir, _) = opened_without_links("different-drawing-search"); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let folder = [("searchFolder", json!(dir.to_string_lossy()))]; + drive::answer::(&mut app, &folder, true); + assert!(drive::is_open::(&app)); + assert!(!drive::is_open::(&app)); + assert_eq!(app.session.active_index(), Some(1)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + drive::answer::(&mut app, &folder, true); + assert!(drive::is_open::(&app)); + assert_eq!(app.session.active_index(), Some(0)); + drive::answer::(&mut app, &[], false); + let _ = std::fs::remove_dir_all(dir); + } + /// Replace relinks the first file and asks about the next; Ignore keeps its preview. #[test] fn opening_without_linked_files_asks_to_replace_or_ignore_each() { diff --git a/crates/ui-egui/src/dialogs/new_brush.rs b/crates/ui-egui/src/dialogs/new_brush.rs index 46b202fe76..7fcb8ca726 100644 --- a/crates/ui-egui/src/dialogs/new_brush.rs +++ b/crates/ui-egui/src/dialogs/new_brush.rs @@ -25,6 +25,7 @@ const TYPES: [&str; 5] = ["calligraphic", "scatter", "art", "bristle", "pattern" /// It starts on Art when there is art, and it starts on Calligraphic otherwise. pub fn open(app: &mut VectorcraftApp, ids: Option) -> Result { let st = app.session.active().ok_or("no document open")?; + let document = st.uid; let art = match &ids { Some(ids) => ids.as_array().is_some_and(|a| !a.is_empty()), None => !st.selection.is_empty(), @@ -36,7 +37,13 @@ pub fn open(app: &mut VectorcraftApp, ids: Option) -> Result, /// The open Indexed Color dialog's live preview. - pub indexed: Option, + pub indexed: Option, /// The open Gap Options dialog's live preview. pub gaps: Option, /// The Properties section's pending colour pick: dialog id, field key and target dimension. diff --git a/crates/ui-egui/src/dialogs/option_form.rs b/crates/ui-egui/src/dialogs/option_form.rs index 8648332c7e..49ef4a34b4 100644 --- a/crates/ui-egui/src/dialogs/option_form.rs +++ b/crates/ui-egui/src/dialogs/option_form.rs @@ -7,7 +7,7 @@ use std::ops::RangeInclusive; use craft::theme::variant::Tone; use craft::ui::choice::{Checkbox, Radio, RadioGroup}; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Politeness, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; use craft::ui::form::{Field, FieldGroup}; use craft::ui::layout_components::Row; @@ -175,6 +175,8 @@ pub(crate) struct OptionForm { lengths: LengthUnits, /// The Preview check box. pub(super) preview: bool, + /// The current document does not own this dialog's preview. + pub(super) preview_paused: bool, /// Whether the dialog's container is open. open: bool, /// The OK the dialog filed for [`pump`] to answer. @@ -202,6 +204,7 @@ pub(super) fn open(app: &mut VectorcraftApp, spec: &'static OptionSpec, values: extra, lengths, preview: false, + preview_paused: false, open: true, held: HeldAnswer::new(), requests: HostRequests::new(), @@ -249,8 +252,9 @@ impl StackDialog for OptionForm { // The app accepted the held OK: this pass closes the dialog with it. A measuring run closes nothing. let finish = self.held.is_accepted() && !measuring; let answers = if measuring { Vec::new() } else { self.requests.take_answers() }; - let OptionForm { spec, values, lengths, preview, open, held, requests, .. } = self; + let OptionForm { spec, values, lengths, preview, preview_paused, open, held, requests, .. } = self; let (spec, lengths) = (*spec, *lengths); + let show_pause = *preview && *preview_paused; let title = (spec.title)(); let refusal = held.refusal().map(|(reason, refused)| (reason.clone(), refused.clone())); let mut form = FormDialog::new(word(&title), Bind::bound(&mut *values)) @@ -274,6 +278,12 @@ impl StackDialog for OptionForm { if let Some((reason, _)) = refusal.as_ref().filter(|(_, refused)| *refused == *values) { Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui); } + if show_pause { + Notice::new(Tone::Info, tl!("Preview is paused. Return to the document this dialog was opened for.").to_owned()) + .layout(NoticeLayout::Inline) + .announce(Politeness::Polite) + .show(ui); + } if finish { form.request_close_as(CloseReason::Activated); } diff --git a/crates/ui-egui/src/dialogs/package.rs b/crates/ui-egui/src/dialogs/package.rs index 61397b4076..5580f9511c 100644 --- a/crates/ui-egui/src/dialogs/package.rs +++ b/crates/ui-egui/src/dialogs/package.rs @@ -20,7 +20,7 @@ use craft::ui::runtime::requests::PathKind; use serde_json::{Value, json}; use vectorcraft_engine::EngineError; -use super::confirm::ask; +use super::confirm::{ask, ask_in_document}; use crate::background::{self, Writer}; use crate::{VectorcraftApp, file_asks, io}; @@ -46,7 +46,7 @@ fn downloads(app: &VectorcraftApp) -> bool { pub fn open(app: &mut VectorcraftApp) -> Result { let st = app.session.active().ok_or("no document")?; let Some(path) = st.path.clone() else { - ask( + ask_in_document( app, tl!("Save the document first?"), tl!("Package collects a saved document with its linked files and fonts."), @@ -55,6 +55,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { ); return Ok(Value::Null); }; + let document = st.uid; let p = std::path::Path::new(&path); let stem = p.file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned()); let folder = p.parent().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(); @@ -73,6 +74,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { .footer_note(Label::from(tl!("Fonts whose licence doesn't allow embedding are not copied."))) }); crate::dialogs::host::open_held(app, dialog, |app, answer| confirm(app, &answer.fields).map(|_| ())).ok_or("no window")?; + app.package_document = Some(document); Ok(Value::Null) } @@ -96,13 +98,27 @@ fn params(web: bool) -> Vec { pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let id = dialog_id(KEY); - let Some(request) = dialogs.with(|host| host.get_mut_by_id::(id).and_then(HostedParamDialog::pick_path)) else { return }; - file_asks::browse(app, id, request, PickRequest::folder(PURPOSE), file_asks::answer_path); + let Some(request) = dialogs.with(|host| host.get_mut_by_id::(id).map(HostedParamDialog::pick_path)) else { + app.package_document = None; + return; + }; + if let Some(request) = request { + file_asks::browse(app, id, request, PickRequest::folder(PURPOSE), file_asks::answer_path); + } +} + +fn require_package_document(app: &VectorcraftApp, document: u64) -> Result<(), String> { + if app.session.active().is_none_or(|st| st.uid != document) { + return Err(tl!("Package can only save and collect the document where it was opened.").to_owned()); + } + Ok(()) } /// What OK does: save a dirty document, then write the package (on the worker with Background Export on) or /// download it. `Err` refuses the OK and keeps the dialog open; the reply says whether the package is in the background. pub(super) fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) -> Result { + let document = app.package_document.ok_or("no Package dialog open")?; + require_package_document(app, document)?; let text = |key: &str| fields.text(key).unwrap_or_default(); let mut params = json!({ "folder": text("folder"), "name": text("name") }); for (key, _) in OPTIONS { @@ -144,6 +160,8 @@ pub(super) fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) -> Result return r; } } + // A completed background job may have changed the active document while Package waited. + require_package_document(app, document)?; let package = app.session.prepare_package(¶ms).map_err(|e| e.to_string()).inspect_err(|e| app.ui.status = e.clone())?; let label = format!("Packaging {}", text("name")); let later = Rc::new(Cell::new(false)); diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index 04e86b346d..a1f4002f11 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -609,7 +609,7 @@ fn tabs_buttons(unit: Unit) -> Param { let (rows, _, _) = tab_rows(fields); let can_add = new_tab_position(&rows, unit).is_some(); let (mut add, mut delete, mut clear) = (false, false, false); - let line = Row::new().show(ui, |ui, _| { + let line = Row::new().wrap(true).show(ui, |ui, _| { add = clicked(&Button::new(tl!("Add")).enabled(can_add).show(ui)); delete = clicked(&Button::new(tl!("Delete Tab")).enabled(!rows.is_empty()).show(ui)); clear = clicked(&Button::new(tl!("Clear All Tabs")).enabled(!rows.is_empty()).show(ui)); diff --git a/crates/ui-egui/src/dialogs/para_style_options/tests.rs b/crates/ui-egui/src/dialogs/para_style_options/tests.rs index 52c8105804..43543d8f3c 100644 --- a/crates/ui-egui/src/dialogs/para_style_options/tests.rs +++ b/crates/ui-egui/src/dialogs/para_style_options/tests.rs @@ -348,6 +348,42 @@ fn tab_rows(app: &VectorcraftApp) -> Vec { fields(app)["tabs"].as_array().cloned().unwrap_or_default() } +#[test] +fn clear_all_tabs_can_be_clicked_in_a_narrow_viewport() { + use egui::accesskit::Role; + use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + for width in [800.0, 540.0] { + let mut app = app(); + app.run("paraStyle.new", json!({"name": "Body", "attrs": {"tabs": [{"position": 36.0}, {"position": 72.0}]}})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(width, 500.0)); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events| { + time += 0.25; + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }) + }; + frame(&mut app, vec![]); + open_tabs(&mut app, "Body"); + for _ in 0..5 { + frame(&mut app, vec![]); + } + let out = frame(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + let clear = nodes.iter().find(|(_, node)| node.role() == Role::Button && node.label() == Some("Clear All Tabs")).unwrap(); + let bounds = clear.1.bounds().unwrap(); + let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32); + + assert_eq!(tab_rows(&app).len(), 2); + frame(&mut app, vec![Event::PointerMoved(at)]); + for pressed in [true, false] { + frame(&mut app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + frame(&mut app, vec![]); + assert!(tab_rows(&app).is_empty(), "Clear All Tabs at {bounds:?} was not reachable in a {width}-point viewport"); + } +} + /// Tabs shows a style's stops in the General unit with their alignment, leader and Align On /// character; a stop left as it was keeps its position exactly, a changed one is read in the unit, /// and the stops are stored sorted by position. Add puts a left stop half an inch past the furthest diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 64176e93ac..92cba2edb5 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -3,6 +3,8 @@ //! Every dialog is a held parameter dialog: its OK is the closure given to `open_held`, a refusal keeps it open with //! the reason, and [`pump`] only runs the live preview of the kinds that have one. +use std::sync::{Arc, Weak}; + // PLAN: the framework import paths below are assumed from the contract rows (craft-ui-patterns re-exports contract and // runtime; the form-dialog items live under `patterns::form_dialogs`; `Field` and `NumberField` under craft-ui-widgets). use craft::behavior::ColumnWidth; @@ -19,7 +21,7 @@ use craft::ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; use craft::ui::text::{NumberField, NumberOutput}; use craft::ui::value_drag::SliderScale; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{NodeId, NodeKind, Selection}; use vectorcraft_geom::PathData; use super::form; @@ -123,8 +125,55 @@ pub(crate) struct Open { /// The open Split Into Grid dialog's live state. pub(crate) struct SplitOpen { id: DialogId, + document: u64, preview: LivePreview, - last: Value, + /// An interaction allocates its own selection snapshot, even when the selected objects did not change. + preview_selection: Option>, +} + +impl SplitOpen { + fn owns_preview(&self, app: &VectorcraftApp) -> bool { + let Some(selection) = &self.preview_selection else { return false }; + app.session.active().is_some_and(|state| { + state.uid == self.document + && state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection)) + }) + } + + fn update_preview(&mut self, app: &mut VectorcraftApp, on: bool, fields: &DialogFields) { + let Some(state) = app.session.active().filter(|state| state.uid == self.document) else { return }; + if !self.owns_preview(app) { + self.preview = LivePreview::default(); + self.preview_selection = None; + if state.interaction.is_some() { + return; + } + } + let params = split_params(fields); + let ran = self.preview.run(app, on, tl!("Split Into Grid"), SPLIT_COMMAND, ¶ms).is_some(); + if !on { + self.preview_selection = None; + } else if ran { + self.preview_selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection)); + } + } + + fn confirm(&mut self, app: &mut VectorcraftApp, fields: &DialogFields) -> Result<(), String> { + if app.session.active().is_none_or(|state| state.uid != self.document) { + return Err(tl!("Split Into Grid can only change the document where it was opened.").to_owned()); + } + if app.session.in_interaction() && !self.owns_preview(app) { + return Err(tl!("Finish the active edit before applying Split Into Grid.").to_owned()); + } + self.preview_selection = None; + std::mem::take(&mut self.preview).commit(app, SPLIT_COMMAND, split_params(fields)).map(drop) + } + + fn cancel(self, app: &mut VectorcraftApp) { + if self.owns_preview(app) { + self.preview.cancel(app); + } + } } /// The command the dialog runs and its parameters. @@ -410,34 +459,25 @@ pub(crate) fn open_split(app: &mut VectorcraftApp) { app.status("There is no window to show the dialog in."); return; }; - let (width, height) = - app.session.active().and_then(|st| st.doc.bounds_of(&st.selection.objects, false)).map_or((0.0, 0.0), |b| (b.width(), b.height())); + let Some(state) = app.session.active() else { + app.status("Open a document before using Split Into Grid."); + return; + }; + let document = state.uid; + let (width, height) = state.doc.bounds_of(&state.selection.objects, false).map_or((0.0, 0.0), |b| (b.width(), b.height())); let lengths = crate::canvas::general_lengths(app); let dialog = HostedParamDialog::new(&ctx, SPLIT_COMMAND, split_fields(width, height), move |f| { ParamDialog::new(SPLIT_COMMAND, tl!("Split Into Grid"), split_rows(lengths)).values(Bind::bound(f)).previews(true) }); let ok = |app: &mut VectorcraftApp, result: &craft::ui::patterns::form_dialogs::ParamResult| { - let params = split_params(&result.fields); - match app.object_dialogs.split.take() { - Some(record) => { - let id = record.id; - record.preview.commit(app, SPLIT_COMMAND, params).map(drop).inspect_err(|_| { - app.object_dialogs.split = Some(SplitOpen { id, preview: LivePreview::default(), last: Value::Null }); - }) - } - None => app.run(SPLIT_COMMAND, params).map(drop), - } + let Some(mut record) = app.object_dialogs.split.take() else { return Err(tl!("The Split Into Grid dialog is closed.").to_owned()) }; + record.confirm(app, &result.fields).inspect_err(|_| app.object_dialogs.split = Some(record)) }; if let Some(old) = app.object_dialogs.split.take() { - old.preview.cancel(app); + old.cancel(app); } - let cancel = Box::new(|app: &mut VectorcraftApp| { - if let Some(record) = app.object_dialogs.split.take() { - record.preview.cancel(app); - } - }); - match open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }) { - Some(id) => app.object_dialogs.split = Some(SplitOpen { id, preview: LivePreview::default(), last: Value::Null }), + match open_held(app, dialog, ok) { + Some(id) => app.object_dialogs.split = Some(SplitOpen { id, document, preview: LivePreview::default(), preview_selection: None }), None => app.status("There is no window to show the dialog in."), } } @@ -456,17 +496,13 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { } records.append(&mut app.object_dialogs.path); app.object_dialogs.path = records; - if let Some(mut s) = app.object_dialogs.split.take() { - if let Some((on, fields)) = dialog_state(app, s.id) { - let params = split_params(&fields); - if !on { - s.last = Value::Null; - } - if s.preview.run(app, on, tl!("Split Into Grid"), SPLIT_COMMAND, ¶ms).is_some() { - s.last = params; - } + if let Some(mut split) = app.object_dialogs.split.take() { + if let Some((on, fields)) = dialog_state(app, split.id) { + split.update_preview(app, on, &fields); + app.object_dialogs.split = Some(split); + } else { + split.cancel(app); } - app.object_dialogs.split = Some(s); } } @@ -516,3 +552,115 @@ pub(crate) fn original_paths(app: &VectorcraftApp) -> Vec<(NodeId, &PathData)> { }) .collect() } + +#[cfg(test)] +mod split_tests { + use serde_json::json; + + use super::*; + use crate::dialogs::tests::{app, cancel, confirm, frame, is_open, set}; + + fn selected_rectangle(app: &mut VectorcraftApp, width: u32, height: u32) { + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": width, "height": height})).unwrap(); + app.run("select.all", json!({})).unwrap(); + } + + fn other_document(app: &mut VectorcraftApp) { + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + selected_rectangle(app, 150, 90); + } + + #[test] + fn split_into_grid_skips_preview_in_the_other_drawing() { + let mut app = app(); + selected_rectangle(&mut app, 112, 62); + let original = app.session.doc().unwrap().doc.clone(); + open_split(&mut app); + set(&mut app, "columns", json!(3)); + other_document(&mut app); + let other = app.session.doc().unwrap().doc.clone(); + set(&mut app, "preview", json!(true)); + + frame(&mut app, vec![]); + + assert!(app.session.doc().unwrap().doc == other, "the other drawing is unchanged by Preview"); + assert!(!app.session.in_interaction()); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, vec![]); + assert_ne!(app.session.doc().unwrap().doc, original); + assert!(app.session.in_interaction()); + assert!(confirm(&mut app)); + assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 6); + assert!(!app.session.in_interaction()); + } + + #[test] + fn split_into_grid_keeps_the_draft_when_ok_is_in_another_drawing() { + let mut app = app(); + selected_rectangle(&mut app, 112, 62); + open_split(&mut app); + set(&mut app, "columns", json!(3)); + other_document(&mut app); + let other = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + + let closed = confirm(&mut app); + + assert!(app.session.doc().unwrap().doc == other, "the other drawing is unchanged by OK"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + assert!(!closed && is_open(&app), "the user can return to confirm"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(confirm(&mut app)); + assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 6); + } + + #[test] + fn split_into_grid_cancel_preserves_the_other_drawings_edit() { + let mut app = app(); + selected_rectangle(&mut app, 112, 62); + other_document(&mut app); + app.run("document.activate", json!({"index": 0})).unwrap(); + let opening = app.session.doc().unwrap().doc.clone(); + open_split(&mut app); + set(&mut app, "preview", json!(true)); + frame(&mut app, vec![]); + assert!(app.session.in_interaction(), "the opening drawing is previewing"); + + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Other edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap(); + let other = app.session.doc().unwrap().doc.clone(); + assert!(cancel(&mut app)); + + assert!(app.session.in_interaction(), "Cancel preserves the other drawing's pending edit"); + assert_eq!(app.session.doc().unwrap().doc, other); + app.session.commit_interaction().unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, opening); + } + + #[test] + fn split_into_grid_does_not_adopt_a_new_edit_on_return() { + let mut app = app(); + selected_rectangle(&mut app, 112, 62); + other_document(&mut app); + app.run("document.activate", json!({"index": 0})).unwrap(); + open_split(&mut app); + set(&mut app, "preview", json!(true)); + frame(&mut app, vec![]); + assert!(app.session.in_interaction()); + for index in [1, 0] { + app.run("document.activate", json!({"index": index})).unwrap(); + } + app.session.begin_interaction("New edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap(); + let editing = app.session.doc().unwrap().doc.clone(); + + frame(&mut app, vec![]); + assert!(!confirm(&mut app)); + assert!(cancel(&mut app)); + + assert!(app.session.in_interaction()); + assert_eq!(app.session.doc().unwrap().doc, editing); + } +} diff --git a/crates/ui-egui/src/dialogs/perspective_plane.rs b/crates/ui-egui/src/dialogs/perspective_plane.rs index 90d37a3f70..13ec8754e0 100644 --- a/crates/ui-egui/src/dialogs/perspective_plane.rs +++ b/crates/ui-egui/src/dialogs/perspective_plane.rs @@ -19,6 +19,8 @@ use crate::canvas::general_lengths; /// The dialog kind of the plane options. pub const KIND: &str = "perspectivePlane"; +const OPENING_DOCUMENT: &str = "__openingDocument"; + /// What becomes of the objects on the plane: (`objects` value, label). const OBJECTS: [(&str, &str); 3] = [("none", "Do Not Move"), ("move", "Move All Objects"), ("copy", "Copy All Objects")]; @@ -47,8 +49,9 @@ fn build<'a>(title: &str, lengths: LengthUnits, _fields: &'a mut DialogFields) - /// Open the options of `plane` (`{plane}`; default the active plane), filled in with its location. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { - let doc = &app.session.active().ok_or("no document")?.doc; - let g = PerspectiveGrid::current(doc); + let state = app.session.active().ok_or("no document")?; + let document = state.uid; + let g = PerspectiveGrid::current(&state.doc); let plane = match p.get("plane").and_then(Value::as_str) { Some(s) => Plane::parse(s).ok_or("plane must be left, right or ground")?, None => g.plane, @@ -60,12 +63,20 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let lengths = general_lengths(app); let ctx = app.ui_ctx.clone().ok_or("no window")?; let Value::Object(map) = json!({"plane": plane.id(), "location": offset, "objects": "none"}) else { return Err("no window".into()) }; + let mut fields = form::fields_of(¶ms(lengths), &map); + // The held answer carries the drawing and plane from the same opening. + fields.set(OPENING_DOCUMENT, document.to_string()); let heading = title(plane); - let dialog = HostedParamDialog::new(&ctx, KIND, form::fields_of(¶ms(lengths), &map), move |f| build(&heading, lengths, f)); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |f| build(&heading, lengths, f)); // A refusal keeps the dialog open with the reason under its rows. - let ok = move |app: &mut VectorcraftApp, r: &ParamResult| { + let ok = |app: &mut VectorcraftApp, r: &ParamResult| { + let document = r.fields.text(OPENING_DOCUMENT).and_then(|uid| uid.parse().ok()); + if !app.session.active().is_some_and(|state| Some(state.uid) == document) { + return Err(tl!("Perspective Plane Options can only change the document where it was opened.").to_owned()); + } + let plane = r.fields.text("plane").ok_or_else(|| tl!("The perspective plane is missing").to_owned())?; let objects = r.fields.text("objects").unwrap_or("none"); - let p = json!({"plane": plane.id(), "offset": r.fields.number("location").unwrap_or(0.0), "objects": objects}); + let p = json!({"plane": plane, "offset": r.fields.number("location").unwrap_or(0.0), "objects": objects}); app.run("perspective.plane.move", p).map(|_| ()) }; open_held(app, dialog, ok).ok_or("no window")?; @@ -100,15 +111,75 @@ mod tests { host(app, |h| h.set_json_field(&ctx, id, field, value)).unwrap(); } - /// OK on the open dialog, then the frame's pump runs the held OK. - fn ok(app: &mut VectorcraftApp) { + fn pump_ok(app: &mut VectorcraftApp) { let (ctx, (id, _)) = (app.ui_ctx.clone().unwrap(), the_dialog(app)); // A held OK reports `false` and files its answer for the app; the dialog closes at its next pass. assert!(host(app, |h| h.confirm_by_id(&ctx, id) || h.held_state(id) == Some(craft::ui::dialog::HeldOk::Waiting)), "OK is enabled"); crate::dialogs::host::pump(app, &ctx); + } + + fn ok(app: &mut VectorcraftApp) { + pump_ok(app); + let ctx = app.ui_ctx.clone().unwrap(); crate::tests_synthetic::key_frame(app, &ctx, vec![]); } + fn right_plane_with_art(app: &mut VectorcraftApp) { + app.run("perspective.grid.preset", json!({"kind": 2})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 450, "y": 380, "width": 60, "height": 60})).unwrap()["id"].clone(); + app.run("perspective.attach", json!({"ids": [id], "plane": "right"})).unwrap(); + } + + #[test] + fn plane_options_keep_the_plane_and_copied_objects_in_the_opening_document() { + let mut app = app(); + right_plane_with_art(&mut app); + let opening = app.session.doc().unwrap().doc.clone(); + app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap(); + set(&app, "location", json!(40.0)); + set(&app, "objects", json!("copy")); + + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + right_plane_with_art(&mut app); + let other = app.session.doc().unwrap().doc.clone(); + let history = app.session.doc().unwrap().history.undo.len(); + let (id, _) = the_dialog(&app); + pump_ok(&mut app); + + assert_eq!(app.session.doc().unwrap().doc, other, "foreign OK leaves the other drawing and its art unchanged"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), history); + assert!(matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_)))); + assert_eq!(the_dialog(&app).1["location"], 40.0); + assert_eq!(the_dialog(&app).1["objects"], "copy"); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, opening); + ok(&mut app); + let doc = &app.session.doc().unwrap().doc; + assert_eq!(PerspectiveGrid::current(doc).right_offset, 40.0); + assert_eq!(doc.layers[0].children().unwrap().len(), 2, "one copy in the opening drawing"); + } + + #[test] + fn replacement_plane_options_use_the_replacement_drawing_and_plane() { + let mut app = app(); + app.run("perspective.grid.preset", json!({"kind": 2})).unwrap(); + let opening = app.session.doc().unwrap().doc.clone(); + app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap(); + + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.run("perspective.grid.preset", json!({"kind": 2})).unwrap(); + app.run("ui.perspectivePlane", json!({"plane": "ground"})).unwrap(); + set(&app, "location", json!(40.0)); + ok(&mut app); + + let grid = PerspectiveGrid::current(&app.session.doc().unwrap().doc); + assert_eq!(grid.offset(Plane::Ground), 40.0, "OK moves the replacement opening's plane"); + assert_eq!(grid.offset(Plane::Right), 0.0); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, opening); + } + #[test] fn double_clicking_a_plane_widget_opens_its_options_and_ok_moves_it() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/perspective_presets.rs b/crates/ui-egui/src/dialogs/perspective_presets.rs index 9d3f81d15d..930c5fa0fc 100644 --- a/crates/ui-egui/src/dialogs/perspective_presets.rs +++ b/crates/ui-egui/src/dialogs/perspective_presets.rs @@ -298,8 +298,9 @@ pub(super) fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Resul Action::Import => { let request = PickRequest::open(KIND).filter("Perspective grid presets", PRESET_EXTS); file_asks::ask(app, request, Owner::Free, |app, picked| { - let path = picked.first_path().ok_or("cancelled")?; - let r = app.run("perspective.presets.import", json!({ "path": path }))?; + let mut params = file_asks::open_params(&picked).ok_or("cancelled")?; + params.remove("name"); + let r = app.run("perspective.presets.import", Value::Object(params))?; if let Some(first) = r["imported"].get(0).and_then(Value::as_str) { select(app, first); } diff --git a/crates/ui-egui/src/dialogs/placement_options.rs b/crates/ui-egui/src/dialogs/placement_options.rs index 3a0fed9ef7..f647a20f69 100644 --- a/crates/ui-egui/src/dialogs/placement_options.rs +++ b/crates/ui-egui/src/dialogs/placement_options.rs @@ -43,6 +43,7 @@ fn params() -> Vec { /// Open the dialog on the placement options of images `ids` (default: the selected ones). pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { + let source_document = app.session.active().map(|document| document.uid); let ids = p.get("ids").cloned().unwrap_or(Value::Null); let r = app.session.execute(CMD, &json!({ "ids": ids })).map_err(|e| e.to_string())?; let placement = &r["placement"]; @@ -60,6 +61,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { }) .held_ok(); crate::dialogs::host::open_held(app, dialog, move |app, result: &ParamResult| { + if app.session.active().map(|document| document.uid) != source_document { + return Err(tl!("Placement Options can only change the document where it was opened.").to_owned()); + } let f = &result.fields; let align = f.int("align").and_then(|i| usize::try_from(i).ok()).and_then(|i| ALIGN.get(i).copied()).unwrap_or(ALIGN[CENTRE]); let params = json!({ "ids": ids, "preserve": f.text("preserve"), "align": align, "clip": f.bool("clip").unwrap_or(false) }); @@ -68,3 +72,57 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { .ok_or("no window")?; Ok(Value::Null) } + +#[cfg(test)] +mod tests { + use craft::ui::dialog::{HeldOk, dialog_id}; + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + use vectorcraft_engine::Session; + + use super::*; + + #[test] + fn held_placement_options_keep_the_link_and_undo_in_the_opening_document() { + let dir = vectorcraft_testkit::TempDir::new("placement-options-document"); + let path = dir.join("linked.png"); + let image = Image::from_raw(2, 2, ChannelLayout::Rgba, SampleType::U8, vec![255; 16]).unwrap(); + std::fs::write(&path, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let link = |app: &mut VectorcraftApp| { + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("file.place", json!({"path": path, "at": [100, 100], "link": true})).unwrap()["ids"][0].as_u64().unwrap() + }; + let source_link = link(&mut app); + let other_link = link(&mut app); + assert_eq!(source_link, other_link, "different documents reuse this object ID"); + let settings = |app: &mut VectorcraftApp| { + let placement = app.run(CMD, json!({"ids": [source_link]})).unwrap()["placement"].clone(); + (placement, app.session.active().unwrap().history.undo.len()) + }; + let other = settings(&mut app); + + app.run("document.activate", json!({"index": 0})).unwrap(); + let starting = settings(&mut app); + app.run("ui.placementOptionsDialog", json!({"ids": [source_link]})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(KEY); + dialogs.with(|host| { + host.set_json_field(&ctx, id, "preserve", json!("fit")).unwrap(); + assert!(!host.confirm_by_id(&ctx, id)); + assert_eq!(host.held_state(id), Some(HeldOk::Waiting)); + }); + + app.run("document.activate", json!({"index": 1})).unwrap(); + crate::dialogs::host::pump(&mut app, &ctx); + assert_eq!(settings(&mut app), other, "the other link and its undo history are preserved"); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(settings(&mut app), starting); + assert!(crate::dialogs::tests::confirm(&mut app)); + let (placement, steps) = settings(&mut app); + assert_eq!(placement["preserve"], json!("fit")); + assert_eq!(steps, starting.1 + 1); + } +} diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index e911e7c0a2..8e405c7a63 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -100,6 +100,7 @@ pub(crate) struct PrintDialogs { struct Open { id: DialogId, mode: PrintMode, + document: Option, /// The preset the settings were loaded from last (the Print Preset row's selection). preset: String, /// The saved preset the editor edits (empty: a new one). @@ -157,7 +158,8 @@ pub fn open(app: &mut VectorcraftApp) -> Result { // The saved preset these settings are, if any (else [Default], shown as [Custom] if they differ). let preset = app.session.prefs.print_presets.iter().find(|p| p.settings == saved).map_or(DEFAULT_PRESET, |p| p.name.as_str()).to_string(); let fields = fields_of(&saved)?; - start(app, PrintMode::Print, fields, preset, Default::default()) + let document = st.uid; + start(app, PrintMode::Print, Some(document), fields, preset, Default::default()) } /// Open the preset editor on the saved preset `name`, or on a new preset starting from `preset` @@ -173,7 +175,7 @@ pub fn open_preset(app: &mut VectorcraftApp, params: &Value) -> Result (s("preset").unwrap_or(DEFAULT_PRESET).to_string(), app.session.new_print_preset_name(), String::new()), }; let set = app.session.print_preset_settings(&base).ok_or_else(|| format!("no print preset named `{base}`"))?; - start(app, PrintMode::PresetEditor, fields_of(&set)?, base, (editing, name)) + start(app, PrintMode::PresetEditor, None, fields_of(&set)?, base, (editing, name)) } /// Host the dialog over the settings `fields`; the preset editor edits the saved preset `editing` (empty: a new one) @@ -181,6 +183,7 @@ pub fn open_preset(app: &mut VectorcraftApp, params: &Value) -> Result, fields: DialogFields, preset: String, (editing, name): (String, String), @@ -217,7 +220,7 @@ fn start( hosted.set_json_field(&ctx, "name", json!(name))?; } let id = dialogs.with(|h| h.open(hosted)); - app.print_dialog.open = Some(Open { id, mode, preset, editing, art: None, preview: None, driver }); + app.print_dialog.open = Some(Open { id, mode, document, preset, editing, art: None, preview: None, driver }); Ok(Value::Null) } @@ -366,6 +369,30 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, let _ = dialogs.with(|h| h.take_by_id::(open.id)); return false; }; + for event in std::mem::take(&mut d.events) { + apply_preset_event(app, dialogs, open, &mut d.settings, event); + } + if open.mode == PrintMode::Print { + let same = serde_json::from_value::(d.settings.clone()) + .ok() + .is_some_and(|s| app.session.print_preset_settings(&open.preset) == Some(s)); + let held = same.then(|| open.preset.clone()); + let rows: Vec> = std::iter::once(PresetRow::item(DEFAULT_PRESET.to_string(), tl!(DEFAULT_PRESET), 0)) + .chain(app.session.prefs.print_presets.iter().map(|p| PresetRow::item(p.name.clone(), p.name.clone(), 0))) + .collect(); + on(dialogs, |p| p.set_presets(rows, held, vec![DEFAULT_PRESET.to_string()])); + } + if open.document.is_some_and(|document| app.session.active().is_none_or(|st| st.uid != document)) { + let message = tl!("Return to the original drawing to print it"); + on(dialogs, |p| { + p.set_sheet(None); + p.set_message(Some(message.into())); + if d.ok.is_some() { + p.answer_ok(Err(message.into())); + } + }); + return true; + } // The row was drawn this frame with the controls of the printer before: the next frame shows the new ones. if d.driver != open.driver { open.driver = d.driver; @@ -383,9 +410,6 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, { app.status(e); } - for event in std::mem::take(&mut d.events) { - apply_preset_event(app, dialogs, open, &mut d.settings, event); - } let doc = app.session.active().map_or((0, 0), |s| (s.uid, s.revision)); let stamp = (d.settings.to_string(), doc); let changed = open.preview.as_ref().is_none_or(|(s, _)| *s != stamp); @@ -425,16 +449,6 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, p.set_field("__inks", FieldValue::Json(inks)); }); } - if open.mode == PrintMode::Print { - let same = serde_json::from_value::(d.settings.clone()) - .ok() - .is_some_and(|s| app.session.print_preset_settings(&open.preset) == Some(s)); - let held = same.then(|| open.preset.clone()); - let rows: Vec> = std::iter::once(PresetRow::item(DEFAULT_PRESET.to_string(), tl!(DEFAULT_PRESET), 0)) - .chain(app.session.prefs.print_presets.iter().map(|p| PresetRow::item(p.name.clone(), p.name.clone(), 0))) - .collect(); - on(dialogs, |p| p.set_presets(rows, held, vec![DEFAULT_PRESET.to_string()])); - } if let Some(answer) = d.ok { let result = accept(app, open, &answer, &d.name); on(dialogs, |p| p.answer_ok(result.map_err(Into::into))); diff --git a/crates/ui-egui/src/dialogs/psd_import.rs b/crates/ui-egui/src/dialogs/psd_import.rs index 19364ef8d3..55d7ec3a20 100644 --- a/crates/ui-egui/src/dialogs/psd_import.rs +++ b/crates/ui-egui/src/dialogs/psd_import.rs @@ -84,6 +84,7 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option (&'static str, &'static LayoutG } } -/// The settings the dialog edits, and for Rearrange the artboards it lays out (`indices`, sorted -/// and once each), which the dialog does not edit. +/// The settings the dialog edits. #[derive(Clone, Debug, PartialEq)] pub(crate) struct RearrangeValues { layout: ArtboardLayout, @@ -78,26 +77,21 @@ pub(crate) struct RearrangeValues { columns: f64, spacing: f64, move_artwork: bool, - indices: Option>, } impl Default for RearrangeValues { fn default() -> Self { - RearrangeValues { layout: ArtboardLayout::GridByRow, rtl: false, columns: 2.0, spacing: 20.0, move_artwork: true, indices: None } + RearrangeValues { layout: ArtboardLayout::GridByRow, rtl: false, columns: 2.0, spacing: 20.0, move_artwork: true } } } impl RearrangeValues { /// `artboard.rearrange` parameters. fn params(&self) -> Value { - let mut p = json!({ + json!({ "layout": self.layout.id(), "order": self.order(), "columns": self.columns, "spacing": self.spacing, "moveArtwork": self.move_artwork, - }); - if let Some(indices) = &self.indices { - p["indices"] = json!(indices); - } - p + }) } fn order(&self) -> &'static str { @@ -154,16 +148,19 @@ pub(crate) fn open_selected(app: &mut VectorcraftApp, indices: &[usize]) { /// Opens the dialog for `indices` (Rearrange), or for every artboard (Rearrange All Artboards). fn open_with(app: &mut VectorcraftApp, indices: Option>) -> Result { - let mut values = RearrangeValues::default(); - if let Some(spacing) = app.ui.rearrange_artboards_spacing.as_f64() { - values.spacing = spacing; - } - let artboards = indices.as_ref().map_or_else(|| app.session.active().map_or(0, |doc| doc.doc.artboards.len()), Vec::len); - values.indices = indices; + let st = app.session.active().ok_or("no document")?; + let artboards = indices.as_ref().map_or(st.doc.artboards.len(), Vec::len); + let selected = indices + .map(|indices| { + indices.into_iter().map(|i| st.doc.artboards.get(i).map(|a| (i, a.id)).ok_or("no such artboard")).collect::, _>>() + }) + .transpose()?; + let values = RearrangeValues { spacing: app.ui.rearrange_artboards_spacing.as_f64().unwrap_or(20.0), ..RearrangeValues::default() }; + let document = st.uid; let lengths = LengthUnits::new(UnitKind::Points, length_kind(app.session.general_unit()), 72.0); let lengths = crate::fields::bare_points(lengths, app.session.prefs.numbers_without_units_are_points); let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(RearrangeArtboardsDialog { id: dialog_id(CMD), open: true, values, artboards, lengths })); + dialogs.with(|host| host.open(RearrangeArtboardsDialog { id: dialog_id(CMD), open: true, values, document, selected, artboards, lengths })); Ok(Value::Null) } @@ -181,6 +178,9 @@ pub(crate) struct RearrangeArtboardsDialog { id: DialogId, open: bool, values: RearrangeValues, + document: u64, + /// Each selected artboard's opening row index and stable ID. None lays out the entire document. + selected: Option>, /// The artboards the dialog lays out (the document's, or the selected ones), which bounds Columns /// and is the count it shows. artboards: usize, @@ -188,8 +188,20 @@ pub(crate) struct RearrangeArtboardsDialog { lengths: LengthUnits, } +pub(crate) struct RearrangeAnswer { + values: RearrangeValues, + document: u64, + selected: Option>, +} + +impl RearrangeArtboardsDialog { + fn answer(&self, values: RearrangeValues) -> RearrangeAnswer { + RearrangeAnswer { values, document: self.document, selected: self.selected.clone() } + } +} + /// The rows of the dialog for `artboards` artboards, Spacing shown in `unit`. -fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, lengths: LengthUnits) { +fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, selected: bool, lengths: LengthUnits) { Field::new(tl!("Layout:")).id_salt("layout").show(ui, |ui, _| { let entries: Vec> = ArtboardLayout::ALL .into_iter() @@ -231,12 +243,12 @@ fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, lengths: L v.move_artwork = on; } }); - let label = if v.indices.is_some() { tl!("Selected Artboards: {n}") } else { tl!("Artboards: {n}") }; + let label = if selected { tl!("Selected Artboards: {n}") } else { tl!("Artboards: {n}") }; Text::new(crate::i18n::fmt(label, &[("n", &artboards.to_string())])).role(TypeRole::Caption).show(ui); } impl StackDialog for RearrangeArtboardsDialog { - type Result = RearrangeValues; + type Result = RearrangeAnswer; fn id(&self) -> DialogId { self.id @@ -246,30 +258,31 @@ impl StackDialog for RearrangeArtboardsDialog { Some(CMD) } - fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option> { + fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option> { let (artboards, lengths) = (self.artboards, self.lengths); - let title = if self.values.indices.is_some() { tl!("Rearrange") } else { tl!("Rearrange All Artboards") }; + let selected = self.selected.is_some(); + let title = if selected { tl!("Rearrange") } else { tl!("Rearrange All Artboards") }; let shown = FormDialog::new(title, Bind::bound(&mut self.values)).opened(Bind::bound(&mut self.open)).show(ui, |ui, _, v| { - body(ui, v, artboards, lengths); + body(ui, v, artboards, selected, lengths); true }); match (shown.accepted, shown.closed) { - (Some(value), _) => Some(DialogResult::Ok(value)), + (Some(value), _) => Some(DialogResult::Ok(self.answer(value))), (None, Some(_)) => Some(DialogResult::Cancel), (None, None) => None, } } - fn confirm(&mut self, _: &egui::Context) -> Option { - Some(self.values.clone()) + fn confirm(&mut self, _: &egui::Context) -> Option { + Some(self.answer(self.values.clone())) } fn json_fields(&self) -> Option { let v = &self.values; let mut fields = json!({"layout": v.layout.id(), "order": v.order(), "columns": v.columns, "spacing": v.spacing, "moveArtwork": v.move_artwork}); - if let Some(indices) = &v.indices { - fields["indices"] = json!(indices); + if let Some(selected) = &self.selected { + fields["indices"] = json!(selected.iter().map(|(index, _)| index).collect::>()); } Some(fields) } @@ -311,28 +324,33 @@ impl StackDialog for RearrangeArtboardsDialog { /// ([`place`]). pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; - let Some(DialogResult::Ok(values)) = dialogs.with(|host| host.take::()) else { return }; - match &values.indices { - None => match app.run(CMD, values.params()) { - Ok(_) => app.ui.rearrange_artboards_spacing = json!(values.spacing), - Err(e) => app.status(e), - }, - Some(listed) => match wait_for_click(app, listed, values.params()) { - Ok(()) => app.ui.rearrange_artboards_spacing = json!(values.spacing), - Err(e) => app.status(e), - }, + let Some(DialogResult::Ok(RearrangeAnswer { values, document, selected })) = dialogs.with(|host| host.take::()) else { + return; + }; + let applied = if app.session.active().is_none_or(|st| st.uid != document) { + Err(tl!("Rearrange Artboards can only change the document where it was opened.").to_owned()) + } else if let Some(selected) = selected { + wait_for_click(app, &selected, values.params()) + } else { + app.run(CMD, values.params()).map(drop) + }; + match applied { + Ok(()) => app.ui.rearrange_artboards_spacing = json!(values.spacing), + Err(e) => app.status(e), } ctx.request_repaint(); } -/// Rearrange for artboards `listed` with `params`, confirmed: it waits for its click on the canvas, -/// for the active document and the tool in use. -fn wait_for_click(app: &mut VectorcraftApp, listed: &[usize], params: Value) -> Result<(), String> { +/// Rearrange the originally selected artboards in their current row order when the canvas is clicked. +fn wait_for_click(app: &mut VectorcraftApp, selected: &[(usize, u32)], mut params: Value) -> Result<(), String> { let st = app.session.active().ok_or_else(|| "no document".to_string())?; - let ids: Vec = listed.iter().filter_map(|i| st.doc.artboards.get(*i)).map(|a| a.id).collect(); - if ids.len() != listed.len() { - return Err("no such artboard".into()); + let wanted: std::collections::HashSet<_> = selected.iter().map(|&(_, id)| id).collect(); + let (indices, ids): (Vec<_>, Vec<_>) = + st.doc.artboards.iter().enumerate().filter_map(|(index, a)| wanted.contains(&a.id).then_some((index, a.id))).unzip(); + if ids.len() != selected.len() { + return Err(tl!("An artboard selected when the dialog opened was removed.").to_owned()); } + params["indices"] = json!(indices); let (doc, tool) = (st.uid, app.session.tool_id().to_string()); app.ui.rearrange_placement = Some(RearrangePlacement { doc, tool, params, ids, armed: false }); app.status(PLACE_HINT); @@ -471,6 +489,77 @@ mod tests { app.dialogs().unwrap().with(|host| host.open_dialogs().last().and_then(|d| d.fields.clone())).unwrap() } + fn check_rearrange_stays_in_opening_document(selected: bool) { + let mut app = app(3); + app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("document.activate", json!({"index": 0})).unwrap(); + if selected { + app.select_tool("artboard"); + open_selected(&mut app, &[0, 2]); + } else { + open_from_menu(&mut app); + } + set(&app, &[("layout", json!("row")), ("order", json!("rightToLeft")), ("spacing", json!(37))]).unwrap(); + + app.run("document.activate", json!({"index": 1})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, destination); + let before = origins(&app); + let undo = app.session.active().unwrap().history.undo.len(); + let spacing = app.ui.rearrange_artboards_spacing.clone(); + ok(&mut app); + assert_eq!(origins(&app), before, "OK leaves the other tab's artboards in place"); + assert!(app.ui.rearrange_placement.is_none(), "the other tab cannot start placement"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.rearrange_artboards_spacing, spacing); + } + + #[test] + fn rearrange_opening_for_all_artboards_leaves_a_new_tab_untouched() { + check_rearrange_stays_in_opening_document(false); + } + + #[test] + fn rearrange_opening_for_selected_artboards_cannot_place_in_a_new_tab() { + check_rearrange_stays_in_opening_document(true); + } + + #[test] + fn rearrange_opening_keeps_the_intended_artboards_after_rows_move() { + let mut app = app(3); + app.select_tool("artboard"); + let st = app.session.active().unwrap(); + let source = [st.doc.artboards[0].id, st.doc.artboards[2].id]; + open_selected(&mut app, &[0, 2]); + set(&app, &[("layout", json!("row")), ("spacing", json!(20))]).unwrap(); + app.run("artboard.reorder", json!({"index": 0, "to": 1})).unwrap(); + let before = origins(&app); + let undo = app.session.active().unwrap().history.undo.len(); + + ok(&mut app); + let placement = app.ui.rearrange_placement.as_ref().expect("the original artboards wait for placement"); + assert_eq!(placement.ids, source); + assert_eq!(placement.params["indices"], json!([1, 2])); + place(&mut app, Some(Point::new(700.0, 300.0))); + assert_eq!(origins(&app), [before[0], (700.0, 300.0), (820.0, 300.0)]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + + #[test] + fn rearrange_opening_does_not_place_a_deleted_artboards_replacement() { + let mut app = app(3); + app.select_tool("artboard"); + open_selected(&mut app, &[0]); + app.run("artboard.delete", json!({"index": 0})).unwrap(); + let before = origins(&app); + let undo = app.session.active().unwrap().history.undo.len(); + + ok(&mut app); + assert!(app.ui.rearrange_placement.is_none(), "the replacement row is not a placement target"); + assert_eq!(origins(&app), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + /// #681: the menu item opens the dialog; each setting reaches `artboard.rearrange`, as one undo step; a /// setting the layout makes meaningless is refused. #[test] @@ -537,7 +626,7 @@ mod tests { assert_eq!(shown["indices"], json!([0, 2])); let (title, count) = app.dialogs().unwrap().with(|host| { let d = host.get::().unwrap(); - (d.values.indices.is_some(), d.artboards) + (d.selected.is_some(), d.artboards) }); assert_eq!((title, count), (true, 2), "Rearrange for the 2 selected artboards"); set(&app, &[("layout", json!("row"))]).unwrap(); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 3768c182d2..e872c841a7 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -2126,7 +2126,7 @@ fn assign_tab( let total: usize = rows.iter().map(|r| r["from"].as_array().map_or(0, Vec::len)).sum(); // Reduction and the preserve rules apply to art (a colour group alone has a row per colour). if art { - Row::new().show(ui, |ui, _| { + Row::new().wrap(true).show(ui, |ui, _| { let counts: Vec> = std::iter::once(Entry::new(0, Label::from(tl!("Auto")))) .chain((1..=total).map(|n| Entry::new(n, Label::from(n.to_string())))) .collect(); diff --git a/crates/ui-egui/src/dialogs/recolor/fixture.rs b/crates/ui-egui/src/dialogs/recolor/fixture.rs index b254285a5b..47e0f722d6 100644 --- a/crates/ui-egui/src/dialogs/recolor/fixture.rs +++ b/crates/ui-egui/src/dialogs/recolor/fixture.rs @@ -15,6 +15,50 @@ use serde_json::{Value, json}; use super::{Fields, GROUP_ACTION, KIND, RecolorDialog}; use crate::VectorcraftApp; +#[test] +fn preserve_grays_can_be_clicked_in_a_narrow_localized_dialog() { + use egui::accesskit::Role; + use egui::{RawInput, pos2, vec2}; + + for lang in ["de", "el"] { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.session.prefs.interface_language = lang.into(); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(540.0, 500.0)); + let mut time = 0.0; + let mut draw = |app: &mut VectorcraftApp, events| { + time += 0.25; + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }) + }; + draw(&mut app, vec![]); + app.run("ui.recolorDialog", json!({})).unwrap(); + for _ in 0..5 { + draw(&mut app, vec![]); + } + let out = draw(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + let label = crate::i18n::t("Grays"); + let bounds = nodes + .iter() + .find(|(_, node)| node.role() == Role::CheckBox && node.label() == Some(label)) + .and_then(|(_, node)| node.bounds()) + .unwrap_or_else(|| panic!("{lang} has no Preserve Grays checkbox")); + let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32); + draw(&mut app, vec![Event::PointerMoved(at)]); + for pressed in [true, false] { + draw(&mut app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + draw(&mut app, vec![]); + let preserves_grays = app.dialogs().unwrap().with(|host| host.get::().map(|d| d.fields.bool("preserveGrays"))); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(preserves_grays, Some(true), "the pointer click toggles Preserve Grays in {lang}"); + } +} + /// Recolor Artwork over an app, in a window-sized fixture. pub(crate) struct Recolor { fixture: Fixture, diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 0dd9edc19b..e7afa2c556 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -37,10 +37,13 @@ use crate::{VectorcraftApp, io}; pub(super) mod color_table; pub const KIND: &str = "saveForWeb"; +const WRONG_DOCUMENT: &str = "Save for Web belongs to the document that opened the dialog."; /// What the open dialog's pump keeps between frames: data keyed by its inputs, never UI state. #[derive(Default)] pub(crate) struct WebExport { + document: Option, + opening: Arc<()>, /// The rendering of the art before optimisation, by [`render_key`]. render: Option<(String, Result, String>)>, /// The Original pane's picture, `None` while the dialog has not been given the current rendering's. @@ -183,11 +186,20 @@ fn settings_of(options: &SaveForWebOptions, table: &Value, kept: &Value, path: O /// Open on the document's active artboard, keeping the other remembered settings. pub fn open(app: &mut VectorcraftApp) -> Result { - app.session.active().ok_or("no document")?; + let document = app.session.active().ok_or("no document")?.uid; let host = app.dialogs().ok_or("no window")?; let ctx = app.ui_ctx.clone().ok_or("no window")?; + // Settle a completed opening while its settings and source are still available. + if let Some(DialogResult::Ok(result)) = host.with(|dialog| dialog.take::()) { + finish(app, result); + } let s = remembered(app); - app.web_export = WebExport { table: serde_json::to_value(&s.color_table).unwrap_or_default(), kept: kept_of(&s), ..WebExport::default() }; + app.web_export = WebExport { + document: Some(document), + table: serde_json::to_value(&s.color_table).unwrap_or_default(), + kept: kept_of(&s), + ..WebExport::default() + }; let (name, artboards, slices) = { let st = app.session.active().ok_or("no document")?; let slices: Vec = st @@ -449,6 +461,10 @@ fn on_dialog(host: &craft::ui::shell::WindowDialogs, f: impl FnOnce(&mut Host host.with(|h| h.get_mut::().map(f)) } +fn on_original_document(app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|active| app.web_export.document == Some(active.uid)) +} + /// Answers the open dialog once per frame: its result when it closed, else its requests. /// Colour requests (the matte, a palette cell) are routed by the host-wide colour picker routing; /// a palette cell's pick is applied to the table by [`take_palette_pick`]. @@ -456,13 +472,32 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(host) = app.dialogs() else { return }; match host.with(|h| h.take::()) { Some(DialogResult::Ok(result)) => return finish(app, result), - Some(_) => { + Some(_) if on_dialog(&host, |_| ()).is_none() => { app.web_export = WebExport::default(); return; } - None => {} + _ => {} } let Some(asked) = on_dialog(&host, Asked::take) else { return }; + if !on_original_document(app) { + let restore = asked.tables.iter().any(|event| matches!(event.edit, ColorTableEdit::Restore)); + if restore { + color_table::restore(&mut app.web_export.table); + let marks = color_table::marks(&app.web_export.table); + on_dialog(&host, |dialog| dialog.set_marks(marks)); + } + let requested = asked.path.is_some() + || asked.browser + || asked.optimize_open + || asked.optimize.is_some() + || asked.tables.iter().any(|event| !matches!(event.edit, ColorTableEdit::Restore)); + update_presets(app, &host, asked.presets, restore); + if requested { + on_dialog(&host, HostedSaveForWeb::cancel_requests); + app.status(tl!(WRONG_DOCUMENT).to_owned()); + } + return; + } // The framework keeps the result line while the settings are the ones it found; the art is the app's. let art = art_key(app); if app.web_export.optimized.is_some() && optimized_result(&app.web_export.optimized, &art).is_none() { @@ -474,12 +509,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { } let marks = color_table::marks(&app.web_export.table); on_dialog(&host, |d| d.set_marks(marks)); - let refresh_presets = !asked.tables.is_empty() || !asked.presets.is_empty(); - store_presets(app, asked.presets); - if refresh_presets { - let presets = dialog_presets(app); - on_dialog(&host, |d| d.set_presets(presets)); - } + update_presets(app, &host, asked.presets, !asked.tables.is_empty()); if asked.optimize_open { let bytes = optimize_start(app, &asked.options); on_dialog(&host, |d| d.answer_optimize_start(bytes)); @@ -565,6 +595,10 @@ pub(crate) fn take_palette_pick(app: &mut VectorcraftApp, parent: DialogId, key: let Some(options) = host.with(|h| h.get_mut_by_id::(parent).map(|d| d.current().clone())) else { return false; }; + if !on_original_document(app) { + app.status(tl!(WRONG_DOCUMENT).to_owned()); + return true; + } let rgb = |c: Srgba| { let [r, g, b, _] = c.to_rgba().0; [r, g, b] @@ -578,7 +612,8 @@ pub(crate) fn take_palette_pick(app: &mut VectorcraftApp, parent: DialogId, key: } /// Runs what the preset list asked for and shows a failure in the status line. -fn store_presets(app: &mut VectorcraftApp, events: Vec) { +fn update_presets(app: &mut VectorcraftApp, host: &craft::ui::shell::WindowDialogs, events: Vec, table_changed: bool) { + let refresh = table_changed || !events.is_empty(); for event in events { let r = match event { WebPresetEvent::Saved(p) => { @@ -595,6 +630,10 @@ fn store_presets(app: &mut VectorcraftApp, events: Vec) { app.status(e); } } + if refresh { + let presets = dialog_presets(app); + on_dialog(host, |d| d.set_presets(presets)); + } } /// Saves the preset `from` under `to`, then deletes `from`. @@ -692,7 +731,18 @@ fn ask_path(app: &mut VectorcraftApp, host: &craft::ui::shell::WindowDialogs, id pick = pick.filter(f.name.clone(), &extensions); } // A cancelled panel has no path. + let opening = app.web_export.opening.clone(); file_asks::ask(app, pick, Owner::Free, move |app, picked| { + if !Arc::ptr_eq(&opening, &app.web_export.opening) { + return Ok(Value::Null); + } + if !on_original_document(app) { + if let Some(host) = app.dialogs() { + on_dialog(&host, HostedSaveForWeb::cancel_requests); + } + app.status(tl!(WRONG_DOCUMENT).to_owned()); + return Ok(Value::Null); + } match picked.first_path() { Some(path) => answer_path(app, id, &key, path), None => { @@ -715,9 +765,13 @@ fn answer_path(app: &VectorcraftApp, id: DialogId, key: &str, path: PathBuf) { /// The dialog closed with Save… or Done: the settings are remembered, and with a path the files are /// written. Failures show in the status line; the dialog has closed. fn finish(app: &mut VectorcraftApp, result: SaveForWebResult) { + let wrong_document = result.path.is_some() && !on_original_document(app); let table = std::mem::take(&mut app.web_export.table); let kept = std::mem::take(&mut app.web_export.kept); app.web_export = WebExport::default(); + if wrong_document { + return app.status(tl!(WRONG_DOCUMENT).to_owned()); + } let params = settings_of(&result.options, &table, &kept, None); if let Err(e) = app.run("webExport.settings", params.clone()) { return app.status(e); diff --git a/crates/ui-egui/src/dialogs/save_for_web/tests.rs b/crates/ui-egui/src/dialogs/save_for_web/tests.rs index 85cba5810d..b030f110db 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/tests.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests.rs @@ -312,6 +312,49 @@ fn save_remembers_and_writes_and_done_only_remembers() { assert!(!dir.join("Untitled-1.png").exists()); } +#[test] +fn save_for_web_download_waits_for_the_original_drawing() { + let dir = vectorcraft_testkit::temp_dir("sfw-original-download"); + let (mut app, downloads) = app(&dir, true); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "format", json!("png24")); + app.run("file.new", json!({"width": 26, "height": 20, "name": "Other drawing"})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 26, "height": 20})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + confirm(&mut app); + + assert!(downloads.borrow().is_empty(), "the other drawing is never downloaded"); + assert!(is_open(&app)); + assert_eq!(fields(&app)["format"], "png24"); + app.run("document.activate", json!({"index": 0})).unwrap(); + save(&mut app); + assert_eq!(downloads.borrow().len(), 1); +} + +#[test] +fn save_for_web_does_not_write_another_drawing_when_the_picker_returns() { + let dir = vectorcraft_testkit::temp_dir("sfw-original-picker"); + let (mut app, _) = app(&dir, false); + app.run("file.new", json!({"width": 26, "height": 20, "name": "Other drawing"})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 26, "height": 20})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "format", json!("png24")); + let ctx = app.ui_ctx.clone().unwrap(); + let dialog = id(&app); + host(&app).with(|h| h.confirm_by_id(&ctx, dialog)); + settle(&mut app); + app.run("document.activate", json!({"index": 1})).unwrap(); + answer_saves(&mut app); + settle(&mut app); + + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); + assert!(is_open(&app)); + app.run("document.activate", json!({"index": 0})).unwrap(); + save(&mut app); + assert!(dir.join("Untitled-1.png").exists()); +} + /// The remembered Transparency Dither, which the dialog does not show, reaches the file Save writes /// and stays remembered after Done. #[test] diff --git a/crates/ui-egui/src/dialogs/save_library.rs b/crates/ui-egui/src/dialogs/save_library.rs index 0e69c82c15..9f06db67b8 100644 --- a/crates/ui-egui/src/dialogs/save_library.rs +++ b/crates/ui-egui/src/dialogs/save_library.rs @@ -36,6 +36,7 @@ fn document_name(app: &VectorcraftApp) -> Option { /// Open the dialog for `library`: `extra` rows sit under the Name row. `names` are the items selected in the /// panel. pub(super) fn open(app: &mut VectorcraftApp, library: Library, names: Vec, extra: Vec) -> Result { + let document = app.session.active().ok_or("no document open")?.uid; let name = document_name(app).ok_or("no document open")?; let ctx = app.ui_ctx.clone().ok_or("no window")?; let Library { key, title, cmd, only, ext, has_user_dir } = library; @@ -64,7 +65,15 @@ pub(super) fn open(app: &mut VectorcraftApp, library: Library, names: Vec(owner)); + if app.session.active().is_none_or(|st| Some(st.uid) != document) { + return Err(tl!("Return to the original drawing to save its library").into()); + } + save(app, cmd, ext, result) + }; super::host::open_held(app, dialog, ok).ok_or("no window")?; Ok(Value::Null) } @@ -105,3 +114,45 @@ fn save(app: &mut VectorcraftApp, cmd: &str, ext: fn(&DialogFields) -> String, r Ok(_) => Ok(()), } } + +#[cfg(test)] +mod tests { + use super::super::{save_symbol_library, tests_export}; + use serde_json::json; + + #[test] + fn save_library_waits_for_the_drawing_that_opened_it() { + let (mut app, written) = tests_export::app(1); + app.run("symbol.new", json!({"name": "Source Mark"})).unwrap(); + save_symbol_library::open(&mut app, vec!["Source Mark".into()]).unwrap(); + tests_export::set(&mut app, "saveTo", json!("file")); + tests_export::set(&mut app, "name", json!("Marks")); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.ellipse", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + app.run("symbol.new", json!({"name": "Other Mark"})).unwrap(); + let error = tests_export::try_confirm(&mut app).expect_err("Save Library must refuse the other drawing"); + assert!(error.contains("original drawing"), "{error}"); + assert!(written.borrow().is_empty()); + assert_eq!(tests_export::fields(&app)["name"], "Marks"); + app.run("document.activate", json!({"index": 0})).unwrap(); + tests_export::try_confirm(&mut app).unwrap(); + assert_eq!(written.borrow().len(), 1); + } + + #[test] + fn reopening_save_library_uses_the_new_drawings_draft() { + let (mut app, written) = tests_export::app(1); + app.run("symbol.new", json!({"name": "Source Mark"})).unwrap(); + save_symbol_library::open(&mut app, vec!["Source Mark".into()]).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.ellipse", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + app.run("symbol.new", json!({"name": "Other Mark"})).unwrap(); + save_symbol_library::open(&mut app, vec!["Other Mark".into()]).unwrap(); + tests_export::set(&mut app, "saveTo", json!("file")); + tests_export::set(&mut app, "name", json!("Other Marks")); + tests_export::try_confirm(&mut app).unwrap(); + let output = written.borrow(); + assert_eq!(output.len(), 1); + assert!(output[0].0.contains("Other Marks")); + } +} diff --git a/crates/ui-egui/src/dialogs/smart_punctuation.rs b/crates/ui-egui/src/dialogs/smart_punctuation.rs index 7e49996eba..9e68c0507b 100644 --- a/crates/ui-egui/src/dialogs/smart_punctuation.rs +++ b/crates/ui-egui/src/dialogs/smart_punctuation.rs @@ -48,7 +48,9 @@ fn params_of(result: &ParamResult) -> Value { /// Report Results on, lists how many of each chosen replacement it made. pub fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let selected = app.session.active().is_some_and(|d| !d.selection.is_empty()); + let source = app.session.active().ok_or("no document")?; + let document = source.uid; + let selected = !source.selection.is_empty(); let mut params: Vec = options() .into_iter() .map(|(key, _, label)| Param::new(key, label, ParamKind::bool(matches!(key, "quotes" | "dashes" | "ellipsis")))) @@ -66,7 +68,13 @@ pub fn open(app: &mut VectorcraftApp) -> Result { if !selected { dialog.set_field("scope", FieldValue::Text("document".into())); } + let owner = egui::Id::unique((COMMAND, "opening-drawing")); + ctx.data_mut(|data| data.insert_temp(owner, document)); let ok = move |app: &mut VectorcraftApp, result: &ParamResult| -> Result<(), String> { + let document = ctx.data(|data| data.get_temp::(owner)); + if app.session.active().is_none_or(|st| Some(st.uid) != document) { + return Err(tl!("Return to the original drawing to replace its punctuation").into()); + } let r = app.run(COMMAND, params_of(result))?; result.remember(&ctx); if result.fields.bool("report") == Some(true) { @@ -165,4 +173,39 @@ mod tests { ok(&mut app); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); } + + #[test] + fn smart_punctuation_waits_for_its_original_drawing() { + let (mut app, source) = app_with_text("a--b"); + app.run("select.none", json!({})).unwrap(); + open(&mut app).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let other = app.run("text.create", json!({"x": 10, "y": 40, "text": "c--d", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + let error = super::super::tests_export::try_confirm(&mut app).expect_err("Smart Punctuation must refuse the other drawing"); + assert!(error.contains("original drawing"), "{error}"); + assert_eq!(plain(&app, other), "c--d"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + assert_eq!(entry(&app, COMMAND).unwrap().fields.unwrap()["scope"], "document"); + app.run("document.activate", json!({ "index": 0 })).unwrap(); + ok(&mut app); + assert_eq!(plain(&app, source), "a–b"); + } + + #[test] + fn reopened_smart_punctuation_applies_in_its_new_drawing() { + let (mut app, source) = app_with_text("a--b"); + app.run("select.none", json!({})).unwrap(); + open(&mut app).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let other = app.run("text.create", json!({"x": 10, "y": 40, "text": "c--d", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.none", json!({})).unwrap(); + open(&mut app).unwrap(); + let (ctx, id) = (app.ui_ctx.clone().unwrap(), entry(&app, COMMAND).unwrap().id); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + assert_eq!(plain(&app, other), "c–d"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(plain(&app, source), "a--b"); + } } diff --git a/crates/ui-egui/src/dialogs/swatch_options.rs b/crates/ui-egui/src/dialogs/swatch_options.rs index 6def4534d4..107da9afa1 100644 --- a/crates/ui-egui/src/dialogs/swatch_options.rs +++ b/crates/ui-egui/src/dialogs/swatch_options.rs @@ -40,12 +40,16 @@ pub const KIND: &str = "swatchOptions"; /// What a dialog says when the window has no dialog host to open it on. pub(super) const NO_WINDOW: &str = "no window"; +const PREVIEW_LABEL: &str = "Swatch Options"; /// The open Swatch Options dialog: the held dialog, the swatch it edits and the parameters its preview last ran with. #[derive(Clone, Debug)] pub(crate) struct Open { /// The held dialog. pub(crate) id: DialogId, + opening: Arc<()>, + document: u64, + preview_reset: u64, /// The name of the swatch being edited. swatch: String, /// The `swatch.edit` parameters of the running preview; `None` while no preview runs. @@ -287,24 +291,43 @@ fn stops_of(g: &GradientPaint) -> GradientStops { /// Opens the held dialog over swatch `swatch`: OK is one `swatch.edit` undo step, Cancel rolls the preview back. fn launch(app: &mut VectorcraftApp, swatch: &str, fields: DialogFields, rows: Vec) -> Result { + let document = app.session.active().ok_or("no drawing")?.uid; let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?; let dialog = hosted(&ctx, KIND, tl!("Swatch Options"), fields, rows, true); - let edited = swatch.to_owned(); - let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { - // The edit replaces the preview, so the preview is dropped first. + if owns_preview(app) { let _ = app.session.cancel_interaction(); + } + let opening = Arc::new(()); + let cancelled = Arc::clone(&opening); + let ok = |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { + let open = app.ui.swatch_options.as_ref().ok_or("the Swatch Options dialog is gone")?; + if app.session.active().is_none_or(|st| st.uid != open.document) { + return Err(tl!("Return to the original drawing to edit this swatch").into()); + } + let edited = open.swatch.clone(); + // The edit replaces the preview, so the preview is dropped first. + if owns_preview(app) { + let _ = app.session.cancel_interaction(); + } else if app.session.in_interaction() { + app.keep_typing()?; + if app.session.in_interaction() { + return Err(tl!("Finish the current edit before changing this swatch").into()); + } + } app.run("swatch.edit", edit_params(&edited, &answer.fields))?; app.ui.swatch_options = None; Ok(()) }; - let cancel = |app: &mut VectorcraftApp| { - if app.session.in_interaction() { - let _ = app.session.cancel_interaction(); + let cancel = move |app: &mut VectorcraftApp| { + if app.ui.swatch_options.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled)) { + if owns_preview(app) { + let _ = app.session.cancel_interaction(); + } + app.ui.swatch_options = None; } - app.ui.swatch_options = None; }; let id = open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(Box::new(cancel)) }).ok_or(NO_WINDOW)?; - app.ui.swatch_options = Some(Open { id, swatch: swatch.to_owned(), last: None }); + app.ui.swatch_options = Some(Open { id, opening, document, preview_reset: app.session.tool_resets(), swatch: swatch.to_owned(), last: None }); Ok(Value::Null) } @@ -318,26 +341,49 @@ fn edit_params(swatch: &str, fields: &DialogFields) -> Value { /// Shows the edit on the canvas while the Preview box is on and drops it when it goes off. It runs each pass; the /// parameters it last previewed with are remembered, so a pass that changes nothing runs nothing. +fn owns_preview(app: &VectorcraftApp) -> bool { + app.ui.swatch_options.as_ref().is_some_and(|open| { + open.last.is_some() + && open.preview_reset == app.session.tool_resets() + && app + .session + .active() + .is_some_and(|st| st.uid == open.document && st.interaction.as_ref().is_some_and(|interaction| interaction.label == PREVIEW_LABEL)) + }) +} + pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { - let Some((id, swatch, last)) = app.ui.swatch_options.as_ref().map(|o| (o.id, o.swatch.clone(), o.last.clone())) else { return }; + let Some(open) = app.ui.swatch_options.as_ref().filter(|open| app.session.active().is_some_and(|st| st.uid == open.document)) else { return }; + let (id, swatch, last) = (open.id, open.swatch.clone(), open.last.clone()); + let owns_preview = owns_preview(app); correct(app, id); let Some((previewing, fields)) = with_dialog(app, id, |d| (d.is_previewing(), d.fields().clone())) else { return }; let want = previewing.then(|| edit_params(&swatch, &fields)); if let Some(params) = &want { // A refused OK drops the interaction under an unchanged dialog: the preview starts again. - if want == last && app.session.in_interaction() { + if want == last && owns_preview { return; } - let begun = app.session.in_interaction() || app.begin_interaction("Swatch Options").map_err(|e| app.status(e)).is_ok(); + if !owns_preview && app.session.in_interaction() { + if let Err(e) = app.keep_typing() { + app.status(e); + return; + } + if app.session.in_interaction() { + return; + } + } + let begun = owns_preview || app.begin_interaction(PREVIEW_LABEL).map_err(|e| app.status(e)).is_ok(); if begun && let Err(e) = app.session.preview("swatch.edit", params) { app.status(e.to_string()); } - } else if last.is_some() { + } else if owns_preview { // The Preview box went off: the document shows its own colour again. Nothing to report if none was open. let _ = app.session.cancel_interaction(); } if let Some(open) = app.ui.swatch_options.as_mut() { open.last = want; + open.preview_reset = app.session.tool_resets(); } } @@ -530,6 +576,81 @@ mod tests { (sw.paint.color(), sw.spot, sw.global) } + #[test] + fn swatch_options_refuses_a_matching_name_in_another_drawing() { + let (ctx, mut app) = setup(); + app.run("swatch.new", json!({"name": "Twin", "color": "#123456"})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("swatch.new", json!({"name": "Twin", "color": "#6789ab"})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap(); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let other = swatch(&app, "Twin"); + activate(&mut app, 0); + open(&mut app, "Twin").unwrap(); + set(&app, &ctx, &[("name", json!("Source paint")), ("preview", json!(false))]); + activate(&mut app, 1); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(KIND); + dialogs.with(|h| h.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.in_interaction(), "the other drawing's edit stays active"); + assert_eq!(swatch(&app, "Twin"), other); + + app.session.cancel_interaction().unwrap(); + activate(&mut app, 0); + dialogs.with(|h| h.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.active().unwrap().doc.swatch("Source paint").is_some()); + } + + #[test] + fn swatch_options_waits_for_another_preview_in_the_original_drawing() { + let (ctx, mut app) = setup(); + app.run("swatch.new", json!({"name": "Editable", "color": "#123456"})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap(); + open(&mut app, "Editable").unwrap(); + set(&app, &ctx, &[("name", json!("Renamed")), ("preview", json!(false))]); + app.session.begin_interaction("An independent preview").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(KIND); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.in_interaction()); + assert!(app.session.active().unwrap().doc.swatch("Renamed").is_none()); + + app.session.cancel_interaction().unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + dialogs.with(|host| host.confirm_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.active().unwrap().doc.swatch("Renamed").is_some()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + + #[test] + fn reopening_swatch_options_rolls_back_the_replaced_preview() { + let (ctx, mut app) = setup(); + for name in ["First color", "Second color"] { + app.run("swatch.new", json!({"name": name, "color": "#123456"})).unwrap(); + } + open(&mut app, "First color").unwrap(); + set(&app, &ctx, &[("name", json!("Temporary name")), ("preview", json!(true))]); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.active().unwrap().doc.swatch("Temporary name").is_some()); + open(&mut app, "Second color").unwrap(); + assert!(app.session.active().unwrap().doc.swatch("First color").is_some()); + assert!(app.session.active().unwrap().doc.swatch("Temporary name").is_none()); + + set(&app, &ctx, &[("name", json!("New name")), ("preview", json!(false))]); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.confirm_by_id(&ctx, dialog_id(KIND))); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.active().unwrap().doc.swatch("New name").is_some()); + assert!(app.session.active().unwrap().doc.swatch("First color").is_some()); + } + #[test] fn swatch_options_shows_and_corrects_both_warnings() { assert_eq!(shown_warnings(ColorPanelMode::RgbSliders), (true, true), "RGB shows both"); diff --git a/crates/ui-egui/src/dialogs/tests_package.rs b/crates/ui-egui/src/dialogs/tests_package.rs index e0d0e87e72..5dec578456 100644 --- a/crates/ui-egui/src/dialogs/tests_package.rs +++ b/crates/ui-egui/src/dialogs/tests_package.rs @@ -224,6 +224,37 @@ fn package_dialog(app: &mut VectorcraftApp, out: &str) { set(app, "folder", json!(out)).unwrap(); } +#[test] +fn package_opening_drawing_is_required_before_saving_or_packaging() { + let dir = Folder::new("opening-drawing"); + let mut app = saved(&dir); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let destination = app.session.active().unwrap().uid; + let destination_path = dir.path("destination.vectorcraft"); + app.run("document.save", json!({"path": destination_path})).unwrap(); + let saved_destination = std::fs::read(&destination_path).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap(); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, source); + let out = dir.path("out"); + package_dialog(&mut app, &out); + app.run("document.activate", json!({"index": 1})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, destination); + let accepted = press_ok(&mut app); + assert!(app.session.active().unwrap().is_dirty(), "Package leaves the different drawing unsaved"); + assert_eq!(std::fs::read(&destination_path).unwrap(), saved_destination); + let package = std::path::Path::new(&out).join("card Folder"); + assert!(!package.exists()); + assert!(!accepted && matches!(held_state(&app), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(press_ok(&mut app)); + assert!(package.join("card.vectorcraft").is_file()); + assert!(!package.join("destination.vectorcraft").exists()); +} + #[test] fn package_is_written_in_the_background_as_it_is_at_once() { let dir = Folder::new("background"); @@ -609,3 +640,28 @@ fn package_without_a_location_says_so() { assert!(matches!(held_state(&app), Some(HeldOk::Refused(_))), "OK is refused with its reason"); assert!(with_package(&app, |_| ()).is_some(), "stays open"); } + +#[test] +fn package_save_first_does_not_save_a_different_drawing() { + let mut app = windowed(); + let picker = crate::tests::picks::scripted(&mut app); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.packageDialog", json!({})).unwrap(); + assert_eq!(confirm::open_question(&app).unwrap().2, "file.saveAs"); + + app.run("document.activate", json!({"index": 1})).unwrap(); + answer_question(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + crate::tests::picks::poll(&mut app, &ctx); + + assert!(picker.requests().is_empty(), "Package in drawing A must never start Save As for drawing B"); + assert_eq!(app.ui.status, "This dialog was opened in a different document."); + + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.packageDialog", json!({})).unwrap(); + answer_question(&mut app); + crate::tests::picks::poll(&mut app, &ctx); + assert_eq!(picker.requests().len(), 1, "approval in the opening drawing starts Save As"); +} diff --git a/crates/ui-egui/src/dialogs/tests_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index 089296ae7a..d7d5249f6a 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -277,6 +277,40 @@ fn the_presets_manager_exports_to_a_file_named_after_the_preset() { } } +#[test] +fn the_presets_manager_imports_browser_contents_and_desktop_paths() { + use super::perspective_presets::{self, Action}; + use vectorcraft_engine::cmd::perspgrid::PRESET_FORMAT; + + let mut app = app(); + let picker = crate::tests_picks::scripted(&mut app); + let ctx = window(&app); + let fixture = |name: &str| json!({"format": PRESET_FORMAT, "presets": [{"name": name}]}).to_string(); + app.run("ui.perspectivePresetsDialog", json!({})).unwrap(); + let default = "[1P-Normal View]"; + + perspective_presets::run(&mut app, Action::Import, default).unwrap(); + picker.answer_contents(&[("Browser.vcperspective", fixture("Browser").as_bytes())]); + crate::tests_picks::poll(&mut app, &ctx); + assert!(app.session.perspective_preset("Browser").is_some(), "the selected browser file adds its preset"); + assert_eq!(field(&app, "selected"), json!("Browser")); + + let dir = vectorcraft_testkit::TempDir::new("perspective-presets-picker"); + let file = dir.join("Desktop.vcperspective"); + std::fs::write(&file, fixture("Desktop")).unwrap(); + perspective_presets::run(&mut app, Action::Import, "Browser").unwrap(); + picker.answer(&[file.to_str().unwrap()]); + crate::tests_picks::poll(&mut app, &ctx); + assert!(app.session.perspective_preset("Desktop").is_some(), "the selected desktop file adds its preset"); + assert_eq!(field(&app, "selected"), json!("Desktop")); + + perspective_presets::run(&mut app, Action::Import, "Desktop").unwrap(); + picker.cancel(); + crate::tests_picks::poll(&mut app, &ctx); + assert_eq!(app.session.prefs.perspective_presets.len(), 2); + assert_eq!(field(&app, "selected"), json!("Desktop")); +} + #[test] fn perspective_preset_menus_list_the_views_of_each_type() { let app = app(); diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 5fa18d848b..183d6f1056 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -206,6 +206,34 @@ fn done_keeps_the_settings_without_printing_and_bad_settings_keep_the_dialog() { assert!(!crate::menus::enabled(&app, "print.printerSetup"), "the mock has no settings to open"); } +#[test] +fn print_does_not_send_or_update_the_other_drawing() { + let (mut app, jobs) = app(); + app.run("file.new", json!({"width": 180, "height": 100, "name": "Other drawing"})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 50, "height": 30})).unwrap(); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + + activate(&mut app, 0); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "copies", json!(2)); + activate(&mut app, 1); + confirm(&mut app); + + assert!(jobs.borrow().is_empty()); + let other = app.session.active().unwrap(); + assert!(other.doc.print_setup.is_none()); + assert_eq!(other.history.undo.len(), undo); + assert!(is_open(&app)); + assert_eq!(fields(&app)["copies"], 2); + activate(&mut app, 0); + confirm(&mut app); + assert_eq!(jobs.borrow().len(), 1); + assert_eq!(pages(&jobs.borrow()[0].2), 6); + assert!(!is_open(&app)); +} + /// A print queue that puts each page on the paper as it is, as `lp` does. struct UprightQueue(Jobs); @@ -482,6 +510,23 @@ fn a_print_preset_keeps_the_scale_link() { assert_eq!(fields(&app)["scale"], json!({"width": 30, "height": 70, "linked": false})); } +#[test] +fn print_preset_changes_survive_a_paused_preview() { + let (mut app, jobs) = app(); + app.run("print.presets.save", json!({"name": "Apart", "settings": {"scaling": "custom", "scale": {"width": 30, "height": 90}}})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + app.run("file.new", json!({"width": 90, "height": 90})).unwrap(); + set(&mut app, "preset", json!("Apart")); + let ctx = ctx(&app); + super::print::pump(&mut app, &ctx); + assert_eq!(scale(&app), (30.0, 90.0, false)); + assert!(jobs.borrow().is_empty()); + app.run("document.activate", json!({"index": 0})).unwrap(); + super::print::pump(&mut app, &ctx); + assert_eq!(scale(&app), (30.0, 90.0, false)); +} + #[test] fn a_scale_set_through_the_dialog_keeps_the_percentage_it_changes() { let (mut app, _) = app(); diff --git a/crates/ui-egui/src/dialogs/text_import.rs b/crates/ui-egui/src/dialogs/text_import.rs index e86f27fef8..9ebccddec8 100644 --- a/crates/ui-egui/src/dialogs/text_import.rs +++ b/crates/ui-egui/src/dialogs/text_import.rs @@ -97,8 +97,12 @@ fn starting_fields(app: &VectorcraftApp) -> DialogFields { pub fn open(app: &mut VectorcraftApp, params: &Value) -> Value { let ctx = app.ui_ctx.clone().unwrap_or_default(); let dialog = HostedParamDialog::new(&ctx, KIND, starting_fields(app), build).held_ok(); + let drawing = crate::place::import_options_drawing(app, params); let params = params.clone(); - open_held(app, dialog, move |app, result| confirm(app, ¶ms, result)); + open_held(app, dialog, move |app, result| { + crate::place::check_import_options_drawing(app, drawing)?; + confirm(app, ¶ms, result) + }); json!({ "dialog": KIND }) } @@ -244,6 +248,23 @@ mod tests { assert_eq!(app.ui.text_import["removeLineReturns"], true, "remembered for the next file"); } + #[test] + fn normal_text_place_options_wait_for_the_original_drawing() { + 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(b"one\r\ntwo")}); + assert_eq!(app.run("file.place", file).unwrap()["dialog"], KIND); + host::set(&app, KIND, "removeLineReturns", json!(true)); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let error = host::confirm(&mut app, KIND).expect_err("the other drawing must not receive the file"); + assert!(error.contains("original drawing"), "{error}"); + assert!(placed_text(&app).is_none()); + assert_eq!(host::fields(&app, KIND)["removeLineReturns"], true); + app.run("document.activate", json!({"index": 0})).unwrap(); + host::confirm(&mut app, KIND).unwrap(); + assert_eq!(placed_text(&app).as_deref(), Some("one two")); + } + /// Every character set is a choice: one confirmed last comes back on the next text file and /// decodes it, an unknown remembered value falls back to Unicode, and with Show Import Options /// off the remembered set is the one the file is placed with. diff --git a/crates/ui-egui/src/dialogs/tools.rs b/crates/ui-egui/src/dialogs/tools.rs index ae0d4723bf..3d798cb1e3 100644 --- a/crates/ui-egui/src/dialogs/tools.rs +++ b/crates/ui-egui/src/dialogs/tools.rs @@ -30,9 +30,20 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) { } // Graph tool click: the graph's size. "graph" => { + let Some(document) = app.session.active().map(|doc| doc.uid) else { + app.status("Open a document before drawing a graph"); + return; + }; let at = click_of(&p).map_or(Point::new(0.0, 0.0), |c| c.at); let graph_type = p.get("type").cloned().unwrap_or(json!("column")); - let params = [("type", graph_type), ("x", json!(at.x)), ("y", json!(at.y)), ("width", json!(200)), ("height", json!(150))]; + let params = [ + ("type", graph_type), + ("x", json!(at.x)), + ("y", json!(at.y)), + ("width", json!(200)), + ("height", json!(150)), + ("__doc", json!(document)), + ]; let params = params.into_iter().map(|(k, v)| (k.to_string(), v)).collect(); let r = command::open(app, "graph.create", "Graph", params); reported(app, r); @@ -99,3 +110,50 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) { _ => {} } } + +#[cfg(test)] +mod tests { + use craft::ui::dialog::dialog_id; + use vectorcraft_engine::Session; + + use super::*; + + fn confirm_graph(app: &mut VectorcraftApp) { + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + for _ in 0..2 { + host.with(|h| h.confirm_by_id(&ctx, dialog_id("graph.create"))); + super::super::host::pump(app, &ctx); + } + } + + #[test] + fn graph_size_without_a_document_keeps_the_source_status() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + open_tool_dialog(&mut app, "graph", json!({"x": 40.0, "y": 30.0})); + + assert_eq!(app.ui.status, "Open a document before drawing a graph"); + assert!(!app.any_dialog_open()); + } + + #[test] + fn graph_size_does_not_draw_in_a_different_document() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let opening = app.session.doc().unwrap().doc.clone(); + let click = json!({"x": 40.0, "y": 30.0, "type": "column"}); + open_tool_dialog(&mut app, "graph", click.clone()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let other = app.session.doc().unwrap().doc.clone(); + + confirm_graph(&mut app); + + assert_eq!(app.session.doc().unwrap().doc, other, "confirmation leaves the other document unchanged"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, opening); + open_tool_dialog(&mut app, "graph", click); + confirm_graph(&mut app); + let doc = &app.session.doc().unwrap().doc; + assert_eq!(doc.layers[0].children().unwrap().len(), 1); + } +} diff --git a/crates/ui-egui/src/dialogs/tracing_presets.rs b/crates/ui-egui/src/dialogs/tracing_presets.rs index d8ff9b4d49..2db0261f2b 100644 --- a/crates/ui-egui/src/dialogs/tracing_presets.rs +++ b/crates/ui-egui/src/dialogs/tracing_presets.rs @@ -89,6 +89,8 @@ pub(crate) struct Manager { data: RowsData, /// What a button asked for, taken by [`pump`]. action: Option, + /// Identifies this opening when an Import picker finishes later. + import_owner: Arc<()>, } impl StackDialog for Manager { @@ -180,8 +182,13 @@ impl StackDialog for Manager { /// Open the presets manager on `selected` (default: the first preset, Default). pub(crate) fn open(app: &mut VectorcraftApp, selected: Option<&str>) { - let manager = - Manager { list: image_trace::presets(app), selected: selected.unwrap_or("Default").to_string(), data: RowsData::of(app), action: None }; + let manager = Manager { + list: image_trace::presets(app), + selected: selected.unwrap_or("Default").to_string(), + data: RowsData::of(app), + action: None, + import_owner: Arc::new(()), + }; match app.dialogs() { Some(dialogs) => { dialogs.with(|host| host.open(manager)); @@ -251,10 +258,11 @@ fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Result<(), Strin select(app, next.as_deref().unwrap_or("Default")); } Action::Import => { + let Some(owner) = with_manager(app, |m| Arc::clone(&m.import_owner)) else { return Ok(()) }; let name = file_asks::filter_name(crate::i18n::current(), "Tracing presets"); let request = PickRequest::open("tracingPresets").filter(name, TRACE_PRESET_EXTS); // The answer, or its failure, reaches the status bar from the continuation; nothing is pending here. - let _ = file_asks::ask(app, request, Owner::Free, picked); + let _ = file_asks::ask(app, request, Owner::Free, move |app, answer| picked(app, answer, ImportSource::Picker(owner))); } Action::Export => { crate::io::save_command_output(app, "imageTrace.presets.export", TRACE_PRESET_FORMAT, json!({}), |_, _| Ok(Value::Null))?; @@ -263,20 +271,37 @@ fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Result<(), Strin Ok(()) } -/// The file Import… picked: a path on the desktop, the file's bytes on the web. -fn picked(app: &mut VectorcraftApp, picked: Picked) -> Result { - match picked { - Picked::Paths(paths) => { - if let Some(path) = paths.first() { - open_path(app, &path.to_string_lossy())?; - } +enum ImportSource { + FileOpen, + Picker(Arc<()>), +} + +impl ImportSource { + fn matches(&self, manager: &Manager) -> bool { + match self { + Self::FileOpen => true, + Self::Picker(owner) => Arc::ptr_eq(owner, &manager.import_owner), } - Picked::Contents(files) => { - if let Some((_, bytes)) = files.first() { - open_file(app, bytes)?; + } + + fn select(&self, app: &VectorcraftApp, name: &str) { + let _ = with_manager(app, |manager| { + if self.matches(manager) { + manager.selected = name.to_string(); } - } - _ => {} + }); + } +} + +/// The file Import… picked, a path on the desktop or the file's bytes on the web. +fn picked(app: &mut VectorcraftApp, picked: Picked, source: ImportSource) -> Result { + let file = match picked { + Picked::Paths(paths) => paths.first().map(|path| file_contents(app, json!({ "path": path.to_string_lossy() }))).transpose()?, + Picked::Contents(files) => files.first().map(|(_, bytes)| checked_contents(bytes)).transpose()?, + _ => None, + }; + if let Some(file) = file { + open_import(app, file, source)?; } Ok(Value::Null) } @@ -294,6 +319,7 @@ fn import_file(app: &mut VectorcraftApp, file: &Value) -> Result<(Value, Vec, + source: ImportSource, } /// The Replace question. Its own type, so the host keeps its answer apart from every other prompt's. @@ -301,22 +327,23 @@ pub(crate) struct ReplacePresets(pub(crate) StandardPrompt); crate::dialogs::confirm::wrapped_dialog!(ReplacePresets, StandardPrompt, REPLACE_KIND); -/// Asks whether the import of `file` replaces the saved presets `skipped` kept, over the manager -/// when it is open. -fn ask_replace(app: &VectorcraftApp, skipped: &[Value], file: Value) { +/// Asks whether the import of `file` replaces the saved presets `skipped` kept. It opens over the +/// manager if the import targets that opening. +fn ask_replace(app: &VectorcraftApp, skipped: &[Value], file: Value, source: ImportSource) { let names: Vec