diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 12151afc1e..a39260ee91 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -496,6 +496,7 @@ fn art_for_artboard_copy_takes_artwork_larger_than_artboard_or_with_bleed() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); // Shape spanning (190..300) x (50..150): 10pt on Artboard 0, 100pt on Artboard 1. let neighbor_art = d.alloc_id(); @@ -523,6 +524,7 @@ fn artboard_for_bounds_edge_cases_and_tie_breaks() { show_video_safe_areas: false, video_ruler_pixel_aspect_ratio: 1.0, color: None, + guide_label: None, }); // 1. Artwork whose center is outside all boards, but overlaps Artboard 0 most: diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 587f60eb11..fbe46f41c8 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -97,6 +97,7 @@ mod style; pub use style::styled_node; pub mod stylelib; mod svgfilter; +pub use svgfilter::MAX_IMPORT_BYTES as MAX_SVG_FILTER_IMPORT_BYTES; mod swatch; pub mod swatchlib; pub(crate) mod symboledit; diff --git a/crates/engine/src/cmd/compositefonts.rs b/crates/engine/src/cmd/compositefonts.rs index bbb5d43dc6..1815e33349 100644 --- a/crates/engine/src/cmd/compositefonts.rs +++ b/crates/engine/src/cmd/compositefonts.rs @@ -27,7 +27,7 @@ pub const EXTS: &[&str] = &["vccomposite"]; const EXPORT: &str = "type.compositeFonts.export"; /// The largest file Import reads, in bytes. -const MAX_FILE_BYTES: usize = 4 << 20; +pub const MAX_FILE_BYTES: usize = 4 << 20; /// The keys a part may give. const PART_KEYS: [&str; 7] = ["font", "style", "size", "baseline", "hScale", "vScale", "scaleAtCenter"]; @@ -349,7 +349,12 @@ fn import(s: &mut Session, p: &Value) -> Result { let too_large = || bad(C, "the file is larger than 4 MB"); let bytes = match given { (Some(path), None, None) if !path.trim().is_empty() => read_file_head(path, MAX_FILE_BYTES + 1)?, - (None, Some(text), None) => text.as_bytes().to_vec(), + (None, Some(text), None) => { + if text.len() > MAX_FILE_BYTES { + return Err(too_large()); + } + text.as_bytes().to_vec() + } (None, None, Some(b64)) => { if b64.len() > MAX_FILE_BYTES / 3 * 4 + 4 { return Err(too_large()); diff --git a/crates/engine/src/cmd/compositefonts/tests.rs b/crates/engine/src/cmd/compositefonts/tests.rs index 751cb49ef0..a83be2df95 100644 --- a/crates/engine/src/cmd/compositefonts/tests.rs +++ b/crates/engine/src/cmd/compositefonts/tests.rs @@ -27,6 +27,27 @@ fn steps(s: &Session) -> usize { s.doc().unwrap().history.undo.len() } +/// Inline and encoded files share the same raw byte limit; rejection changes no fonts or history. +#[test] +fn import_file_byte_boundaries_preserve_the_document_on_refusal() { + let mut s = session(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font("Existing")]})).unwrap(); + let before = steps(&s); + let large = " ".repeat(super::MAX_FILE_BYTES + 1); + for params in [json!({"data": large}), json!({"dataBase64": vectorcraft_format::base64_encode(large.as_bytes())})] { + let error = s.execute("type.compositeFonts.import", ¶ms).unwrap_err(); + assert!(error.to_string().contains("the file is larger than 4 MB"), "{error}"); + assert_eq!(names(&s), ["Existing"]); + assert_eq!(steps(&s), before); + } + let mut exact = json!({"compositeFonts": [font("Imported")]}).to_string(); + exact.extend(std::iter::repeat_n(' ', super::MAX_FILE_BYTES - exact.len())); + let imported = s.execute("type.compositeFonts.import", &json!({"data": exact, "apply": false})).unwrap(); + assert_eq!(imported["fonts"][0]["name"], "Imported"); + assert_eq!(names(&s), ["Existing"]); + assert_eq!(steps(&s), before); +} + fn text(s: &Session, id: u64) -> vectorcraft_doc::TextObject { match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { NodeKind::Text(t) => (**t).clone(), diff --git a/crates/engine/src/cmd/svgfilter.rs b/crates/engine/src/cmd/svgfilter.rs index 43af8bce35..263003d96f 100644 --- a/crates/engine/src/cmd/svgfilter.rs +++ b/crates/engine/src/cmd/svgfilter.rs @@ -8,6 +8,8 @@ //! editing one adds a copy to the document under the default's name, and from then on that copy is //! the filter of that name. Deleting the copy lists the default again. +use std::borrow::Cow; + use serde_json::{Value, json}; use vectorcraft_doc::{Appearance, Document, SvgFilter}; use vectorcraft_render::effects::svg_filter::defaults::{DEFAULT_FILTERS, default_filter}; @@ -17,7 +19,7 @@ use super::fileio::{absolute_path, read_file_head}; use super::{CommandSpec, Result, Session, bad, cmd, has_doc, text_param}; /// The largest SVG file Import SVG Filter reads. -const MAX_IMPORT_BYTES: usize = 16 << 20; +pub const MAX_IMPORT_BYTES: usize = 16 << 20; pub fn specs() -> Vec { vec![ @@ -53,7 +55,7 @@ pub fn specs() -> Vec { "Import SVG Filter…", [], None, - "{path?|svg?} add the elements of an SVG file (at most 16 MB; not SVGZ; its first 256 filters) or of SVG text to the document's SVG filters, as one undo step; a filter whose name the document already has, and one svgFilter.define would refuse, is left out; objects whose effect names an added filter draw with it → {added: [names…], skipped: count, filters}", + "{path?|svg?|dataBase64?} add the elements of an SVG file (at most 16 MB; not SVGZ; its first 256 filters), SVG text or base64-encoded file bytes to the document's SVG filters, as one undo step; file bytes keep their UTF-8, BOM-marked UTF-16 or declared ISO 8859-1 encoding. A filter whose name the document already has, and one svgFilter.define would refuse, is left out; objects whose effect names an added filter draw with it → {added: [names…], skipped: count, filters}", has_doc, import ), @@ -197,13 +199,19 @@ fn delete(s: &mut Session, p: &Value) -> Result { Ok(json!({ "filters": filters_json(&s.doc()?.doc) })) } -/// The bytes of `p`'s `path` (an SVG file, read up to [`MAX_IMPORT_BYTES`]) or `svg`. -fn import_bytes(p: &Value, cmd: &str) -> Result> { - let bytes = match (text_param(p, "path", cmd)?, text_param(p, "svg", cmd)?) { +/// The bytes of `p`'s `path`, `svg` text or `dataBase64`, up to [`MAX_IMPORT_BYTES`]. Inline SVG borrows its UTF-8 bytes. +fn import_bytes<'a>(p: &'a Value, cmd: &str) -> Result> { + let bytes = match (text_param(p, "path", cmd)?, text_param(p, "svg", cmd)?, text_param(p, "dataBase64", cmd)?) { // One byte past the cap is enough to refuse the file below. - (Some(path), _) => read_file_head(&absolute_path(path), MAX_IMPORT_BYTES + 1)?, - (None, Some(svg)) => svg.as_bytes().to_vec(), - _ => return Err(bad(cmd, "give `path`, an SVG file, or `svg`, SVG text")), + (Some(path), _, _) => Cow::Owned(read_file_head(&absolute_path(path), MAX_IMPORT_BYTES + 1)?), + (None, Some(svg), _) => Cow::Borrowed(svg.as_bytes()), + (None, None, Some(encoded)) => { + if vectorcraft_format::base64_decoded_len(encoded) > MAX_IMPORT_BYTES as u64 { + return Err(bad(cmd, format!("the SVG file is larger than {MAX_IMPORT_BYTES} bytes"))); + } + Cow::Owned(vectorcraft_format::base64_decode(encoded).ok_or_else(|| bad(cmd, "bad dataBase64"))?) + } + _ => return Err(bad(cmd, "give `path`, an SVG file, `svg`, SVG text, or `dataBase64`, file bytes")), }; if bytes.len() > MAX_IMPORT_BYTES { return Err(bad(cmd, format!("the SVG file is larger than {MAX_IMPORT_BYTES} bytes"))); diff --git a/crates/engine/src/tests/svgfilter.rs b/crates/engine/src/tests/svgfilter.rs index 611c9bfd1f..41ed696c08 100644 --- a/crates/engine/src/tests/svgfilter.rs +++ b/crates/engine/src/tests/svgfilter.rs @@ -34,6 +34,39 @@ fn names(s: &mut Session) -> Vec { const BLUR: &str = r#""#; const SHIFT: &str = r#""#; +#[test] +fn byte_import_keeps_svg_encodings_and_uses_one_undo_step() { + let svg = r#""#; + let utf16: Vec = [0xff, 0xfe].into_iter().chain(svg.encode_utf16().flat_map(u16::to_le_bytes)).collect(); + let latin1: Vec = format!("{svg}").chars().map(|c| c as u8).collect(); + for bytes in [svg.as_bytes().to_vec(), utf16, latin1] { + let mut s = session(); + let out = run(&mut s, "svgFilter.import", json!({"dataBase64": vectorcraft_format::base64_encode(&bytes)})); + assert_eq!(out["added"], json!(["café"])); + assert_eq!(names(&mut s), ["café"]); + assert_eq!(steps(&s), 1); + run(&mut s, "edit.undo", json!({})); + assert!(names(&mut s).is_empty()); + } +} + +#[test] +fn byte_import_refuses_invalid_oversized_and_compressed_files_without_an_edit() { + let mut s = session(); + assert!(err(&mut s, "svgFilter.import", json!({"dataBase64": "!"})).contains("dataBase64")); + assert!(err(&mut s, "svgFilter.import", json!({"dataBase64": 3})).contains("must be a string")); + let mut inline = "é".repeat(8 << 20); + inline.push(' '); + assert!(err(&mut s, "svgFilter.import", json!({"svg": inline})).contains("larger than 16777216 bytes")); + assert!(names(&mut s).is_empty()); + assert_eq!(steps(&s), 0); + for bytes in [vec![0xff], vec![b' '; (16 << 20) + 1], vectorcraft_svg::compress("")] { + assert!(s.execute("svgFilter.import", &json!({"dataBase64": vectorcraft_format::base64_encode(&bytes)})).is_err()); + assert!(names(&mut s).is_empty()); + assert_eq!(steps(&s), 0); + } +} + #[test] fn filters_are_defined_edited_and_deleted_in_one_undo_step_each() { let mut s = session(); diff --git a/crates/ui-egui/src/addons/pathtools/bridge.rs b/crates/ui-egui/src/addons/pathtools/bridge.rs index ffe710633c..76b3627f76 100644 --- a/crates/ui-egui/src/addons/pathtools/bridge.rs +++ b/crates/ui-egui/src/addons/pathtools/bridge.rs @@ -3,6 +3,7 @@ //! circles selected; Keep Originals), which previews on the canvas and runs //! `addon.pathtools.bridge` on OK. +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::UnitKind; use serde_json::{Value, json}; @@ -50,7 +51,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { ("many", FieldValue::Bool(many)), ]); let lengths = general_lengths(app); - dialogs::open(app, &SPEC, fields, move |_| { + dialogs::open(app, &SPEC, fields, move |fields| { let rows = vec![ Param::new("constantGap", tl!("Constant Gap"), ParamKind::bool(false)), Param::number("gap", tl!("Gap:"), GAP, 1.0, 2) @@ -67,7 +68,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { .enabled_when("many", FieldValue::Bool(true)), Param::new("keepOriginals", tl!("Keep Originals"), ParamKind::bool(false)), ]; - ParamDialog::new(COMMAND, tl!("Smooth Bridge"), rows).previews(true) + ParamDialog::new(COMMAND, tl!("Smooth Bridge"), rows).previews(true).values(Bind::bound(fields)) }) } @@ -83,6 +84,80 @@ mod tests { app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() } + fn bridge_app(xs: &[f64]) -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = xs.iter().map(|&x| circle(&mut app, x, 10.0)).collect(); + app.run("select.set", json!({"ids": ids})).unwrap(); + app + } + + fn geometry(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|node| node.kind.clone()).collect() + } + + fn type_number(panel: &mut crate::tests::panel_harness::Panel, label: &str, text: &str) { + panel.click(label); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); + } + + #[test] + fn real_bridge_controls_change_the_preview_and_confirmed_geometry() { + use crate::tests::panel_harness::Panel; + + let mut panel = Panel::new(bridge_app(&[100.0, 124.0]), crate::tests::picks::dialogs); + let before = panel.app().session.doc().unwrap().history.undo.len(); + menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); + panel.frame(); + assert!(!panel.enabled("Reach"), "two circles can be bridged at any distance"); + panel.click("Keep Originals"); + type_number(&mut panel, "Radius", "150"); + let id = dialog_id(&panel.app()); + assert_eq!(read(&panel.app(), id, |f| f.number("radius")), Some(150.0)); + let mut expected = bridge_app(&[100.0, 124.0]); + expected.session.execute(super::COMMAND, &json!({"radius": 150, "keepOriginals": true})).unwrap(); + assert_eq!(geometry(&panel.app()), geometry(&expected)); + assert_eq!(geometry(&panel.app()).len(), 3, "both circles stay beside the bridge"); + + panel.click("Constant Gap"); + type_number(&mut panel, "Gap", "6"); + let params = read(&panel.app(), id, super::params); + assert_eq!(params, json!({"gap": 6.0, "reach": 10.0, "keepOriginals": true})); + let mut expected = bridge_app(&[100.0, 124.0]); + expected.session.execute(super::COMMAND, ¶ms).unwrap(); + let preview = geometry(&panel.app()); + assert_eq!(preview, geometry(&expected)); + panel.click("OK"); + panel.frame(); + assert_eq!(geometry(&panel.app()), preview); + assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before + 1); + assert!(!panel.app().any_dialog_open()); + } + + #[test] + fn real_bridge_reach_edit_reaches_the_command_and_cancel_restores_the_originals() { + use crate::tests::panel_harness::Panel; + + let mut panel = Panel::new(bridge_app(&[100.0, 124.0, 148.0, 300.0]), crate::tests::picks::dialogs); + let original = geometry(&panel.app()); + menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); + panel.frame(); + assert!(panel.enabled("Reach")); + type_number(&mut panel, "Reach", "5"); + let id = dialog_id(&panel.app()); + let params = read(&panel.app(), id, super::params); + assert_eq!(params["reach"], 5.0); + let mut expected = bridge_app(&[100.0, 124.0, 148.0, 300.0]); + expected.session.execute(super::COMMAND, ¶ms).unwrap(); + assert_eq!(geometry(&panel.app()), geometry(&expected)); + panel.click("Cancel"); + panel.frame(); + assert_eq!(geometry(&panel.app()), original); + } + #[test] fn constant_gap_shows_the_gap_and_bridges_many_circles_within_reach() { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); diff --git a/crates/ui-egui/src/addons/pathtools/dashes.rs b/crates/ui-egui/src/addons/pathtools/dashes.rs index 7c90a560a8..48432a81e6 100644 --- a/crates/ui-egui/src/addons/pathtools/dashes.rs +++ b/crates/ui-egui/src/addons/pathtools/dashes.rs @@ -1,6 +1,7 @@ //! Divide into Dashes in the interface: its dialog (dash and gap lengths, Fit to Corners and Ends, //! Remove Gaps), which previews on the canvas and runs `addon.pathtools.divideDashes` on OK. +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; use serde_json::{Value, json}; @@ -36,7 +37,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { ("removeGaps", FieldValue::Bool(true)), ]); let lengths = general_lengths(app); - dialogs::open(app, &SPEC, fields, move |_| { + dialogs::open(app, &SPEC, fields, move |fields| { let rows = vec![ Param::number("dash", tl!("Dash:"), 10.0, 1.0, 2).length(lengths).bounds(Some(*DASHES.start()), Some(*DASHES.end())), Param::number("gap", tl!("Gap:"), 0.0, 1.0, 2).length(lengths).bounds(Some(*GAPS.start()), Some(*GAPS.end())), @@ -45,6 +46,95 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { // PLAN: assumed `Param::enabled_above(key, threshold)` (pl.F4, forms-w1) Param::new("removeGaps", tl!("Remove Gaps"), ParamKind::bool(true)).enabled_above("gap", 0.0), ]; - ParamDialog::new(COMMAND, tl!("Divide into Dashes"), rows).previews(true) + ParamDialog::new(COMMAND, tl!("Divide into Dashes"), rows).values(Bind::bound(fields)).previews(true) }) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::addons::dialogs::tests::{dialog_id, open_item, read}; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let path = app.run("path.create", json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}]})).unwrap(); + app.run("select.set", json!({"ids": [path["id"]]})).unwrap(); + app + } + + fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + crate::dialogs::host::pump(app, ui.ctx()); + } + + fn spans(app: &VectorcraftApp) -> Vec<(f64, f64)> { + app.session.active().unwrap().doc.layers[0] + .children() + .unwrap() + .iter() + .map(|node| { + let bounds = node.geometric_bounds().unwrap(); + (bounds.x0, bounds.x1) + }) + .collect() + } + + /// Real input controls the preview and approval; Cancel restores the undivided path. + #[test] + fn keyboard_and_toggle_edits_control_dashes_preview_cancel_and_ok() { + let mut expected = app(); + expected.run(COMMAND, json!({"dash": 30, "gap": 10, "fit": true, "removeGaps": false})).unwrap(); + let expected = spans(&expected); + assert!(expected.len() > 1); + + for cancel in [true, false] { + let app = app(); + let original = app.session.active().unwrap().doc.clone(); + let selection = app.session.active().unwrap().selection.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, draw); + panel.room(egui::vec2(800.0, 600.0)); + open_item(&mut panel.app(), "Path Precision Tools", "Divide into Dashes…"); + panel.frame(); + panel.click_role("Preview", Role::CHECK_BOX); + let id = dialog_id(&panel.app()); + for (label, key, text, value) in [("Dash", "dash", "30 pt", 30.0), ("Gap", "gap", "10 pt", 10.0)] { + panel.click_role(label, Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + assert_eq!(read(&panel.app(), id, |fields| fields.number(key)), Some(value)); + } + panel.click_role("Fit to Corners and Ends", Role::CHECK_BOX); + panel.click_role("Remove Gaps", Role::CHECK_BOX); + assert_eq!(read(&panel.app(), id, |fields| fields.bool("fit")), Some(true)); + assert_eq!(read(&panel.app(), id, |fields| fields.bool("removeGaps")), Some(false)); + panel.click_role("Preview", Role::CHECK_BOX); + let preview = spans(&panel.app()); + assert_eq!(preview.len(), expected.len()); + assert!(preview.iter().zip(&expected).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6)); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + panel.click(if cancel { "Cancel" } else { "OK" }); + assert!(panel.app().dialogs().unwrap().with(|host| host.open_dialogs().is_empty())); + assert!(!panel.app().session.in_interaction()); + if cancel { + let app = panel.app(); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, original); + assert_eq!(state.selection, selection); + assert_eq!(state.history.undo.len(), undo); + } else { + assert_eq!(spans(&panel.app()), preview); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(panel.app().session.active().unwrap().doc, original); + } + } + } +} diff --git a/crates/ui-egui/src/addons/pathtools/tangent_circle.rs b/crates/ui-egui/src/addons/pathtools/tangent_circle.rs index 94e5daa51c..c890e063da 100644 --- a/crates/ui-egui/src/addons/pathtools/tangent_circle.rs +++ b/crates/ui-egui/src/addons/pathtools/tangent_circle.rs @@ -2,6 +2,7 @@ //! circle to draw, or all), which previews the circles on the canvas and runs //! `addon.pathtools.tangentCircle` on OK. +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use serde_json::{Value, json}; @@ -71,7 +72,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { .enabled_when("twoShapes", FieldValue::Bool(true)), Param::new("circle", tl!("Circle:"), ParamKind::choice(options, Some("0".into()))), ]; - ParamDialog::new(COMMAND, tl!("Tangent Circle"), rows).previews(true) + ParamDialog::new(COMMAND, tl!("Tangent Circle"), rows).values(Bind::bound(fields)).previews(true) }) } @@ -87,6 +88,97 @@ mod tests { app.run("shape.ellipse", json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() } + #[test] + fn actual_radius_and_circle_edits_control_preview_cancel_and_ok() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::patterns::form_dialogs::HostedParamDialog; + + fn app() -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let a = circle(&mut app, 100.0, 100.0, 10.0); + let b = circle(&mut app, 130.0, 100.0, 10.0); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app + } + + fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + crate::dialogs::host::pump(app, ui.ctx()); + } + + fn previewing(app: &VectorcraftApp) -> bool { + let id = dialog_id(app); + app.dialogs().unwrap().with(|host| host.get_by_id::(id).unwrap().is_previewing()) + } + + fn count(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().doc.layers[0].children().unwrap().len() + } + + fn last_bounds(app: &VectorcraftApp) -> vectorcraft_geom::Rect { + app.session.active().unwrap().doc.layers[0].children().unwrap().last().unwrap().geometric_bounds().unwrap() + } + + let mut expected = app(); + expected.run(super::COMMAND, json!({"radius": 20, "circle": 2})).unwrap(); + let expected = last_bounds(&expected); + + for cancel in [true, false] { + let app = app(); + let original = app.session.active().unwrap().doc.clone(); + let selection = app.session.active().unwrap().selection.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, draw); + panel.room(egui::vec2(800.0, 600.0)); + crate::addons::dialogs::tests::open_item(&mut panel.app(), "Path Precision Tools", "Tangent Circle…"); + panel.frame(); + let id = dialog_id(&panel.app()); + assert!(previewing(&panel.app()), "the hosted dialog starts with Preview on"); + assert_eq!(count(&panel.app()), 10); + panel.click_role("Preview", Role::CHECK_BOX); + assert!(!previewing(&panel.app())); + assert_eq!(panel.app().session.active().unwrap().doc, original); + panel.click_role("Radius", Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("20 pt"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + assert_eq!(read(&panel.app(), id, |fields| fields.number("radius")), Some(20.0)); + assert_eq!(count(&panel.app()), 2, "editing with Preview off keeps the originals"); + panel.click_role("Preview", Role::CHECK_BOX); + assert!(previewing(&panel.app())); + assert_eq!(count(&panel.app()), 8); + assert_eq!(read(&panel.app(), id, |fields| fields.int("found")), Some(6)); + panel.click("Circle"); + panel.click("2"); + assert_eq!(read(&panel.app(), id, |fields| fields.text("circle").map(str::to_owned)), Some("2".into())); + assert_eq!(count(&panel.app()), 3); + let actual = last_bounds(&panel.app()); + assert!((actual.x0 - expected.x0).abs() < 1e-6 && (actual.y0 - expected.y0).abs() < 1e-6); + assert!((actual.x1 - expected.x1).abs() < 1e-6 && (actual.y1 - expected.y1).abs() < 1e-6); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + panel.click(if cancel { "Cancel" } else { "OK" }); + assert!(panel.app().dialogs().unwrap().with(|host| host.open_dialogs().is_empty())); + assert!(!panel.app().session.in_interaction()); + if cancel { + let app = panel.app(); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, original); + assert_eq!(state.selection, selection); + assert_eq!(state.history.undo.len(), undo); + } else { + assert_eq!(count(&panel.app()), 3); + assert_eq!(last_bounds(&panel.app()), actual); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(panel.app().session.active().unwrap().doc, original); + } + } + } + #[test] fn tangent_circle_previews_picks_one_cancels_and_runs_on_ok() { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); diff --git a/crates/ui-egui/src/addons/select.rs b/crates/ui-egui/src/addons/select.rs index df48a816f5..6ae9a2ae91 100644 --- a/crates/ui-egui/src/addons/select.rs +++ b/crates/ui-egui/src/addons/select.rs @@ -200,10 +200,7 @@ fn body(ui: &mut Ui, fields: &mut Fields, rows: &[(String, String)], go_to: &mut }); let relations: Vec> = RELATIONS.iter().map(|&(value, text)| Entry::new(value.to_owned(), label(tl!(text)))).collect(); Field::new(label(tl!("Select:"))).show(ui, |ui, _| { - let picked = Select::new(label(tl!("Select:")), Bind::given(fields.relation.clone()), &relations).show(ui).value().cloned(); - if let Some(relation) = picked { - fields.relation = relation; - } + Select::new(label(tl!("Select:")), Bind::bound(&mut fields.relation), &relations).show(ui); }); } diff --git a/crates/ui-egui/src/addons/select/link_status.rs b/crates/ui-egui/src/addons/select/link_status.rs index e7d9c1a509..8e0d033cb6 100644 --- a/crates/ui-egui/src/addons/select/link_status.rs +++ b/crates/ui-egui/src/addons/select/link_status.rs @@ -290,10 +290,7 @@ fn body(ui: &mut Ui, fields: &mut Fields, rows: &[Value]) { TextField::search(label(tl!("Search images")), Bind::bound(&mut fields.search)).show(ui); let shows: Vec> = SHOW.iter().map(|&(value, text)| Entry::new(value.to_owned(), label(tl!(text)))).collect(); Field::new(label(tl!("Show:"))).show(ui, |ui, _| { - let picked = Select::new(label(tl!("Show:")), Bind::given(fields.show.clone()), &shows).show(ui).value().cloned(); - if let Some(show) = picked { - fields.show = show; - } + Select::new(label(tl!("Show:")), Bind::bound(&mut fields.show), &shows).show(ui); }); let visible = shown(rows, &fields.search, &fields.show, &Env::of(ui).folder()); let lines: Vec = visible diff --git a/crates/ui-egui/src/addons/select/link_status/tests.rs b/crates/ui-egui/src/addons/select/link_status/tests.rs index 463f1dd53b..1dfbc67c40 100644 --- a/crates/ui-egui/src/addons/select/link_status/tests.rs +++ b/crates/ui-egui/src/addons/select/link_status/tests.rs @@ -95,6 +95,43 @@ fn selected(app: &VectorcraftApp) -> Vec { ids } +#[test] +fn canceling_a_keyboard_show_filter_restores_all_rows_before_selecting() { + use craft::ui::contract::Role; + + let dir = Folder::new("cancel-show-filter"); + let (app, river, harbour, stamp) = app(&dir); + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 600.0)); + menus::invoke(&mut panel.app(), COMMAND, Value::Null); + panel.frame(); + panel.click_role("Show", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(host(&panel.app(), |host| host.get::().unwrap().fields.show.clone()), "linked"); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + assert_eq!(host(&panel.app(), |host| host.get::().unwrap().fields.show.clone()), "all"); + for name in ["river.png", "harbour.png", "stamp.png"] { + assert!(panel.shows(name), "canceling the filter restores {name}"); + } + panel.click_role("All", Role::BUTTON); + panel.click_role("Zoom to Selection", Role::CHECK_BOX); + panel.click("Select"); + let mut want = vec![river, harbour, stamp]; + want.sort_unstable(); + assert_eq!(selected(&panel.app()), want); + + menus::invoke(&mut panel.app(), COMMAND, Value::Null); + panel.frame(); + panel.click_role("Show", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(host(&panel.app(), |host| host.get::().unwrap().fields.show.clone()), "linked"); + assert!(panel.shows("river.png")); + assert!(!panel.shows("harbour.png") && !panel.shows("stamp.png")); + panel.click("Cancel"); + assert_eq!(selected(&panel.app()), want); +} + #[test] fn the_message_says_what_was_selected_and_what_was_left_out() { assert_eq!(message(&["missing"], 9, &[]), "Selected 9 missing images"); diff --git a/crates/ui-egui/src/addons/select/tests.rs b/crates/ui-egui/src/addons/select/tests.rs index 9e2cb85e04..8f839e3598 100644 --- a/crates/ui-egui/src/addons/select/tests.rs +++ b/crates/ui-egui/src/addons/select/tests.rs @@ -39,6 +39,41 @@ fn names(v: &[&str]) -> Vec { v.iter().map(|s| s.to_string()).collect() } +#[test] +fn canceling_a_keyboard_relation_choice_restores_the_original_selection_rule() { + use craft::ui::contract::Role; + + let mut app = new_app(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let inside = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let edge = app.run("shape.rectangle", json!({"x": 90, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.none", json!({})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 600.0)); + menus::invoke(&mut panel.app(), COMMAND, Value::Null); + panel.frame(); + panel.click_role("Select", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(host(&panel.app(), |host| host.get::().unwrap().fields.relation.clone()), "inside"); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + assert_eq!(host(&panel.app(), |host| host.get::().unwrap().fields.relation.clone()), "overlap"); + panel.click("OK"); + let mut actual = panel.app().session.active().unwrap().selection.objects.clone(); + let mut expected = vec![vectorcraft_doc::NodeId(inside), vectorcraft_doc::NodeId(edge)]; + actual.sort_unstable(); + expected.sort_unstable(); + assert_eq!(actual, expected); + + menus::invoke(&mut panel.app(), COMMAND, Value::Null); + panel.frame(); + panel.click_role("Select", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(host(&panel.app(), |host| host.get::().unwrap().fields.relation.clone()), "inside"); + panel.click("OK"); + assert_eq!(panel.app().session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(inside)]); +} + /// A 100 × 100 document with a Banner artboard at x 150, an object in each artboard, and nothing selected. fn banner() -> (VectorcraftApp, u64) { let mut app = new_app(); diff --git a/crates/ui-egui/src/addons/typetools.rs b/crates/ui-egui/src/addons/typetools.rs index 58e1b005ca..3f73b835ee 100644 --- a/crates/ui-egui/src/addons/typetools.rs +++ b/crates/ui-egui/src/addons/typetools.rs @@ -3,6 +3,7 @@ //! and runs `addon.type.textTweaker` on OK. use craft::menu::Node; +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::UnitKind; use serde_json::{Value, json}; @@ -116,7 +117,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { .enabled_when("shape", FieldValue::Text("random".into())), Param::new("skipSpaces", tl!("Skip Spaces"), ParamKind::bool(true)), ]); - ParamDialog::new(COMMAND, tl!("Text Tweaker"), rows).previews(true) + ParamDialog::new(COMMAND, tl!("Text Tweaker"), rows).values(Bind::bound(fields)).previews(true) }) } diff --git a/crates/ui-egui/src/addons/typetools/tests.rs b/crates/ui-egui/src/addons/typetools/tests.rs index 5e54c38b2f..9c9d0b703c 100644 --- a/crates/ui-egui/src/addons/typetools/tests.rs +++ b/crates/ui-egui/src/addons/typetools/tests.rs @@ -6,13 +6,91 @@ use crate::addons::dialogs::tests::{dialog_id, frame, open_item, read, set}; /// A window's app with one type object, selected. fn app() -> VectorcraftApp { + app_with_text("abc") +} + +fn app_with_text(text: &str) -> VectorcraftApp { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let id = app.run("text.create", json!({"x": 40, "y": 100, "text": "abc", "size": 20})).unwrap()["id"].as_u64().unwrap(); + let id = app.run("text.create", json!({"x": 40, "y": 100, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap(); app.run("select.set", json!({"ids": [id]})).unwrap(); app } +/// The real form controls the same text changes as the command, including attribute-dependent +/// defaults, random seed and whether a space is included. Cancel restores the original text. +#[test] +fn keyboard_and_choice_edits_reach_text_tweaker_preview_and_approval() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::patterns::form_dialogs::HostedParamDialog; + + fn text(app: &VectorcraftApp) -> vectorcraft_doc::TextObject { + let state = app.session.active().unwrap(); + let node = state.doc.node(state.selection.objects[0]).unwrap(); + match &node.kind { + vectorcraft_doc::NodeKind::Text(text) => (**text).clone(), + _ => panic!("selected object is not text"), + } + } + + fn type_number(panel: &mut Panel, label: &str, input: &str) { + panel.click_role(label, Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(input); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + } + + let params = json!({"attribute": "rotation", "from": 10.0, "to": 40.0, "shape": "random", "seed": 42, "skipSpaces": false}); + let mut expected = app_with_text("a b"); + expected.run(super::COMMAND, params.clone()).unwrap(); + let expected = text(&expected); + for cancel in [true, false] { + let app = app_with_text("a b"); + let original = app.session.active().unwrap().doc.clone(); + let selection = app.session.active().unwrap().selection.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(800.0, 700.0)); + open_item(&mut panel.app(), "Type Tools", "Text Tweaker…"); + panel.frame(); + let id = dialog_id(&panel.app()); + assert!(panel.app().dialogs().unwrap().with(|host| host.get_by_id::(id).unwrap().is_previewing())); + panel.click_role("Preview", Role::CHECK_BOX); + assert_eq!(panel.app().session.active().unwrap().doc, original); + panel.click("Attribute"); + panel.click("Character Rotation"); + assert_eq!(read(&panel.app(), id, |fields| (fields.number("from"), fields.number("to"))), (Some(0.0), Some(30.0))); + type_number(&mut panel, "From", "10"); + type_number(&mut panel, "To", "40"); + panel.click("Shape"); + panel.click("Random"); + assert!(panel.enabled("Seed")); + type_number(&mut panel, "Seed", "42"); + panel.click_role("Skip Spaces", Role::CHECK_BOX); + assert_eq!(read(&panel.app(), id, super::params), params); + assert_eq!(panel.app().session.active().unwrap().doc, original, "Preview off leaves the text unchanged"); + panel.click_role("Preview", Role::CHECK_BOX); + assert_eq!(text(&panel.app()), expected, "the real controls reach the same text formatting as automation"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + panel.click(if cancel { "Cancel" } else { "OK" }); + assert!(!panel.app().any_dialog_open()); + assert!(!panel.app().session.in_interaction()); + if cancel { + let app = panel.app(); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, original); + assert_eq!(state.selection, selection); + assert_eq!(state.history.undo.len(), undo); + } else { + assert_eq!(text(&panel.app()), expected); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(panel.app().session.active().unwrap().doc, original); + } + } +} + #[test] fn another_attribute_starts_from_its_own_values() { let mut app = app(); diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index e432b42759..2be7e422af 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -353,7 +353,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy})) } Payload::Style(_) => Ok(()), - Payload::Panel(drag @ PanelDrag::Paint { params, paint, .. }) if !params.is_null() => { + Payload::Panel(drag @ 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) @@ -362,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 Some(mut params) = drag.paint_drop_params(app.session.active().map(|st| st.uid)) else { return Ok(()) }; + let destination = app.session.active().map(|st| st.uid); + if rows.as_ref().is_some_and(|rows| !rows.unlinked_process_color && destination.is_some_and(|uid| uid != rows.document)) + && paint.color().is_some() + && !paint.is_registration() + { + return Err(tl!("A linked color swatch can only be applied in its own document.").into()); + } + let Some(mut params) = drag.paint_drop_params(destination) else { return Ok(()) }; 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 6060043515..1f1934a3f0 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -331,6 +331,63 @@ fn a_swatch_drag_keeps_its_color_after_next_document() { assert_eq!(app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(), source); } +#[test] +fn linked_swatch_drops_stay_in_their_source_document() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + for spot in [false, true] { + for (different_drawing, same_name) in [(false, false), (true, false), (true, true)] { + 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", "global": true, "spot": spot})).unwrap(); + if different_drawing { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + } + if same_name { + app.run("swatch.new", json!({"name": name, "color": "#0000ff", "global": true})).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; + if different_drawing { + 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"); + if different_drawing { + 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 active"); + panel.release(); + let app = panel.app(); + let doc = &app.session.active().unwrap().doc; + let fill = doc.node(target).unwrap().appearance.fill_paint(); + if different_drawing { + assert_eq!(fill, Paint::solid(Color::rgb8(0, 255, 0)), "the destination fill stays unchanged"); + assert_eq!(app.ui.status, "A linked color swatch can only be applied in its own document."); + assert_eq!(doc.swatch(name).and_then(|s| s.paint.color()), same_name.then_some(Color::rgb8(0, 0, 255))); + } else { + assert_eq!(fill, doc.tint_paint(name, 1.0).unwrap(), "the fill remains linked to its swatch"); + } + } + } +} + #[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/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index aef6749bbc..0697d1cf8e 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -9,6 +9,7 @@ use craft::ui::form::Field; use craft::ui::layout_components::Row; use craft::ui::menu::Menu; use craft::ui::pickers::{Select, SelectLook}; +use craft::ui::runtime::env::Env; use craft::ui::style::TypeRole; use craft::ui::text::ZoomField; @@ -47,6 +48,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let busy = busy_labels(app); let (mut zoom_to, mut rotate_to, mut go, mut show_pick, mut stop) = (None, None, None, None, false); + let mut invalid_zoom = None; // The readouts end the bar, the pointer's position and then the timings; a narrow bar leaves out the timings // first, then the position, before the message. let readouts = |ui: &mut Ui, _: &mut BodyCx<'_>| { @@ -73,8 +75,11 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { .side(SideLabel::new().kind(LabelKind::Hidden)) .show(ui, |ui, _| ZoomField::new(tl!("Zoom"), app.canvas_view(), document).scrub(true).show(ui)); // The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom. - if let Some(view) = zoom.inner.and_then(|z| z.view.committed().copied()) { - zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(&view, app.ui_scaling()), print)); + if let Some(zoom) = zoom.inner { + if let Some(view) = zoom.view.committed() { + zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, app.ui_scaling()), print)); + } + invalid_zoom = zoom.invalid_zoom.map(|invalid| invalid.message(&Env::of(ui))); } Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { // Entries are keyed by index: an angle is not a hashable value. @@ -156,6 +161,9 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } + if let Some(message) = invalid_zoom { + app.status(message); + } } /// What the bar shows as work in progress: the running script, then background jobs, opens and places. The first diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index 310eba4a6a..3dbeece787 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -164,7 +164,7 @@ 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 (document, reverts) = (source.uid, source.reverts); 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")?; @@ -195,8 +195,12 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map, object_keys: Op .held_ok(); 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()); + match app.session.active().filter(|st| st.uid == document) { + Some(source) if source.reverts != reverts => { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + None if !object => return Err(tl!("Return to the original drawing to edit its brush").into()), + _ => {} } ok(app, result) }) diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index 2b85bb6394..9bff24d03e 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -135,7 +135,7 @@ pub(crate) struct BulletsDialog { /// The preview from the opening drawing and the interaction that owns its undo snapshot. pub(crate) struct Preview { - document: u64, + document: (u64, u64), live: LivePreview, selection: Option>, } @@ -144,13 +144,13 @@ impl Preview { fn owns_interaction(&self, app: &VectorcraftApp) -> bool { let Some(selection) = &self.selection else { return false }; app.session.active().is_some_and(|state| { - state.uid == self.document + (state.uid, state.reverts) == self.document && state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection)) }) } fn update(&mut self, app: &mut VectorcraftApp, fields: Map) { - let Some(state) = app.session.active().filter(|state| state.uid == self.document) else { return }; + let Some(state) = app.session.active().filter(|state| (state.uid, state.reverts) == self.document) else { return }; if !self.owns_interaction(app) { self.live = LivePreview::default(); self.selection = None; @@ -175,8 +175,11 @@ impl Preview { } return Ok(()); } - if app.session.active().is_none_or(|state| state.uid != self.document) { + let Some(state) = app.session.active().filter(|state| state.uid == self.document.0) else { return Err(tl!("Bullets and Numbering can only change the document where it was opened.").to_owned()); + }; + if state.reverts != self.document.1 { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); } if app.session.in_interaction() && !self.owns_interaction(app) { return Err(tl!("Finish the active edit before applying Bullets and Numbering.").to_owned()); @@ -211,7 +214,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Some(v) => Some(v.as_str().and_then(ListTab::of).ok_or_else(|| format!("`{key}` must be one of {}", TABS.join(", ")))?), }; crate::panels::character::text_style(app).ok_or("select some type first")?; - let document = app.session.active().ok_or("no document")?.uid; + let active = app.session.active().ok_or("no document")?; + let document = (active.uid, active.reverts); // A dialog this one replaces leaves its preview on the type: end it, so the values read below are the document's own. if let Some(old) = app.bullets_preview.take() { old.cancel(app); @@ -617,7 +621,7 @@ impl StackDialog for BulletsDialog { pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { let Some(host) = app.dialogs() else { return }; let Some(mut preview) = app.bullets_preview.take() else { return }; - let active_document = app.session.active().is_some_and(|state| state.uid == preview.document); + let active_document = app.session.active().is_some_and(|state| (state.uid, state.reverts) == preview.document); let lengths = crate::canvas::general_lengths(app); let Some((fields, answer)) = host.with(|h| { h.get_mut::().map(|d| { @@ -804,6 +808,36 @@ mod tests { assert_eq!(first(&app, id).0, Some(ParaList::numbered(NumberStyle::Arabic))); } + #[test] + fn bullets_preview_and_ok_leave_restored_paragraphs_unchanged() { + let (mut app, id) = app(); + let dir = vectorcraft_testkit::TempDir::new("bullets-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let saved = paras(&app, id); + app.run("file.saveAs", json!({"path": dir.join("Paragraphs.vectorcraft")})).unwrap(); + app.run("text.setFormat", json!({"ids": [id], "leftIndent": 19})).unwrap(); + let drawing = app.session.active().unwrap(); + let (uid, reverts) = (drawing.uid, drawing.reverts); + app.run("ui.bulletsAndNumbering", json!({})).unwrap(); + pick_preset(&mut app, "bullet", Some("square")); + frame(&mut app); + assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square))); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let restored = app.session.active().unwrap(); + assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1)); + let undo = restored.history.undo.len(); + frame(&mut app); + assert_eq!(paras(&app, id), saved); + assert!(!app.session.in_interaction()); + press_ok(&mut app); + assert!(with_dialog(&app, |dialog| matches!(dialog.held.state(), Some(HeldOk::Refused(_))))); + assert_eq!(paras(&app, id), saved); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + #[test] fn bullets_cancel_keeps_the_other_drawings_pending_edit() { let (mut app, id) = app(); diff --git a/crates/ui-egui/src/dialogs/check_spelling.rs b/crates/ui-egui/src/dialogs/check_spelling.rs index 4c4d575a6f..30b7d57820 100644 --- a/crates/ui-egui/src/dialogs/check_spelling.rs +++ b/crates/ui-egui/src/dialogs/check_spelling.rs @@ -4,7 +4,7 @@ //! and the pump that runs each action against the document. //! //! The walk's state: -//! - `doc`: uid of the document it started on; another active document ends it +//! - `doc` and `reverts`: the drawing contents it started on; switching or reverting ends it //! - `ids`: object IDs checked (None: entire document; Some(empty): nothing) //! - `layer`: the one object checked while the dialog's Check All Layers is off //! - `skipped`: `(node_id, start, word)` skipped by Ignore, which Change All leaves alone @@ -43,6 +43,8 @@ type Word = (u64, usize, usize, String, String); pub(crate) struct SpellingWalk { /// Uid of the document the walk started on. doc: u64, + /// File Revert generation of the document the walk started on. + reverts: u64, /// The selected objects; None is the whole document, which Some(empty) is not. ids: Option>, /// The one object checked while Check All Layers is off. @@ -66,23 +68,28 @@ fn start(app: &mut VectorcraftApp) -> Result { if app.session.active().is_none() { return Err("no document".into()); } - let (doc, ids) = { + let (doc, reverts, ids) = { let st = app.session.doc().map_err(|e| e.to_string())?; // The selection (groups too: the check goes through the type inside them), or, with // nothing selected, every visible, unlocked type object (the check's default). let selected: Vec = st.selection.objects.iter().map(|n| n.0).collect(); - (st.uid, (!selected.is_empty()).then_some(selected)) + (st.uid, st.reverts, (!selected.is_empty()).then_some(selected)) }; - let mut w = SpellingWalk { doc, ids, ..Default::default() }; + let mut w = SpellingWalk { doc, reverts, ids, ..Default::default() }; advance(app, &mut w, None, 1)?; Ok(w) } /// Open Check Spelling on the active document's type. pub fn open(app: &mut VectorcraftApp) -> Result { - let w = start(app)?; - let items = items_of(app, &w)?; + let mut w = start(app)?; let dialogs = app.dialogs().ok_or("no window")?; + let all_layers = dialogs.with(|host| host.get::().is_none_or(CheckSpellingDialog::all_layers_checked)); + if !all_layers { + w.layer = w.shown.as_ref().map(|word| word.0); + advance(app, &mut w, None, 1)?; + } + let items = items_of(app, &w)?; dialogs.with(|host| match host.get_mut::() { Some(d) => d.restart(items), None => { @@ -109,7 +116,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { }); return; } - if check_doc_uid(app, &w).is_err() { + if check_opening_drawing(app, &w).is_err() { dialogs.with(|host| host.cancel::(ctx)); return; } @@ -417,17 +424,17 @@ fn shown_word(app: &VectorcraftApp, w: &SpellingWalk) -> Option<(u64, usize, usi Some((*id, *start, *end, still_there)) } -/// Fails when the active document is not the one the walk started on. -fn check_doc_uid(app: &VectorcraftApp, w: &SpellingWalk) -> Result<(), String> { - if app.session.active().map(|st| st.uid) != Some(w.doc) { - return Err("the document was switched".into()); +/// Fails when the active drawing's contents are not the ones the walk started on. +fn check_opening_drawing(app: &VectorcraftApp, w: &SpellingWalk) -> Result<(), String> { + if !app.session.active().is_some_and(|st| st.uid == w.doc && st.reverts == w.reverts) { + return Err("the document was switched or reverted".into()); } Ok(()) } /// The word shown, when the walk is still going and on the walk's document. fn shown_text(app: &VectorcraftApp, w: &SpellingWalk) -> Result, String> { - check_doc_uid(app, w)?; + check_opening_drawing(app, w)?; Ok(w.shown.as_ref().map(|s| s.3.clone())) } @@ -969,6 +976,47 @@ mod tests { assert_eq!(plain(&app, b), "fixed y"); } + #[test] + fn reopening_keeps_the_unchecked_all_layers_scope_for_change_all() { + use crate::tests::panel_harness::Panel; + use craft::ui::dialog::StackDialog as _; + + fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + super::pump(app, ui.ctx()); + } + + let _dictionary = crate::testing::custom_dictionary(); + let mut app = app(); + let first = text(&mut app, 50.0, WORD_A); + app.run("layer.new", json!({"name": "Other text"})).unwrap(); + let second = text(&mut app, 100.0, WORD_A); + app.run("select.none", json!({})).unwrap(); + let mut panel = Panel::new(app, draw); + panel.app().run(super::COMMAND, json!({})).unwrap(); + panel.frame(); + let checked = shown(&panel.app()).0; + let other = if checked == first { second } else { first }; + panel.click("Check All Layers"); + panel.app().run(super::COMMAND, json!({})).unwrap(); + panel.frame(); + { + let app = panel.app(); + let ctx = panel.ctx(); + app.dialogs().unwrap().with(|host| { + let dialog = host.get::().unwrap(); + assert!(!dialog.all_layers_checked(), "reopening preserves the chosen scope"); + let id = dialog.id(); + host.set_json_field(ctx, id, "changeTo", json!("fixed")).unwrap(); + }); + } + panel.click("Change All"); + assert_eq!(plain(&panel.app(), checked), "fixed"); + assert_eq!(plain(&panel.app(), other), WORD_A, "the unchecked scope leaves the other layer's text alone"); + } + fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); @@ -1112,13 +1160,75 @@ mod tests { begin(&mut app); // PLAN: the pump's close-on-switch needs the window host fixture of the hosted-dialog - // tests; this drives the guard the pump calls (`check_doc_uid`) through the walk's steps. + // tests; this drives the guard the pump calls (`check_opening_drawing`) through the walk's steps. app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); let mut w = app.spelling.take().unwrap(); - assert!(super::check_doc_uid(&app, &w).is_err()); + assert!(super::check_opening_drawing(&app, &w).is_err()); assert!(super::ignore(&mut app, &mut w).is_err(), "no step runs on another document"); } + #[test] + fn queued_spelling_changes_leave_reverted_text_unchanged() { + use crate::tests::panel_harness::Panel; + use craft::ui::dialog::StackDialog as _; + + // The host files the real button's action; the test decides when the app consumes it. + fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + } + + let _dictionary = crate::testing::custom_dictionary(); + for button in ["Change", "Change All"] { + let mut app = app(); + let saved = format!("{WORD_A} saved"); + let id = text(&mut app, 50.0, &saved); + app.run("select.none", json!({})).unwrap(); + app.services.read = Some(Box::new(|path: &str| std::fs::read(path).map_err(|error| error.to_string()))); + app.services.write = Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|error| error.to_string()))); + let dir = vectorcraft_testkit::TempDir::new("spelling-revert"); + app.run("file.saveAs", json!({"path": dir.join("Spelling.vectorcraft")})).unwrap(); + let state = app.session.active().unwrap(); + let (uid, reverts) = (state.uid, state.reverts); + app.run("text.editRange", json!({"id": id, "start": saved.len(), "end": saved.len(), "insert": " draft"})).unwrap(); + let mut panel = Panel::new(app, draw); + panel.app().run(super::COMMAND, json!({})).unwrap(); + panel.frame(); + let ctx = panel.ctx().clone(); + let set_replacement = |app: &VectorcraftApp| { + app.dialogs().unwrap().with(|host| { + let dialog = host.get::().unwrap().id(); + host.set_json_field(&ctx, dialog, "changeTo", json!("fixed")).unwrap(); + }); + }; + set_replacement(&panel.app()); + panel.click(button); + assert_eq!(plain(&panel.app(), id), format!("{saved} draft"), "the action is still queued"); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + let undo = { + let app = panel.app(); + let state = app.session.active().unwrap(); + assert_eq!((state.uid, state.reverts), (uid, reverts + 1)); + assert_eq!(plain(&app, id), saved, "the same word and local ID were reloaded from the native file"); + state.history.undo.len() + }; + super::pump(&mut panel.app(), &ctx); + assert_eq!(plain(&panel.app(), id), saved, "{button} from the old walk must not edit restored text"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + assert!(panel.app().spelling.is_none(), "the reverted walk is retired"); + assert!(!panel.app().dialogs().unwrap().with(|host| host.is_open::())); + + panel.app().run(super::COMMAND, json!({})).unwrap(); + panel.frame(); + set_replacement(&panel.app()); + panel.click(button); + super::pump(&mut panel.app(), &ctx); + assert_eq!(plain(&panel.app(), id), "fixed saved", "a fresh check can still change the restored text"); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + } + } + #[test] fn check_spelling_ignores_uneditable_text() { let _dictionary = crate::testing::custom_dictionary(); diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index ef5192b032..d8e88f9bae 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -160,7 +160,7 @@ fn slot(dialogs: &mut ColorDialogs) -> &mut Option { /// Open the dialog with every channel at 0, adjusting fills and strokes. pub fn open(app: &mut VectorcraftApp) { - ADJUST.open(app); + Adjust { label: tl!(ADJUST.label), ..ADJUST }.open(app); } /// Previews the open dialog; one line of `dialogs::host::pump`. @@ -217,22 +217,22 @@ fn track(key: &str, x: f32) -> Srgba { fn channels(ui: &mut egui::Ui, fields: &mut DialogFields, _cx: &mut CustomContext) -> egui::Response { super::form::stacked(ui, fields, |ui, fields| { for (key, label) in mode(fields).channels { - percent_row(ui, fields, key, label, |x| track(key, x)); + percent_row(ui, fields, key, tl!(label), |x| track(key, x)); } }) } fn rows() -> Vec { - let modes = MODES.iter().map(|m| (m.id.to_owned(), Label::from(m.label))).collect(); + let modes = MODES.iter().map(|m| (m.id.to_owned(), Label::from(tl!(m.label)))).collect(); let with_model = MODES.iter().map(|m| m.id).filter(|id| *id != GLOBAL); vec![ - Param::new("mode", "Color Mode", ParamKind::choice(modes, Some("rgb".to_owned()))), - Param::new("convert", "Convert", ParamKind::bool(false)).enabled_when_in("mode", with_model), - Param::read_only_text("note", "", "Shifts the tints of global and spot colors; other colors stay.").visible_when("mode", GLOBAL), + Param::new("mode", tl!("Color Mode"), ParamKind::choice(modes, Some("rgb".to_owned()))), + Param::new("convert", tl!("Convert"), ParamKind::bool(false)).enabled_when_in("mode", with_model), + Param::read_only_text("note", "", tl!("Shifts the tints of global and spot colors; other colors stay.")).visible_when("mode", GLOBAL), Param::custom("channels", "Channels", channels).companions(channel_keys()), Param::section("Adjust Options"), - Param::new("fill", "Fill", ParamKind::bool(true)), - Param::new("stroke", "Stroke", ParamKind::bool(true)), + Param::new("fill", tl!("Fill"), ParamKind::bool(true)), + Param::new("stroke", tl!("Stroke"), ParamKind::bool(true)), ] } diff --git a/crates/ui-egui/src/dialogs/color_group_options.rs b/crates/ui-egui/src/dialogs/color_group_options.rs index 36fab4b2a1..45798466fb 100644 --- a/crates/ui-egui/src/dialogs/color_group_options.rs +++ b/crates/ui-egui/src/dialogs/color_group_options.rs @@ -3,7 +3,7 @@ //! as they are. //! //! Fields: `name`. The group being renamed (its name, its place in the list of color groups, the names of -//! its swatches and the uid of its document when the dialog opened) is kept by the dialog's OK. +//! its swatches and the document's identity and revert generation at opening) is kept by the dialog's OK. use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamKind, ParamResult}; use serde_json::{Value, json}; @@ -16,8 +16,9 @@ pub const KIND: &str = "colorGroupOptions"; /// A color group as the dialog found it: what tells it apart from the others, since color groups carry nothing else. struct Identity { - /// The uid of the document the dialog opened on. + /// The document and its saved-content generation when the dialog opened. doc: u64, + reverts: u64, /// The group's place in the document's list of color groups. at: usize, /// The group's name. @@ -40,14 +41,15 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let st = app.session.active().ok_or("no document open")?; let at = st.doc.swatch_groups.iter().position(|g| g.name == group).ok_or_else(|| format!("no colour group `{group}`"))?; let g = &st.doc.swatch_groups[at]; - let identity = Identity { doc: st.uid, at, group: g.name.clone(), swatches: g.swatches.iter().map(|w| w.name.clone()).collect() }; + let identity = + Identity { doc: st.uid, reverts: st.reverts, at, group: g.name.clone(), swatches: g.swatches.iter().map(|w| w.name.clone()).collect() }; let mut fields = DialogFields::new(); fields.set("name", g.name.as_str()); let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?; let rows = vec![Param::new("name", field_label(tl!("Name:")), ParamKind::text(""))]; let dialog = hosted(&ctx, KIND, tl!("Color Group Options"), fields, rows, false); let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { - // Another document or group: it closes as Cancel does and renames nothing. + // A different document, a revert, or a different group closes the draft without renaming. if !same_group(app, &identity) { return Ok(()); } @@ -60,9 +62,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { } /// Whether the dialog's group is still in its document, at the place in the list, under the name -/// and with the swatches it opened with, and that document is the active one. +/// and with the swatches it opened with, and the document is still active and has not been reverted. fn same_group(app: &VectorcraftApp, identity: &Identity) -> bool { - let Some(st) = app.session.active().filter(|st| st.uid == identity.doc) else { return false }; + let Some(st) = app.session.active().filter(|st| st.uid == identity.doc && st.reverts == identity.reverts) else { return false }; st.doc .swatch_groups .get(identity.at) @@ -101,6 +103,42 @@ mod tests { app.session.active().unwrap().history.undo.len() } + #[test] + fn an_old_rename_draft_keeps_the_color_group_restored_by_revert() { + let (ctx, mut app) = app(); + let dir = vectorcraft_testkit::TempDir::new("color-group-options-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("colors.vectorcraft")})).unwrap(); + let color = |app: &VectorcraftApp| app.session.active().unwrap().doc.swatch("Bright Red").unwrap().paint.color(); + let saved_color = color(&app); + let saved_groups = groups(&app); + let st = app.session.active().unwrap(); + let (uid, reverts) = (st.uid, st.reverts); + + app.run("swatch.edit", json!({"name": "Bright Red", "color": "#1784ca"})).unwrap(); + assert_ne!(color(&app), saved_color); + app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap(); + let id = dialog_id(KIND); + app.dialogs().unwrap().with(|h| h.set_json_field(&ctx, id, "name", json!("Old palette draft"))).unwrap(); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let restored = app.session.active().unwrap(); + assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1)); + assert_eq!(color(&app), saved_color); + assert_eq!(groups(&app), saved_groups); + let undo = undo_len(&app); + + crate::tests::picks::answer_dialog(&mut app, id, &[], true); + assert_eq!(groups(&app), saved_groups, "old Color Group Options must leave the restored group named Brights"); + assert_eq!(color(&app), saved_color); + assert_eq!(undo_len(&app), undo); + + app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap(); + ok(&mut app, &ctx, "Restored palette"); + assert!(groups(&app).iter().any(|name| name == "Restored palette")); + assert_eq!(undo_len(&app), undo + 1); + } + /// Whether the dialog is still open. fn is_open(app: &VectorcraftApp) -> bool { app.dialogs().unwrap().with(|h| h.get_by_id::(dialog_id(KIND)).is_some()) diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index f9649382bf..a8c8bf1c0d 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -43,15 +43,23 @@ pub(crate) enum Target { /// The stroke proxy. Stroke, /// The background colour of this artboard. - Artboard { document: u64, index: usize }, + Artboard { document: u64, reverts: u64, index: usize }, /// A colour row `key` of the open dialog `parent`. Answer { parent: DialogId, key: String }, } impl Target { fn in_active_document(&self, app: &VectorcraftApp) -> bool { - let Self::Artboard { document, .. } = self else { return true }; - app.session.active().is_some_and(|st| st.uid == *document) + self.document_problem(app).is_none() + } + + fn document_problem(&self, app: &VectorcraftApp) -> Option<&'static str> { + let Self::Artboard { document, reverts, .. } = self else { return None }; + match app.session.active() { + Some(st) if st.uid == *document && st.reverts == *reverts => None, + Some(st) if st.uid == *document => Some(tl!("The document was reverted. Reopen this dialog to continue.")), + _ => Some(tl!("The active document changed while the Color Picker was open")), + } } } @@ -160,14 +168,14 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let found = index.and_then(|i| { let st = app.session.active()?; let color = st.doc.artboards.get(i)?.color.unwrap_or(Color::WHITE); - Some((st.uid, i, color)) + Some((st.uid, st.reverts, i, color)) }); Some(found.ok_or("no such artboard")?) } }; let color = match (p.get("color"), artboard) { (Some(v), _) => color_value(v).ok_or_else(|| format!("bad color {v}"))?, - (None, Some((_, _, c))) => c, + (None, Some((_, _, _, c))) => c, (None, None) => proxy_color(app, stroke), }; let dialogs = app.dialogs().ok_or("no window")?; @@ -195,18 +203,19 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { dialog = dialog.kept(model_values(&color)); } // The host replaces a picker only for the same document and artboard. - if let Some((document, index, _)) = artboard { + if let Some((document, _, index, _)) = artboard { dialog = dialog.instance((document, index)); } let id = dialogs.with(|h| h.open(dialog)); // A picker the open replaced leaves its preview behind: end it. - let before = app.color_dialogs.pickers.len(); - app.color_dialogs.pickers.retain(|o| o.id != id); - if app.color_dialogs.pickers.len() != before { - let _ = app.session.cancel_interaction(); + if let Some(at) = app.color_dialogs.pickers.iter().position(|open| open.id == id) { + let retired = app.color_dialogs.pickers.remove(at); + if retired.target.in_active_document(app) { + let _ = app.session.cancel_interaction(); + } } let target = match artboard { - Some((document, index, _)) => Target::Artboard { document, index }, + Some((document, reverts, index, _)) => Target::Artboard { document, reverts, index }, None if stroke => Target::Stroke, None => Target::Fill, }; @@ -284,10 +293,10 @@ fn finish( open: &mut Open, result: Option>, ) { - // Switching documents rolls back the source preview. Do not settle it against the new drawing. - if !open.target.in_active_document(app) { + // Switching or restoring a drawing ends the preview belonging to its old contents. + if let Some(reason) = open.target.document_problem(app) { if matches!(result, Some(DialogResult::Ok(_))) { - app.status("The active document changed while the Color Picker was open"); + app.status(reason); } return; } diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index 26e3bf486b..a2d239eb0f 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -287,3 +287,44 @@ fn sampler_above_the_field_previews_and_cancel_restores_the_original() { cancel(&mut app, &ctx); assert_eq!(fill_hex(&app), original); } + +#[test] +fn the_artboard_picker_leaves_restored_artboards_unchanged() { + for accept in [true, false] { + let (mut app, ctx) = app(); + app.run("artboard.new", json!({})).unwrap(); + app.run("artboard.setProps", json!({"index": 1, "color": "#123456"})).unwrap(); + let dir = vectorcraft_testkit::TempDir::new("artboard-picker-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("artboard.setProps", json!({"index": 1, "color": "#ff0000"})).unwrap(); + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + set_hex(&mut app, &ctx, "#abcdef"); + assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#abcdef")); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let restored = artboard_color(&app); + assert_eq!(restored.map(|c| c.to_hex()).as_deref(), Some("#123456")); + let steps = undo_len(&app); + frame(&mut app, &ctx); + assert_eq!(artboard_color(&app), restored); + assert!(!app.session.in_interaction()); + if accept { + ok(&mut app, &ctx); + assert!(app.ui.status.contains("document was reverted")); + } else { + app.begin_interaction("New drawing edit").unwrap(); + cancel(&mut app, &ctx); + assert!(app.session.in_interaction()); + app.session.cancel_interaction().unwrap(); + } + assert_eq!(artboard_color(&app), restored); + assert_eq!(undo_len(&app), steps); + + app.run("ui.colorPicker", json!({"artboard": 1})).unwrap(); + set_hex(&mut app, &ctx, "#abcdef"); + ok(&mut app, &ctx); + assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#abcdef")); + } +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 46d2a44802..81c1d6d1a0 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -88,8 +88,10 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par let token = Arc::new(()); let dialog = { let (key, heading, opening) = (command.to_string(), heading_label(label), params.clone()); - HostedParamDialog::command(&ctx, command, fields, move |_: &mut DialogFields| { - ParamDialog::command(key.clone(), heading.clone(), command_params(&key, &opening, setting)).previews(previews) + HostedParamDialog::command(&ctx, command, fields, move |fields| { + ParamDialog::command(key.clone(), heading.clone(), command_params(&key, &opening, setting)) + .previews(previews) + .values(craft::ui::contract::Bind::bound(fields)) }) // The Preview box starts off, as production's dialogs did (#5360). .preview_off() @@ -590,6 +592,75 @@ mod tests { crate::panels::pattern_options::repeat_fields(app).unwrap()["cols"].as_u64().unwrap() } + #[test] + fn hosted_commands_keep_actual_keyboard_edits_until_ok() { + use egui::accesskit::Role; + use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let type_and_accept = |app: &mut VectorcraftApp, command: &str, name: &str, role: Role, value: &str, preview: bool| { + let ctx = app.ui_ctx.clone().unwrap(); + let time = std::cell::Cell::new(0.0); + let frame = |app: &mut VectorcraftApp, events: Vec| { + ctx.enable_accesskit(); + time.set(time.get() + 0.1); + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time.get()), screen_rect: Some(viewport), ..Default::default() }) + }; + let locate = |app: &mut VectorcraftApp, label: &str, role: Role| { + frame(app, vec![]); + let nodes = frame(app, vec![]).platform_output.accesskit_update.unwrap().nodes; + let node = nodes + .iter() + .map(|(_, node)| node) + .find(|node| { + node.role() == role + && (node.label() == Some(label) + || node.labelled_by().iter().any(|id| nodes.iter().any(|(key, name)| key == id && name.label() == Some(label)))) + }) + .unwrap_or_else(|| panic!("{command}: missing {role:?} {label}")); + let b = node.bounds().unwrap(); + let at = pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + assert!(viewport.contains(at), "{command}: {label} is reachable"); + at + }; + let click = |app: &mut VectorcraftApp, at: Pos2| { + frame(app, vec![Event::PointerMoved(at)]); + for pressed in [true, false] { + frame(app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + frame(app, vec![]); + }; + frame(app, vec![]); + assert_eq!(ctx.content_rect(), viewport); + crate::menus::invoke(app, command, json!({})); + let id = id_of(app); + if preview { + let toggle = locate(app, "Preview", Role::CheckBox); + click(app, toggle); + assert!(app.session.in_interaction(), "{command}: pointer turns Preview on"); + } + let at = locate(app, name, role); + click(app, at); + frame(app, vec![Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }]); + frame(app, vec![Event::Text(value.to_owned())]); + frame(app, vec![Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); + frame(app, vec![]); + let live_columns = preview.then(|| cols(app)); + let ok = locate(app, "OK", Role::Button); + click(app, ok); + frame(app, vec![]); + assert!(app.dialogs().unwrap().with(|h| h.get_by_id::(id).is_none()), "{command}: OK closes the dialog"); + live_columns + }; + + let (mut repeat, _) = prepared("object.repeat.options"); + let preview = type_and_accept(&mut repeat, "object.repeat.options", "Columns", Role::SpinButton, "5", true); + let (mut selection, _) = prepared("select.save"); + type_and_accept(&mut selection, "select.save", "Name", Role::TextInput, "Typed selection", false); + let saved = &selection.session.active().unwrap().doc.saved_selections; + assert_eq!((preview, cols(&repeat), saved.last().map(|s| s.name.as_str())), (Some(5), 5, Some("Typed selection"))); + } + #[test] fn area_type_options_choices_match_the_params_doc() { let doc = vectorcraft_engine::find_command("text.areaOptions").unwrap().params; diff --git a/crates/ui-egui/src/dialogs/composite_fonts.rs b/crates/ui-egui/src/dialogs/composite_fonts.rs index d1f01049d3..61bcee82b7 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts.rs @@ -57,7 +57,7 @@ use egui::{Context, Ui}; use serde_json::{Map, Value, json}; use vectorcraft_doc::text::{COMPOSITE_BASELINE, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX}; use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CustomCharSet}; -use vectorcraft_engine::cmd::compositefonts::{EXTS, file_bytes}; +use vectorcraft_engine::cmd::compositefonts::{EXTS, MAX_FILE_BYTES, file_bytes}; use vectorcraft_text::FontDb; use crate::VectorcraftApp; @@ -137,7 +137,7 @@ enum PartEdit { /// [`COMMAND`] and answers whether the dialog may close. pub struct CompositeFontsDialog { /// The document whose fonts the draft edits. - document: u64, + document: (u64, u64), fonts: Vec, /// The index of the font picked. selected: usize, @@ -172,7 +172,7 @@ pub struct CompositeFontsDialog { pub fn open(app: &mut VectorcraftApp) -> Result { let document = app.session.active().ok_or("no document open")?; let dialogs = app.dialogs().ok_or("no window to show the dialog in")?; - let dialog = CompositeFontsDialog::new(document.uid, document.doc.composite_fonts.to_vec(), crate::font_menu::hold(app)); + let dialog = CompositeFontsDialog::new((document.uid, document.reverts), document.doc.composite_fonts.to_vec(), crate::font_menu::hold(app)); dialogs.with(|host| host.open(dialog)); Ok(Value::Null) } @@ -244,7 +244,7 @@ fn part_mut(f: &mut CompositeFont, at: usize) -> Option<&mut CompositePart> { impl CompositeFontsDialog { /// The dialog over `fonts`, the first picked. - fn new(document: u64, fonts: Vec, hold: PickerHold) -> Self { + fn new(document: (u64, u64), fonts: Vec, hold: PickerHold) -> Self { let mut sample = Map::new(); sample::defaults(&mut sample); CompositeFontsDialog { @@ -862,11 +862,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { }) else { return; }; - if let Some((document, fonts)) = held { - let answer = if app.session.active().is_some_and(|active| active.uid == document) { - app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from) - } else { - Err(Label::from(tl!("Composite Fonts can only change the document where it was opened.").to_owned())) + if let Some(((document, reverts), fonts)) = held { + let answer = match app.session.active().filter(|active| active.uid == document) { + Some(active) if active.reverts == reverts => app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from), + Some(_) => Err(Label::from(tl!("The document was reverted. Reopen this dialog to continue."))), + None => Err(Label::from(tl!("Composite Fonts can only change the document where it was opened."))), }; with_dialog(app, |d| d.held.answer(answer)); } @@ -899,6 +899,12 @@ fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest, owner: Arc<()> /// Reads the fonts of the file picked and gives them to the dialog (Load… or Replace…). fn load_file(app: &mut VectorcraftApp, request: &PresetFileRequest, replace: bool, picked: &Picked) -> Result { + // Refuse the browser's raw file before open_params allocates its base64 representation. + if let Picked::Contents(files) = picked + && files.first().is_some_and(|(_, bytes)| bytes.len() > MAX_FILE_BYTES) + { + return Err(vectorcraft_engine::EngineError::BadParams { cmd: IMPORT.into(), msg: "the file is larger than 4 MB".into() }.to_string()); + } let Some(mut params) = open_params(picked) else { return Ok(Value::Null) }; let browser_name = params.remove("name"); let name = picked diff --git a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs index 2db07b9344..3a56a41c23 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs @@ -127,6 +127,42 @@ fn load_and_replace_accept_a_browser_picked_file() { } } +/// Load and Replace refuse an oversized browser file while preserving both the draft and artwork; +/// a later valid file still reaches that same draft. +#[test] +fn oversized_browser_composite_font_files_leave_the_draft_unchanged() { + for command in [PresetCommands::Load, PresetCommands::Replace] { + let mut app = app(); + let picker = scripted(&mut app); + let ctx = ctx(&app); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("Draft".into())); + let dialogs = app.dialogs().unwrap(); + ctx.run_ui(egui::RawInput::default(), |ui| dialogs.with(|host| host.run(ui))).textures_delta.clear(); + let before = dialog(&mut app, |d| d.fonts.clone()); + let bytes = file_bytes(&before).unwrap(); + let step = steps(&app); + let large = vec![b' '; MAX_FILE_BYTES + 1]; + request(&mut app, command, None); + picker.answer_contents(&[("large.vccomposite", &large)]); + poll(&mut app, &ctx); + assert_eq!( + app.ui.status, + vectorcraft_engine::EngineError::BadParams { cmd: IMPORT.into(), msg: "the file is larger than 4 MB".into() }.to_string() + ); + assert_eq!(dialog(&mut app, |d| d.fonts.clone()), before); + assert!(names(&app).is_empty()); + assert_eq!(steps(&app), step); + request(&mut app, command, None); + picker.answer_contents(&[("valid.vccomposite", &bytes)]); + poll(&mut app, &ctx); + assert!(app.ui.status.contains("valid.vccomposite"), "{}", app.ui.status); + assert_eq!(dialog(&mut app, |d| d.fonts.clone()), before); + assert!(names(&app).is_empty()); + assert_eq!(steps(&app), step); + } +} + fn steps(app: &VectorcraftApp) -> usize { app.session.active().unwrap().history.undo.len() } @@ -575,3 +611,33 @@ fn custom_character_sets_draw_their_characters_and_the_buttons() { assert!(p.shows(name), "{name} is drawn"); } } + +#[test] +fn composite_fonts_approval_does_not_replace_definitions_restored_by_revert() { + let mut app = app(); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("Saved Font".into())); + ok(&mut app).unwrap(); + let dir = vectorcraft_testkit::TempDir::new("composite-fonts-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("Unsaved Font".into())); + ok(&mut app).unwrap(); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("Stale Draft Font".into())); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let restored_step = steps(&app); + assert_eq!(names(&app), ["Saved Font"]); + assert_eq!(ok(&mut app), Err("The document was reverted. Reopen this dialog to continue.".into())); + assert_eq!(names(&app), ["Saved Font"]); + assert_eq!(steps(&app), restored_step); + + cancel(&mut app); + open(&mut app).unwrap(); + dialog(&mut app, |d| d.new_font("Fresh Font".into())); + ok(&mut app).unwrap(); + assert_eq!(names(&app), ["Saved Font", "Fresh Font"]); +} diff --git a/crates/ui-egui/src/dialogs/corners.rs b/crates/ui-egui/src/dialogs/corners.rs index 6eb3d2702c..9c4ee9e4f4 100644 --- a/crates/ui-egui/src/dialogs/corners.rs +++ b/crates/ui-egui/src/dialogs/corners.rs @@ -9,6 +9,7 @@ use std::collections::BTreeSet; +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; use serde_json::{Value, json}; @@ -65,7 +66,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { } let ctx = app.ui_ctx.clone().ok_or("no window")?; let lengths = general_lengths(app); - let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| dialog(fields.text("radii") == Some("relative"), lengths)); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { + dialog(fields.text("radii") == Some("relative"), lengths).values(Bind::bound(fields)) + }); open_held(app, dialog, ok).ok_or("no window")?; Ok(Value::Null) } @@ -341,4 +344,40 @@ mod tests { app.run("edit.undo", json!({})).unwrap(); assert!(!lc(&app).0, "undo brings back absolute radii"); } + + #[test] + fn a_live_radius_edit_applies_to_the_corners_that_opened_the_dialog() { + use craft::ui::testing::Fixture; + use std::cell::RefCell; + use std::rc::Rc; + + let (app, id) = app(); + let app = Rc::new(RefCell::new(app)); + let shown = app.clone(); + let mut fixture = Fixture::new(move |ui| { + let mut app = shown.borrow_mut(); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.run(ui)); + super::super::host::pump(&mut app, ui.ctx()); + }); + fixture.room(egui::vec2(880.0, 720.0)); + let undo = { + let mut app = app.borrow_mut(); + app.ui_ctx = Some(fixture.ctx().clone()); + app.run("ui.corners", json!({"id": id, "corners": [1, 3]})).unwrap(); + app.session.active().unwrap().history.undo.len() + }; + fixture.settle(); + let radius = fixture.by_label("Radius:").or_else(|| fixture.by_label("Radius")).expect("the Corners radius field"); + fixture.click(&radius).key(egui::Key::A, egui::Modifiers::COMMAND).type_text("12").key(egui::Key::Tab, egui::Modifiers::NONE).settle(); + let ok = fixture.by_label("OK").expect("the Corners confirmation button"); + fixture.click(&ok).settle(); + + let mut app = app.borrow_mut(); + assert_eq!(corners(&app, id).0, [0.0, 12.0, 0.0, 12.0], "OK applies the typed radius only to the opening corners"); + assert!(!is_open(&app)); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(corners(&app, id).0, [0.0; 4]); + } } diff --git a/crates/ui-egui/src/dialogs/effect_params.rs b/crates/ui-egui/src/dialogs/effect_params.rs index 5876d9265e..10028d3c4b 100644 --- a/crates/ui-egui/src/dialogs/effect_params.rs +++ b/crates/ui-egui/src/dialogs/effect_params.rs @@ -103,15 +103,22 @@ pub(crate) fn effect_params(cx: &EffectCx, fields: &DialogFields) -> Vec } } -/// One row per default of an effect without a builder: the JSON type of the default decides the -/// kind, and the rows follow the effect's parameter documentation. +/// One row per default of a built-in effect without a builder: the JSON type of the default decides +/// the kind, labels use the UI language, and the rows follow the effect's parameter documentation. pub(super) fn generic(cx: &EffectCx, fields: &DialogFields) -> Vec { let id = cx.id.as_str(); let Some(info) = vectorcraft_effects::effect_info(id) else { return Vec::new() }; let relative = fields.contains("relative") && effect_rows::is_relative(fields); let mut defaults: Vec<(&String, &Value)> = info.defaults.as_object().into_iter().flatten().collect(); defaults.sort_by_key(|(key, _)| doc_rank(info.params, key)); - defaults.into_iter().filter_map(|(key, default)| generic_row(cx, key, default, relative)).collect() + defaults + .into_iter() + .filter_map(|(key, default)| { + let mut row = generic_row(cx, key, default, relative)?; + row.label = tl!(row.label.as_str()).to_owned().into(); + Some(row) + }) + .collect() } /// One row per stored value of an effect that has no rows of its own (a plug-in no longer @@ -294,3 +301,61 @@ pub(super) fn doc_rank(doc: &str, key: &str) -> usize { .find(|at| starts(*at) && doc.get(at + key.len()..).is_some_and(|rest| rest.starts_with(':') || rest.starts_with("?:"))) .unwrap_or(usize::MAX) } + +#[cfg(test)] +mod tests { + use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + use serde_json::json; + use vectorcraft_doc::NodeId; + use vectorcraft_engine::Session; + + use crate::VectorcraftApp; + + #[test] + fn gallery_cutout_setting_uses_its_localized_label() { + let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let mut shown_labels = Vec::new(); + for (language, expected) in [("en", "Levels"), ("de", "Stufen"), ("ja", "レベル数")] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.session.prefs.interface_language = language.to_owned(); + let lang = app.ui_language(); + let ctx = app.ui_ctx.clone().unwrap(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + ctx.enable_accesskit(); + time += 0.1; + crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(viewport), ..Default::default() }) + }; + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let square = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + frame(&mut app, vec![]); + assert_eq!(ctx.content_rect(), viewport); + app.run("ui.effectGalleryDialog", json!({})).unwrap(); + frame(&mut app, vec![]); + let nodes = frame(&mut app, vec![]).platform_output.accesskit_update.unwrap().nodes; + let filter = crate::i18n::effect_name(lang, "artistic.cutout").unwrap(); + let bounds = nodes.iter().filter(|(_, node)| node.label() == Some(filter.as_str())).find_map(|(_, node)| node.bounds()).unwrap(); + let at = pos2((bounds.x0 + bounds.x1) as f32 * 0.5, (bounds.y0 + bounds.y1) as f32 * 0.5); + assert!(viewport.contains(at), "{language}: Cutout is reachable"); + 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![]); + let output = frame(&mut app, vec![]); + let state = app.session.active().unwrap(); + let affected = &state.doc.node(NodeId(square)).unwrap().appearance.effects; + assert_eq!(affected.first().map(|effect| effect.id.as_str()), Some("artistic.cutout"), "{language}: Cutout is previewed"); + + let nodes = output.platform_output.accesskit_update.unwrap().nodes; + let found = [expected, "Levels"].into_iter().find(|label| { + nodes + .iter() + .any(|(_, node)| node.label() == Some(*label) && node.bounds().is_some_and(|b| viewport.contains(pos2(b.x0 as f32, b.y0 as f32)))) + }); + eprintln!("{language}: expected {expected:?}, found {found:?}"); + shown_labels.push(found); + } + assert_eq!(shown_labels, [Some("Levels"), Some("Stufen"), Some("レベル数")]); + } +} diff --git a/crates/ui-egui/src/dialogs/envelope.rs b/crates/ui-egui/src/dialogs/envelope.rs index b9daed9358..7b28dc305d 100644 --- a/crates/ui-egui/src/dialogs/envelope.rs +++ b/crates/ui-egui/src/dialogs/envelope.rs @@ -197,7 +197,7 @@ fn open_dialog(app: &mut VectorcraftApp, kind: &'static str, values: Map Result egui::Context { app.ui_ctx.clone().expect("the test context") } diff --git a/crates/ui-egui/src/dialogs/export_host.rs b/crates/ui-egui/src/dialogs/export_host.rs index 9730de0da1..79eb47b546 100644 --- a/crates/ui-egui/src/dialogs/export_host.rs +++ b/crates/ui-egui/src/dialogs/export_host.rs @@ -52,7 +52,7 @@ pub(crate) enum Export { /// Save for Office Documents. Office, /// Text Export Options. - Text, + Text { source: Option }, /// The options a save or open asks for before it goes on, for `action`. Save { /// The action the options belong to. @@ -161,7 +161,7 @@ fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Resu Export::Dxf => dxf_options::confirm(app, open, fields), Export::Hpgl { .. } => hpgl_options::confirm(app, open, fields), Export::Office => office_export::confirm(app, open, fields), - Export::Text => text_export::confirm(app, open, fields), + Export::Text { source } => text_export::confirm(app, open, source.as_ref(), fields), Export::Save { .. } => save_options::confirm(app, open, fields), } } diff --git a/crates/ui-egui/src/dialogs/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index 80439178a8..24fb32b996 100644 --- a/crates/ui-egui/src/dialogs/file_info.rs +++ b/crates/ui-egui/src/dialogs/file_info.rs @@ -55,10 +55,12 @@ type Info = Map; pub fn open(app: &mut VectorcraftApp) -> Result { let fields = app.session.execute("file.info", &json!({})).map_err(|e| e.to_string())?; let fields = fields.as_object().cloned().ok_or("file.info gave no fields")?; - let document = app.session.active().ok_or("no document")?.uid; - let ok = |app: &mut VectorcraftApp, (document, fields): &(u64, Info)| { - if !app.session.active().is_some_and(|active| active.uid == *document) { - return Err(tl!("File Info can only change the document it was opened for.").to_owned()); + let source = app.session.active().ok_or("no document")?; + let document = (source.uid, source.reverts); + let ok = |app: &mut VectorcraftApp, ((uid, generation), fields): &((u64, u64), Info)| { + let source = app.session.active().filter(|st| st.uid == *uid).ok_or(tl!("File Info can only change the document it was opened for."))?; + if source.reverts != *generation { + return Err(tl!("Reopen File Info after reverting the drawing").into()); } app.run("file.info", Value::Object(fields.clone())).map(|_| ()) }; @@ -113,6 +115,8 @@ enum Request { SaveTo(PathBuf), /// A browser picker returned a template larger than the import limit. TemplateTooLarge, + /// Download the current draft as a template, without requiring a filesystem path. + Download, /// Merge the template `source` into the fields as `mode` says. Import { source: Info, mode: &'static str }, } @@ -136,6 +140,7 @@ enum Chosen { #[derive(Default)] struct Templates { can_save: bool, + web_save: bool, can_open: bool, has_folder: bool, /// The metadata templates folder, where the save pick starts, once listed. @@ -221,6 +226,7 @@ impl Templates { } }); match chosen { + Some(Chosen::Pick(Pick::Save)) if self.web_save => self.requests.push(Request::Download), Some(Chosen::Pick(kind)) => self.pick(cx, kind, title), Some(Chosen::Template(file)) => wait_for_template(import, file), Some(Chosen::Folder) => self.requests.push(Request::Folder), @@ -232,7 +238,7 @@ impl Templates { /// The File Info dialog: a form over the fields `file.info` reports, whose OK is held for the app. pub(crate) struct FileInfoDialog { id: DialogId, - document: u64, + document: (u64, u64), open: bool, /// OK files its answer for the app instead of closing ([`HoldsOk::held_ok`]). hold: bool, @@ -248,7 +254,7 @@ pub(crate) struct FileInfoDialog { } impl FileInfoDialog { - fn new(document: u64, value: Info) -> Self { + fn new(document: (u64, u64), value: Info) -> Self { FileInfoDialog { id: dialog_id(KEY), document, @@ -390,7 +396,7 @@ fn import_options(ui: &mut egui::Ui, mode: &mut &'static str) -> Option { } impl HoldsOk for FileInfoDialog { - type Answer = (u64, Info); + type Answer = ((u64, u64), Info); fn held_ok(mut self) -> Self { self.hold = true; @@ -567,6 +573,26 @@ fn save_template(app: &mut VectorcraftApp, picked: PathBuf, fields: Info) -> Res save(app).map(|_| ()) } +/// Save the draft through the browser's file service. Serializing it changes neither drawing nor draft. +fn download_template(app: &mut VectorcraftApp, fields: Info) -> Result<(), String> { + let title = text_of(&fields, "title"); + let stem = vectorcraft_engine::cmd::library::file_stem_for(if title.trim().is_empty() { "Metadata" } else { &title }); + let name = format!("{stem}.{XMP_EXT}"); + let result = app.run("file.info.saveTemplate", json!({"fields": fields}))?; + let data = result["data"].as_str().ok_or("the metadata template contains no data")?.as_bytes().to_vec(); + let request = PickRequest::save(PURPOSE).file_name(name).suggested_extension(XMP_EXT).filter(tl!("XMP metadata templates"), &[XMP_EXT]); + file_asks::save(app, request, data, file_asks::Owner::Free, |app, picked| { + match picked { + Picked::Downloaded(name) => app.status(format!("Saved {name}")), + Picked::Saved { path, .. } => app.status(format!("Saved {}", path.display())), + Picked::Failed(error) => return Err(error), + _ => {} + } + Ok(Value::Null) + }); + Ok(()) +} + /// Merge the template `source` names into the dialog's fields as `mode` says. fn import(app: &mut VectorcraftApp, d: &mut FileInfoDialog, source: Info, mode: &str) -> Result<(), String> { let mut p = Value::Object(source); @@ -587,10 +613,13 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { // PLAN: fl.A9 lists no `file_info::pump`; the Templates menu needs the session, so hub-w2 adds this line to `dialogs::host::pump`. let Some(dialogs) = app.dialogs() else { return }; let id = dialog_id(KEY); - let (can_save, can_open, has_folder) = (file_asks::can(app, PickKind::Save), file_asks::can(app, PickKind::Open), has_templates_folder(app)); + let web_save = app.ui_ctx.as_ref().and_then(Host::try_of_ctx).is_some_and(|host| host.files().browser_saves()); + let (can_save, can_open, has_folder) = + (web_save || file_asks::can(app, PickKind::Save), file_asks::can(app, PickKind::Open), has_templates_folder(app)); let requests = dialogs.with(|host| { host.get_mut_by_id::(id).map(|d| { d.templates.can_save = can_save; + d.templates.web_save = web_save; d.templates.can_open = can_open; d.templates.has_folder = has_folder; d.take_requests() @@ -614,6 +643,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { None => Ok(()), }, Request::TemplateTooLarge => Err(tl!("The metadata template is larger than 8 MB.").to_owned()), + Request::Download => match dialogs.with(|host| host.get_by_id::(id).map(FileInfoDialog::filed_fields)) { + Some(fields) => download_template(app, fields), + None => Ok(()), + }, Request::Import { source, mode } => { dialogs.with(|host| host.get_mut_by_id::(id).map(|d| import(app, d, source, mode))).unwrap_or(Ok(())) } @@ -652,6 +685,42 @@ mod tests { app.dialogs().unwrap().with(|host| host.set_json_field(&ctx, dialog_id(KEY), field, value)) } + #[test] + fn stale_file_info_cannot_replace_metadata_restored_by_revert() { + let mut app = windowed(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let dir = vectorcraft_testkit::TempDir::new("file-info-metadata-revert"); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.info", json!({"title": "Saved Title"})).unwrap(); + app.run("file.saveAs", json!({"path": dir.join("metadata.vectorcraft")})).unwrap(); + let saved = &app.session.active().unwrap().doc; + let (saved_title, saved_metadata) = (saved.info_title().to_owned(), saved.metadata.clone()); + app.run("file.info", json!({"title": "Unsaved Title"})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "title", json!("Old Draft")).unwrap(); + let source = app.session.active().unwrap(); + let (uid, generation) = (source.uid, source.reverts); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reverted = app.session.active().unwrap(); + assert_eq!(reverted.uid, uid); + assert_ne!(reverted.reverts, generation); + assert_eq!(reverted.doc.info_title(), saved_title); + assert_eq!(reverted.doc.metadata, saved_metadata); + let undo = reverted.history.undo.len(); + crate::tests::picks::answer_dialog(&mut app, dialog_id(KEY), &[], true); + let reverted = app.session.active().unwrap(); + assert_eq!(reverted.doc.info_title(), saved_title); + assert_eq!(reverted.doc.metadata, saved_metadata); + assert_eq!(reverted.history.undo.len(), undo); + assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog_id(KEY))), Some(HeldOk::Refused(_)))); + + app.run("ui.fileInfoDialog", json!({})).unwrap(); + crate::tests::picks::answer_dialog(&mut app, dialog_id(KEY), &[("title", json!("Fresh Title"))], true); + assert_eq!(app.run("file.info", json!({})).unwrap()["title"], json!("Fresh Title")); + } + /// Presses OK: the dialog files its fields, and the frames after it run the app's OK and close an accepted dialog /// (a second OK would file a refused answer again). Whether it closed. fn press_ok(app: &mut VectorcraftApp) -> bool { @@ -662,6 +731,75 @@ mod tests { app.dialogs().unwrap().with(|host| host.held_state(dialog_id(KEY))) } + #[test] + fn browser_template_saves_export_the_draft_and_preserve_it_on_cancel_or_failure() { + use std::cell::RefCell; + use std::path::Path; + use std::rc::Rc; + use std::sync::Arc; + + use craft::host::{Picked, ScriptedFiles}; + use craft::ui::testing::{Fixture, Room}; + + let mut app = windowed(); + let files = Arc::new(ScriptedFiles::held().in_browser()); + crate::tests::picks::install_files(&mut app, files.clone()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let original = app.session.active().unwrap().doc.metadata.clone(); + let app = Rc::new(RefCell::new(app)); + let shown = Rc::clone(&app); + let mut fixture = Fixture::new(move |ui| crate::tests::picks::dialogs(&mut shown.borrow_mut(), ui)); + fixture.in_room(Room::Window); + let ctx = fixture.ctx().clone(); + { + let mut app = app.borrow_mut(); + app.ui_ctx = Some(ctx.clone()); + craft::host::Host::clone(&app.host).install(&ctx); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "title", json!("Draft Template")).unwrap(); + set(&app, "author", json!("Ada")).unwrap(); + set(&app, PENDING, json!("print")).unwrap(); + } + fixture.settle(); + let draft = with_dialog(&app.borrow(), |d| d.filed_fields()).unwrap(); + for answer in [ + Picked::Saved { path: "draft.xmp".into(), file_type: None }, + Picked::Downloaded("draft.xmp".into()), + Picked::Cancelled, + Picked::Failed("download refused".into()), + ] { + let before = files.requests().len(); + let menu = fixture.by_label("Templates").expect("the Templates menu"); + fixture.click(&menu).settle(); + let save = fixture.by_label("Save Metadata Template…").expect("browser hosts can save the draft"); + fixture.click(&save).settle(); + assert_eq!(files.requests().len(), before + 1, "one save per action"); + let request = files.requests().pop().unwrap(); + assert_eq!(request.kind, craft::host::PickKind::Save); + assert!(request.file_name.as_deref().is_some_and(|name| name.ends_with(".xmp"))); + app.borrow_mut().ui.status = "before the answer".into(); + assert!(files.answer(answer.clone()).is_some()); + crate::file_asks::poll(&mut app.borrow_mut()); + fixture.settle(); + let app = app.borrow(); + match answer { + Picked::Cancelled => assert_eq!(app.ui.status, "before the answer"), + Picked::Failed(_) => assert_eq!(app.ui.status, "download refused"), + _ => assert!(app.ui.status.starts_with("Saved ")), + } + assert_eq!(with_dialog(&app, |d| d.filed_fields()).unwrap(), draft); + let document = app.session.active().unwrap(); + assert_eq!(document.doc.metadata, original); + assert!(document.history.undo.is_empty()); + assert!(document.path.is_none(), "saving a template does not save the drawing"); + } + let xmp = files.file(Path::new("draft.xmp")).expect("the service received the XMP bytes"); + let template = vectorcraft_pdf::read_template(&xmp).expect("the saved draft is a metadata template"); + assert_eq!(template.title.as_deref(), Some("Draft Template")); + assert_eq!(template.author.as_deref(), Some("Ada")); + assert_eq!(template.keywords, Some(vec!["print".into()])); + } + #[test] fn file_info_draws_and_ok_is_one_undo_step() { let mut app = windowed(); diff --git a/crates/ui-egui/src/dialogs/flare_options.rs b/crates/ui-egui/src/dialogs/flare_options.rs index d479b57368..b67116b3a8 100644 --- a/crates/ui-egui/src/dialogs/flare_options.rs +++ b/crates/ui-egui/src/dialogs/flare_options.rs @@ -42,7 +42,7 @@ pub(crate) struct Open { /// The hosted dialog. id: DialogId, opening: Arc<()>, - document: Option, + document: Option<(u64, u64)>, /// 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. @@ -55,7 +55,7 @@ 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 + self.preview.is_none() || app.session.active().map(|st| (st.uid, st.reverts)) == self.document } fn cancel_preview(self, app: &mut VectorcraftApp) { @@ -132,7 +132,7 @@ pub fn open(app: &mut VectorcraftApp, at: Option) -> Value { 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); + let document = app.session.active().map(|st| (st.uid, st.reverts)); match open_held_with(app, dialog, ok, held) { Some(id) => app.object_dialogs.flare = Some(Open { id, opening, document, click: at, edit, preview: previews.then(LivePreview::default) }), None => app.status("no window"), @@ -301,6 +301,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { 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) { + if app.session.active().map(|st| st.uid) == open.document.map(|(uid, _)| uid) { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } return Err(tl!("Return to the original drawing to place or edit the flare").into()); } if open.preview.is_some() && other_preview(app) { @@ -544,4 +547,32 @@ mod tests { let parts = flare_parts(&app); assert_eq!((parts.iter().filter(|p| *p == "Ring").count(), parts.iter().any(|p| p == "Rays")), (10, true), "{parts:?}"); } + + #[test] + fn a_pending_flare_does_not_draw_on_restored_art() { + let mut app = app(); + let dir = vectorcraft_testkit::TempDir::new("flare-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("shape.ellipse", json!({"x": 5, "y": 5, "width": 20, "height": 20})).unwrap(); + let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers[0].children().unwrap().len(); + open(&mut app, Some(Point::new(100.0, 110.0))); + pump(&mut app); + assert_eq!(count(&app), 2, "the original art and the flare preview"); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + pump(&mut app); + assert_eq!(count(&app), 0, "the old preview leaves the restored art alone"); + let options = app.session.tool_options_of("flare"); + press_ok(&mut app); + assert_eq!(count(&app), 0, "the old approval leaves the restored art alone"); + assert_eq!(app.session.tool_options_of("flare"), options); + assert!(app.object_dialogs.flare.is_some()); + + press_cancel(&mut app); + open(&mut app, Some(Point::new(100.0, 110.0))); + press_ok(&mut app); + assert_eq!(count(&app), 1); + } } diff --git a/crates/ui-egui/src/dialogs/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index 973c77a45f..92ee610e3b 100644 --- a/crates/ui-egui/src/dialogs/flatten.rs +++ b/crates/ui-egui/src/dialogs/flatten.rs @@ -175,12 +175,13 @@ pub(crate) fn custom_dialog(ctx: &egui::Context, parent: &HostedPdfExport, job: as_written(&mut o, parent.settings().advanced.overprint); let mut fields = option_fields(&o); fields.set(KEPT_OVERPRINTS, kept); - HostedParamDialog::new(ctx, CUSTOM_KEY, fields, |_| { + HostedParamDialog::new(ctx, CUSTOM_KEY, fields, |fields| { ParamDialog::new( CUSTOM_KEY, tl!("Custom Transparency Flattener Options"), option_params(&FIXED, tl!("PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept.")), ) + .values(Bind::bound(fields)) }) } @@ -213,8 +214,8 @@ pub(crate) fn apply_custom(job: &mut SavePdfJob, parent: &HostedPdfExport, field /// Open Flatten Transparency for the selection with the default preset. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let dialog = HostedParamDialog::new(&ctx, KEY, option_fields(&FlattenOptions::default()), |_| { - ParamDialog::new(KEY, tl!("Flatten Transparency"), option_params(&[], "")).previews(true) + let dialog = HostedParamDialog::new(&ctx, KEY, option_fields(&FlattenOptions::default()), |fields| { + ParamDialog::new(KEY, tl!("Flatten Transparency"), option_params(&[], "")).values(Bind::bound(fields)).previews(true) }) // Flattening complex art is slow: the preview waits until it is turned on. .preview_off(); @@ -450,4 +451,71 @@ mod tests { create(&mut app, &ctx, id, params, "High Resolution"); assert_eq!(app.session.prefs.flattener_presets.len(), 1); } + + #[test] + fn flattened_art_resolution_keeps_a_live_keyboard_edit() { + assert_live_resolution(false); + } + + #[test] + fn pdf_flattener_resolution_keeps_a_live_keyboard_edit() { + assert_live_resolution(true); + } + + fn assert_live_resolution(custom: bool) { + use craft::ui::testing::Fixture; + use std::cell::RefCell; + use std::rc::Rc; + + let app = Rc::new(RefCell::new(scene())); + let shown = app.clone(); + let mut fixture = Fixture::new(move |ui| { + let mut app = shown.borrow_mut(); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|host| host.run(ui)); + super::super::host::pump(&mut app, ui.ctx()); + }); + fixture.room(egui::vec2(880.0, 720.0)); + let ctx = fixture.ctx().clone(); + let document = app.borrow().session.active().unwrap().uid; + let mut job = SavePdfJob { + document, + path: None, + save_mode: None, + flattener: Some(FlattenOptions { line_art_ppi: 611.0, ..FlattenOptions::default() }), + selection: false, + }; + let parent = HostedPdfExport::new(vectorcraft_pdf::APP, vectorcraft_pdf::PdfSettings::default()); + let id = { + let mut app = app.borrow_mut(); + app.ui_ctx = Some(ctx.clone()); + if custom { + let dialog = custom_dialog(&ctx, &parent, &job, &[]); + app.dialogs().unwrap().with(|host| host.open(dialog)) + } else { + open(&mut app).unwrap(); + app.flatten_dialog.open.as_ref().unwrap().id + } + }; + fixture.settle(); + let field = fixture + .by_label("Line Art and Text Resolution") + .or_else(|| fixture.by_label("Line Art and Text Resolution:")) + .expect("the hosted resolution field"); + if custom { + let fields = app.borrow().dialogs().unwrap().with(|h| h.get_by_id::(id).unwrap().fields().clone()); + assert_eq!(fields.number("lineArtPpi"), Some(611.0), "the PDF dialog opens with the job's own resolution"); + } + fixture.click(&field).key(egui::Key::A, egui::Modifiers::COMMAND).type_text("399").key(egui::Key::Tab, egui::Modifiers::NONE).settle(); + let app = app.borrow(); + let fields = app.dialogs().unwrap().with(|h| h.get_by_id::(id).unwrap().fields().clone()); + assert_eq!(fields.number("lineArtPpi"), Some(399.0), "the hosted form keeps its keyboard edit"); + if custom { + apply_custom(&mut job, &parent, &fields, &[]).unwrap(); + assert_eq!(job.flattener.unwrap().line_art_ppi, 399.0); + } else { + let params = command_params(&option_params(&[], ""), &fields, &[]).unwrap(); + assert_eq!(params["lineArtPpi"], 399.0); + } + } } diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index f2bf968f04..8a0f587513 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -16,17 +16,21 @@ use std::sync::Arc; use craft::behavior::IconId; -use craft::color_ui::ui::{ColorPanel, ColorPanelLayout, ColorPanelOutput, ColorPanelShown, ColorPanelState, DropperButton, SwatchPalette}; +use craft::color_ui::ui::{ + ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelOutput, ColorPanelShown, ColorPanelState, ColorPanelWords, DropperButton, SwatchPalette, +}; use craft::theme::Srgba; use craft::theme::variant::Tone; +use craft::ui::buttons::Button; use craft::ui::choice::Segmented; -use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, PopupKind, Show as _, ShowContainer as _, Trigger}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; use craft::ui::form::Field; use craft::ui::layout_components::{Row, Stack}; +use craft::ui::menu::{Menu, MenuItem}; use craft::ui::notices::Notice; use craft::ui::popover::Popover; -use craft::ui::runtime::env::{Label, UnitKind}; +use craft::ui::runtime::env::{Env, Label, UnitKind}; use craft::ui::runtime::overlay::CloseReason; use craft::ui::text::NumberField; use egui::{Pos2, Ui, vec2}; @@ -98,11 +102,63 @@ impl TargetKey { } } +/// A Color mode command from the popover's menu that has not been seen to finish. +struct OwnMode { + /// The document's history step when it ran. + from: (u64, u64), + /// The mode it picked. + mode: ColorPanelMode, + /// The Color panel showed `mode` at an earlier pass with no new history step. + shown: bool, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum OwnModeNow { + /// No command is pending. + None, + /// The command has not been seen to finish. + Waiting, + /// The command made the new history step: the changed paint is the popover's own edit. + Edited, + /// The command finished without a history step. + Unchanged, +} + +impl OwnMode { + /// What the command has done by this pass, with the document at history `step` and the Color panel showing + /// `shown_mode`. The first new history step after it is its own edit. Once the panel shows the picked mode, one + /// more pass with no new step means it changed nothing. + fn now(&mut self, step: Option<(u64, u64)>, shown_mode: ColorPanelMode) -> OwnModeNow { + if step != Some(self.from) { + return OwnModeNow::Edited; + } + if shown_mode != self.mode { + return OwnModeNow::Waiting; + } + if std::mem::replace(&mut self.shown, true) { OwnModeNow::Unchanged } else { OwnModeNow::Waiting } + } +} + /// The gradient in that slot as the popover last saw it, including any live edits it applied. #[derive(Clone)] struct TargetOwner { key: TargetKey, paints: Arc, + /// The history step when the popover took `paints`. + step: Option<(u64, u64)>, + /// The document's count of Undo and Redo steps as of the popover's last pass. + restores: Option, + /// The paints the popover owned before its own later edits, newest last, each with the history step it was + /// current at and the stop or point it edited then, so that Undo and Redo of those edits keep it open on the + /// same stop or point. + earlier: Vec, +} + +#[derive(Clone)] +struct Earlier { + step: Option<(u64, u64)>, + key: TargetKey, + paints: Arc, } struct TargetPaints { @@ -111,10 +167,49 @@ struct TargetPaints { } impl TargetOwner { + /// The most earlier paints kept. + const EARLIER: usize = 32; + + fn new(key: TargetKey, paints: Arc, step: Option<(u64, u64)>, restores: Option) -> Self { + Self { key, paints, step, restores, earlier: Vec::new() } + } + fn matches(&self, app: &VectorcraftApp, target: &Target) -> bool { - self.key.matches(app, target) - && self.paints.shown == *target.paint() - && app.session.gradient_edit_paints(!self.key.fill).is_ok_and(|paints| paints == self.paints.edited) + self.key.matches(app, target) && self.owns(app, target, &self.paints) + } + + /// The earlier owned paint and stop or point that the target shows now after Undo or Redo of one of the popover's + /// own edits. A stop selected after Undo that is not the one that paint belonged to matches nothing, and so does + /// an earlier paint set again by anything other than Undo or Redo. + fn owned_earlier(&self, app: &VectorcraftApp, target: &Target, restores: Option) -> Option { + if restores == self.restores { + return None; + } + self.earlier.iter().rev().find(|e| e.key.matches(app, target) && self.owns(app, target, &e.paints)).map(|e| e.key.clone()) + } + + fn owns(&self, app: &VectorcraftApp, target: &Target, paints: &TargetPaints) -> bool { + paints.shown == *target.paint() && app.session.gradient_edit_paints(!self.key.fill).is_ok_and(|now| now == paints.edited) + } + + /// The popover now owns `paints`, taken at history step `step`; the paints it owned until now are kept as earlier + /// ones, with `was`, the stop or point they belonged to. + fn adopt(&mut self, paints: Arc, was: TargetKey, step: Option<(u64, u64)>) { + let old = std::mem::replace(&mut self.paints, paints); + let old_step = std::mem::replace(&mut self.step, step); + self.earlier.retain(|e| !Arc::ptr_eq(&e.paints, &old)); + // Undo and Redo return only to the first or the last paints of one history step. The samples of a live drag + // between them replace each other, so a long drag does not push out the paints before it. + if let [.., before, last] = self.earlier.as_slice() + && before.step == old_step + && last.step == old_step + { + self.earlier.pop(); + } + self.earlier.push(Earlier { step: old_step, key: was, paints: old }); + if self.earlier.len() > Self::EARLIER { + self.earlier.remove(0); + } } } @@ -231,6 +326,10 @@ struct Filed { swatch: Option<(String, Color)>, eyedropper: bool, panels: Vec, + /// Only an actual Shift-cycle changes this; an unchanged local snapshot must not overwrite a menu command. + mode: Option, + /// The mode whose row of the popover's Color mode menu ran its command this pass. + mode_command: Option, } /// The gradient stop popover. @@ -247,6 +346,9 @@ pub(crate) struct GradientStopPopover { /// The fields set from outside, applied at confirm. set: PopoverFields, filed: Filed, + /// A command the popover's Color mode menu ran, which runs outside `pump`: the document's history step when it + /// ran, the mode it picked, and whether the Color panel already showed that mode at an earlier pass. + own_mode: Option, } impl GradientStopPopover { @@ -260,6 +362,7 @@ impl GradientStopPopover { feed: None, set: PopoverFields::default(), filed: Filed::default(), + own_mode: None, } } @@ -286,6 +389,9 @@ impl StackDialog for GradientStopPopover { .at_point(*at) .close_on_enter(true) .show(ui, |ui, _| body(ui, feed, tab, panel, filed)); + if shown.inner == Some(true) { + return Some(DialogResult::Cancel); + } match shown.output.closed { Some(CloseReason::Enter) => self.confirm(ui.ctx()).map(DialogResult::Ok), Some(_) => Some(DialogResult::Cancel), @@ -336,7 +442,8 @@ impl StackDialog for GradientStopPopover { /// The popover's body: the tabs and the eyedropper, the Color panel or the swatches, then opacity and location (a /// point: spread). What the user edits is filed in `filed`. -fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, filed: &mut Filed) { +fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, filed: &mut Filed) -> bool { + let mut outside = false; Stack::new().show(ui, |ui, _| { Row::new().show(ui, |ui, _| { let tabs = [ @@ -349,16 +456,25 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi let tip = tl!("Eyedropper: click the art to sample the stop's colour").to_owned(); filed.eyedropper |= DropperButton::new(tip, Bind::given(false)).show(ui).edit.value() == Some(&true); } + if *tab == Tab::Color { + let (closed, picked) = mode_menu(ui, &feed.shown, panel.mode); + outside |= closed; + filed.mode_command = picked.or(filed.mode_command); + } }); match *tab { // The Color panel edits the selected stop (or point) of the active gradient. Tab::Color => { + let before = panel.mode; filed.panels.push( ColorPanel::new(Bind::bound(&mut *panel), [feed.current; 2]) .layout(ColorPanelLayout::FillStroke) .shown(feed.shown.clone()) .show(ui), ); + if panel.mode != before { + filed.mode = Some(panel.mode); + } } Tab::Swatches => swatches(ui, feed, filed), } @@ -368,6 +484,30 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi *amount = percent_field(ui, label.to_owned(), feed.amount).or(*amount); }); }); + outside +} + +/// The Color panel's existing five mode commands. Native menu ownership keeps its parent popover +/// open on a pick and gives the child the first Escape, including rows outside the parent bounds. Returns whether +/// an outside press closed the menu, and the mode whose row ran its command. +fn mode_menu(ui: &mut Ui, shown: &ColorPanelShown, fallback: ColorPanelMode) -> (bool, Option) { + let words = Env::of(ui).words::(); + let label = match shown { + ColorPanelShown::Mode(mode) => mode.label(&words), + ColorPanelShown::Tint(_) => words.tint.clone(), + _ => fallback.label(&words), + }; + let button = Button::new(label).popup(PopupKind::Menu).show(ui); + let mut picked = None; + let menu = Menu::new(tl!("Color mode")).opened_by(&button, Trigger::Click).show(ui, |ui, _| { + for mode in ColorPanelMode::FILL_STROKE { + if MenuItem::command(mode.command()).show(ui).ran { + picked = Some(mode); + } + } + }); + // The child absorbs an outside press before its parent sees it. Close both for that event only. + (menu.output.closed == Some(CloseReason::Outside), picked) } /// Document swatches as tiles: a pick gives the stop (or point) that colour. @@ -454,6 +594,9 @@ fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Tar dialogs.with(|host| { if let Some(popover) = host.get_mut_by_id::(id) { (popover.at, popover.feed) = (at, Some(feed)); + popover.panel = app.ui.color_panel; + // This panel edits the active stop/point, never the other paint behind the proxy. + popover.panel.background = false; } }); } @@ -474,8 +617,10 @@ pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) { let Some(key) = TargetKey::of(app, &target) else { return }; let Ok(edited) = app.session.gradient_edit_paints(!key.fill) else { return }; let paints = Arc::new(TargetPaints { shown: target.paint().clone(), edited }); + let step = app.session.active().map(|st| st.history.step()); + let restores = app.session.active().map(|st| st.history_restores); dialogs.with(|host| { - host.open(GradientStopPopover::new(anchor, TargetOwner { key, paints })); + host.open(GradientStopPopover::new(anchor, TargetOwner::new(key, paints, step, restores))); }); refresh(app, &ctx, dialog_id(KIND), &target); } @@ -498,13 +643,40 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { Some(_) => return, None => {} } - let Some(mut owner) = dialogs.with(|host| host.get_by_id::(id).map(|popover| popover.target.clone())) else { + let step = app.session.active().map(|st| st.history.step()); + let restores = app.session.active().map(|st| st.history_restores); + let shown_mode = app.ui.color_panel.mode; + let Some((mut owner, own_mode)) = dialogs.with(|host| { + host.get_mut_by_id::(id).map(|popover| { + if let Some(mode) = popover.filed.mode_command.take() { + popover.own_mode = step.map(|from| OwnMode { from, mode, shown: false }); + } + let own = popover.own_mode.as_mut().map_or(OwnModeNow::None, |pending| pending.now(step, shown_mode)); + if own != OwnModeNow::Waiting { + popover.own_mode = None; + } + (popover.target.clone(), own == OwnModeNow::Edited) + }) + }) else { return; }; - let Some(target) = selected(app).filter(|target| owner.matches(app, target)) else { + let accepted = selected(app).and_then(|target| { + if owner.matches(app, &target) || (own_mode && owner.key.matches(app, &target)) { + Some((target, None)) + } else { + owner.owned_earlier(app, &target, restores).map(|key| (target, Some(key))) + } + }); + let Some((target, earlier)) = accepted else { dialogs.with(|host| host.cancel_by_id(ctx, id)); return; }; + // The stop or point the paints owned until now belong to, before Undo or Redo or this pass's edits move it. + let owned_key = owner.key.clone(); + if let Some(key) = earlier { + owner.key = key; + } + owner.restores = restores; let filed = dialogs.with(|host| host.get_mut_by_id::(id).map(GradientStopPopover::take_filed)).unwrap_or_default(); if filed.fields != PopoverFields::default() { apply(app, &target, &filed.fields); @@ -525,6 +697,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { // PLAN: assumed `panels::color::apply_output(app, &ColorPanelOutput)` (color-w9's decision). crate::panels::color::apply_output(app, output); } + if let Some(mode) = filed.mode { + let target = crate::panels::color::target_now(app); + crate::panels::color::set_mode(app, &target, mode); + } if filed.eyedropper { dialogs.with(|host| host.cancel_by_id(ctx, id)); crate::panels::gradient::stop_eyedropper(app); @@ -537,7 +713,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { }; // The popover can continue with the paints resulting from its own edits in this pass. if owner.paints.shown != *target.paint() || owner.paints.edited != edited { - owner.paints = Arc::new(TargetPaints { shown: target.paint().clone(), edited }); + let step = app.session.active().map(|st| st.history.step()); + owner.adopt(Arc::new(TargetPaints { shown: target.paint().clone(), edited }), owned_key, step); } dialogs.with(|host| { if let Some(popover) = host.get_mut_by_id::(id) { @@ -761,6 +938,139 @@ mod tests { assert!(!is_open(&app)); } + #[test] + fn a_mode_command_that_changes_nothing_stops_counting_as_its_own_edit() { + let (from, other) = ((3, 0), ColorPanelMode::FILL_STROKE[0]); + let picked = ColorPanelMode::FILL_STROKE[1]; + let mut pending = OwnMode { from, mode: picked, shown: false }; + assert!(OwnModeNow::Waiting == pending.now(Some(from), other), "the command has not run yet"); + assert!(OwnModeNow::Waiting == pending.now(Some(from), picked), "the panel shows the mode; one more pass"); + assert!(OwnModeNow::Unchanged == pending.now(Some(from), picked), "no history step followed: nothing changed"); + let mut pending = OwnMode { from, mode: picked, shown: false }; + assert!(OwnModeNow::Edited == pending.now(Some((4, 0)), picked), "the first new step is the command's own"); + } + + #[test] + fn undo_after_a_stop_crosses_its_neighbor_does_not_edit_the_neighbor() { + let mut app = app(); + open_at(&mut app, 0, Anchor::Screen(egui::pos2(200.0, 200.0))); + assert!(is_open(&app)); + let ctx = ctx(&app); + let edit = |app: &VectorcraftApp, fields: PopoverFields| { + app.dialogs().unwrap().with(|host| host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.fields = fields); + }; + edit(&app, PopoverFields { location: Some(75.0), ..PopoverFields::default() }); + host::pump(&mut app, &ctx); + assert_eq!(app.session.selected_stop(), Some(1), "the stop crossed its neighbor"); + app.run("edit.undo", json!({})).unwrap(); + host::pump(&mut app, &ctx); + if is_open(&app) { + edit(&app, PopoverFields { opacity: Some(25.0), ..PopoverFields::default() }); + host::pump(&mut app, &ctx); + let stops = stops(&app); + assert!(stops[0].opacity < 1.0, "the edit reaches the stop the popover opened on"); + assert_eq!(stops[1].opacity, 1.0, "the neighbor is left alone"); + } + } + + #[test] + fn redo_after_a_stop_crosses_its_neighbor_does_not_reopen_on_the_neighbor() { + let mut app = app(); + open_at(&mut app, 0, Anchor::Screen(egui::pos2(200.0, 200.0))); + let ctx = ctx(&app); + app.dialogs().unwrap().with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.fields.location = Some(75.0); + }); + host::pump(&mut app, &ctx); + assert_eq!(app.session.selected_stop(), Some(1), "the stop crossed its neighbor"); + app.run("edit.undo", json!({})).unwrap(); + app.run("gradient.selectStop", json!({"index": 0})).unwrap(); + host::pump(&mut app, &ctx); + assert!(is_open(&app), "Undo returns to the paint it owned on stop 0"); + app.run("edit.redo", json!({})).unwrap(); + app.run("gradient.selectStop", json!({"index": 0})).unwrap(); + host::pump(&mut app, &ctx); + assert!(!is_open(&app), "after Redo, stop 0 is the neighbor"); + } + + #[test] + fn its_earlier_paint_set_again_from_elsewhere_closes_the_popover() { + let mut app = app(); + open_popover(&mut app); + let ctx = ctx(&app); + let queue = |app: &VectorcraftApp, opacity: f64| { + app.dialogs().unwrap().with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.fields.opacity = Some(opacity); + }); + }; + queue(&app, 25.0); + host::pump(&mut app, &ctx); + assert!(is_open(&app) && stops(&app)[1].opacity < 1.0, "the live edit applied"); + // The fixture's gradient again, set without Undo. + let stops_json = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#00ff00"}, {"offset": 1, "color": "#000000"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops_json, "start": [100, 150], "end": [200, 150]}})).unwrap(); + assert_eq!(app.session.selected_stop(), Some(1)); + queue(&app, 50.0); + host::pump(&mut app, &ctx); + assert!(!is_open(&app), "a gradient from elsewhere closes it, even one it owned before"); + assert_eq!(stops(&app)[1].opacity, 1.0, "the pending edit is discarded"); + } + + #[test] + fn undo_after_a_long_live_drag_keeps_the_popover_open() { + let mut app = app(); + open_popover(&mut app); + let ctx = ctx(&app); + let dialogs = app.dialogs().unwrap(); + let gesture = GestureId::new(1); + let pick = |hex: &str| PickedColor::rgb(Srgba::from_hex(hex).unwrap()); + let before = pick("#00ff00"); + let original = stops(&app)[1].color.to_hex(); + let samples = (0..2 * TargetOwner::EARLIER).map(|i| EditEvent::update(gesture, pick(&format!("#{:02x}0000", 40 + i)))); + for edit in samples.chain([EditEvent::commit(gesture, Mixed::Same(before), pick("#0000ff"))]) { + let mut edit = Some(edit); + ctx.run_ui(Default::default(), |ui| { + let Some(edit) = edit.take() else { return }; + let mut state = ColorPanelState::default(); + let mut output = ColorPanel::new(Bind::bound(&mut state), [before.color; 2]).show(ui); + output.edits.push((PanelTarget::Foreground, edit)); + dialogs.with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.panels.push(output); + }); + }) + .textures_delta + .clear(); + host::pump(&mut app, &ctx); + } + assert_eq!(stops(&app)[1].color.to_hex(), "#0000ff"); + app.run("edit.undo", json!({})).unwrap(); + host::pump(&mut app, &ctx); + assert_eq!(stops(&app)[1].color.to_hex(), original, "Undo returns to the paint before the drag"); + assert!(is_open(&app), "the paint before the drag is still the popover's own"); + } + + #[test] + fn undo_of_its_own_edit_keeps_the_popover_open() { + let mut app = app(); + open_popover(&mut app); + app.dialogs().unwrap().with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.fields.opacity = Some(25.0); + }); + let ctx = ctx(&app); + host::pump(&mut app, &ctx); + assert!(stops(&app)[1].opacity < 1.0, "the live edit applied"); + app.run("edit.undo", json!({})).unwrap(); + host::pump(&mut app, &ctx); + assert_eq!(stops(&app)[1].opacity, 1.0); + assert!(is_open(&app), "Undo returns to a paint the popover owned"); + app.run("edit.redo", json!({})).unwrap(); + host::pump(&mut app, &ctx); + assert!(is_open(&app), "Redo returns to a paint the popover owned"); + replace_gradient(&mut app); + host::pump(&mut app, &ctx); + assert!(!is_open(&app), "a gradient from elsewhere still closes it"); + } + #[test] fn discards_edits_when_only_a_secondary_selected_gradient_is_replaced() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 9cf40d3319..1eb37190e5 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -51,6 +51,7 @@ use crate::file_asks::{self, Owner}; /// The dialog kind of Graph Data, the key of its dialog on the host. pub const KIND: &str = "graphData"; const WRONG_DOCUMENT: &str = "Graph Data belongs to the document that opened this sheet."; +const REVERTED_DOCUMENT: &str = "Reopen Graph Data after reverting the drawing."; /// The sheet's size: a row of labels over a graph's categories, a column of labels before its /// series; the least rows it shows. @@ -71,13 +72,11 @@ const ROW_H: f32 = 19.0; pub fn open(app: &mut VectorcraftApp) -> Result { // The query fails without a graph selected, with the engine's own message. let v = app.session.execute("graph.setData", &json!({})).map_err(|e| e.to_string())?; - let document = app.session.active().ok_or("no document open")?.uid; - let graph = app.session.active().and_then(|st| st.selection.objects.iter().find_map(|id| graph_of(&st.doc, *id)).map(|id| (st, id))); - let scatter = graph.is_some_and(|(st, id)| { - st.doc.node(id).and_then(|n| n.extras().graph.as_deref()).is_some_and(|g| g.kind == vectorcraft_doc::GraphKind::Scatter) - }); - let id = graph.map(|(_, id)| id.0); - let dialog = GraphDataDialog::new(grid_from_data(&v), document, id, scatter, can_import(app)); + let st = app.session.active().ok_or("no document open")?; + let graph = st.selection.objects.iter().find_map(|id| graph_of(&st.doc, *id)); + let scatter = graph + .is_some_and(|id| st.doc.node(id).and_then(|n| n.extras().graph.as_deref()).is_some_and(|g| g.kind == vectorcraft_doc::GraphKind::Scatter)); + let dialog = GraphDataDialog::new(grid_from_data(&v), st.uid, st.reverts, graph.map(|id| id.0), scatter, can_import(app)); let dialogs = app.dialogs().ok_or("no window to show the dialog in")?; dialogs.with(|host| host.open(dialog)); Ok(Value::Null) @@ -437,6 +436,7 @@ fn import(app: &mut VectorcraftApp, owner: &Arc<()>, picked: Picked) -> Result, import_owner: Arc<()>, apply: Option, @@ -448,26 +448,29 @@ struct Asks { pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let can = can_import(app); - let active = app.session.active().map(|doc| doc.uid); + let active = app.session.active().map(|doc| (doc.uid, doc.reverts)); let asked = dialogs.with(|host| { host.get_mut::().map(|d| { d.can_import = can; - if active == Some(d.document) { + if active == Some((d.document, d.reverts)) { d.held.clear_refusal(); } d.take_asks() }) }); - let Some(Asks { document, graph, import_owner, apply: filed, actions }) = asked else { return }; - let same_document = active == Some(document); + let Some(Asks { document, reverts, graph, import_owner, apply: filed, actions }) = asked else { return }; + let refusal = match active { + Some((uid, current_reverts)) if uid == document => (current_reverts != reverts).then_some(tl!(REVERTED_DOCUMENT)), + _ => Some(tl!(WRONG_DOCUMENT)), + }; if let Some(sheet) = filed { - let answer = if same_document { + let answer = if let Some(reason) = refusal { + Err(Label::from(reason)) + } else { if let Err(e) = apply(app, &sheet, graph) { app.status(e); } Ok(()) - } else { - Err(Label::from(tl!(WRONG_DOCUMENT))) }; dialogs.with(|host| host.get_mut::().map(|dialog| dialog.applied(answer))); } @@ -489,13 +492,18 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { move |app, picked| import(app, &owner, picked), ); } - Action::Revert if !same_document => app.status(tl!(WRONG_DOCUMENT).to_owned()), - Action::Revert => match graph_grid(app, graph) { - Ok(grid) => { - dialogs.with(|host| host.get_mut::().map(|d| d.replace(grid))); + Action::Revert => { + if let Some(reason) = refusal { + app.status(reason.to_owned()); + } else { + match graph_grid(app, graph) { + Ok(grid) => { + dialogs.with(|host| host.get_mut::().map(|d| d.replace(grid))); + } + Err(e) => app.status(e), + } } - Err(e) => app.status(e), - }, + } } } } @@ -675,6 +683,7 @@ pub(crate) struct GraphDataDialog { state: GridState, entry: Entry, document: u64, + reverts: u64, /// The graph the sheet opened on. graph: Option, scatter: bool, @@ -687,7 +696,7 @@ pub(crate) struct GraphDataDialog { impl GraphDataDialog { /// The window over `grid`, the data of `graph`; Switch x/y is on for a `scatter` graph. - fn new(grid: Grid, document: u64, graph: Option, scatter: bool, can_import: bool) -> Self { + fn new(grid: Grid, document: u64, reverts: u64, graph: Option, scatter: bool, can_import: bool) -> Self { let sheet = Sheet { grid, ..Sheet::default() }; let state = GridState::new(CellSelection::cell(CellAt::new(0, 1)), 1.0); let mut entry = Entry { text: String::new(), at: (0, 1) }; @@ -699,6 +708,7 @@ impl GraphDataDialog { state, entry, document, + reverts, graph, scatter, can_import, @@ -712,6 +722,7 @@ impl GraphDataDialog { fn take_asks(&mut self) -> Asks { Asks { document: self.document, + reverts: self.reverts, graph: self.graph, import_owner: self.import_owner.clone(), apply: self.held.take(), @@ -922,6 +933,62 @@ mod tests { assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), expected); } + fn stale_sheet_after_file_revert(test: &str) -> (VectorcraftApp, u64, Value) { + struct SavedFile(std::path::PathBuf); + impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + let (mut app, id) = app_with(",Original\nQ1,1", "column"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-graph-data-revert-{}-{test}.vectorcraft", std::process::id()))); + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + assert!(path.0.is_file()); + let saved = data(&mut app, id); + app.run("graph.setData", json!({"id": id, "series": ["Unsaved"], "categories": ["Q2"], "rows": [[3.0]]})).unwrap(); + assert_ne!(data(&mut app, id), saved); + app.run("select.set", json!({"ids": [id]})).unwrap(); + open(&mut app).unwrap(); + set_field(&app, "grid", json!([["", "Draft"], ["Q2", "9"]])).unwrap(); + let state = app.session.active().unwrap(); + let (uid, reverts) = (state.uid, state.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let state = app.session.active().unwrap(); + assert_eq!((state.uid, state.reverts), (uid, reverts + 1)); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert_eq!(data(&mut app, id), saved, "the restored graph uses the same ID"); + (app, id, saved) + } + + #[test] + fn graph_data_after_file_revert_cannot_apply_the_old_draft() { + let (mut app, id, saved) = stale_sheet_after_file_revert("apply"); + let undo = app.session.active().unwrap().history.undo.len(); + apply_through_host(&mut app); + assert_eq!(data(&mut app, id), saved); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(read(&app, GraphDataDialog::held_state), Some(HeldOk::Refused(_)))); + + app.run("select.set", json!({"ids": [id]})).unwrap(); + open(&mut app).unwrap(); + set_field(&app, "grid", json!([["", "Fresh"], ["Q3", "7"]])).unwrap(); + apply_through_host(&mut app); + assert_eq!(data(&mut app, id)["rows"], json!([[7.0]])); + } + + #[test] + fn graph_data_after_file_revert_keeps_the_old_sheet_on_worksheet_revert() { + let (mut app, id, saved) = stale_sheet_after_file_revert("worksheet"); + let draft = read(&app, |dialog| dialog.sheet.grid.clone()); + edit(&app, |dialog| dialog.actions.push(Action::Revert)); + pump(&mut app, &crate::testing::ui_context()); + assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), draft); + assert_eq!(data(&mut app, id), saved); + } + /// The app with the window drawn each frame as the shell draws it. // PLAN: the shell's own frame (hub-w2) replaces `host.run` here, and runs `file_asks::poll` (files-w7) itself. fn harness(app: VectorcraftApp) -> Harness { diff --git a/crates/ui-egui/src/dialogs/graph_design.rs b/crates/ui-egui/src/dialogs/graph_design.rs index 04e5e7f0a8..d0302d1e41 100644 --- a/crates/ui-egui/src/dialogs/graph_design.rs +++ b/crates/ui-egui/src/dialogs/graph_design.rs @@ -252,8 +252,11 @@ pub(crate) enum Answer { impl Answer { /// Runs the command; the refusal is its error. fn run(&self, app: &mut VectorcraftApp, target: &GraphTarget) -> Result<(), Label> { - if !target.in_active_document(app) { + let Some(active) = app.session.active().filter(|active| active.uid == target.document.0) else { return Err(Label::from(tl!("This graph design belongs to the document that opened the dialog."))); + }; + if active.reverts != target.document.1 { + return Err(Label::from(tl!("The document was reverted. Reopen this dialog to continue."))); } let design = |d: &Option| json!({ "design": d.as_ref().map(|d| d.name.as_str()), "library": library_of(d.as_ref()) }); let (command, mut params) = match self { @@ -281,21 +284,18 @@ impl Answer { /// The graph and picked series the Column or Marker form opened for. #[derive(Clone)] struct GraphTarget { - document: u64, + document: (u64, u64), graph: u64, series: Vec, } impl GraphTarget { fn selected(app: &VectorcraftApp) -> Result { - let document = app.session.active().ok_or("no document open")?.uid; + let active = app.session.active().ok_or("no document open")?; + let document = (active.uid, active.reverts); let selected = vectorcraft_engine::graph_type_subject(&app.session).map_err(|error| error.to_string())?; Ok(Self { document, graph: selected.id.0, series: selected.series }) } - - fn in_active_document(&self, app: &VectorcraftApp) -> bool { - app.session.active().is_some_and(|active| active.uid == self.document) - } } /// A loaded library's document, for the thumbnails of its designs. @@ -409,7 +409,7 @@ pub(crate) struct GraphDesignDialog { struct Work { actions: Vec, answer: Option<(Answer, GraphTarget)>, - document: Option, + document: Option<(u64, u64)>, } impl GraphDesignDialog { @@ -854,7 +854,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { } } let answered = work.answer.map(|(answer, target)| answer.run(app, &target)); - let same_document = work.document.is_none_or(|document| app.session.active().is_some_and(|active| active.uid == document)); + let same_document = work.document.is_none_or(|document| app.session.active().is_some_and(|active| (active.uid, active.reverts) == document)); let lists = if same_document { Lists::read(app).ok() } else { None }; dialogs.with(|host| { if let Some(dialog) = host.get_mut::() { @@ -956,6 +956,58 @@ mod tests { } } + fn a_graph_design_draft_after_file_revert(graph_kind: &str, command: &str) { + struct SavedFile(std::path::PathBuf); + impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + let (mut app, ctx) = app_with_design(); + select_graph(&mut app, graph_kind); + let graph = app.session.active().unwrap().selection.objects[0].0; + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-graph-design-revert-{}-{graph_kind}.vectorcraft", std::process::id()))); + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + assert!(path.0.is_file()); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [graph]})).unwrap(); + crate::menus::invoke(&mut app, command, json!({})); + set(&app, &ctx, "selected", json!("New Design")).unwrap(); + let state = app.session.active().unwrap(); + let (uid, reverts) = (state.uid, state.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let state = app.session.active().unwrap(); + assert_eq!((state.uid, state.reverts), (uid, reverts + 1)); + app.run("select.set", json!({"ids": [graph]})).unwrap(); + let selected_design = |app: &mut VectorcraftApp| app.session.execute(command, &json!({"id": graph})).unwrap()["design"].clone(); + assert_eq!(selected_design(&mut app), Value::Null); + let undo = app.session.active().unwrap().history.undo.len(); + + app.dialogs().unwrap().with(|host| host.confirm::(&ctx)); + super::pump(&mut app, &ctx); + assert_eq!(selected_design(&mut app), Value::Null, "the stale draft must leave the restored graph's design alone"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(fields(&app)["selected"], "New Design", "the refused answer still shows the draft"); + + crate::menus::invoke(&mut app, command, json!({})); + set(&app, &ctx, "selected", json!("New Design")).unwrap(); + ok(&mut app, &ctx); + assert_eq!(selected_design(&mut app), "New Design", "a fresh draft applies to the restored graph"); + } + + #[test] + fn graph_column_draft_after_file_revert_leaves_the_restored_columns_alone() { + a_graph_design_draft_after_file_revert("column", "graph.column"); + } + + #[test] + fn graph_marker_draft_after_file_revert_leaves_the_restored_markers_alone() { + a_graph_design_draft_after_file_revert("line", "graph.marker"); + } + #[test] fn graph_design_footer_ok_applies_column_and_marker_designs_unless_dismissed() { for (graph_type, command, dismiss) in [("column", "graph.column", false), ("line", "graph.marker", false), ("column", "graph.column", true)] { diff --git a/crates/ui-egui/src/dialogs/graphic_style_options.rs b/crates/ui-egui/src/dialogs/graphic_style_options.rs index 6081982fb2..bf1bbcd0ca 100644 --- a/crates/ui-egui/src/dialogs/graphic_style_options.rs +++ b/crates/ui-egui/src/dialogs/graphic_style_options.rs @@ -7,7 +7,8 @@ //! OK, not by a field, so a name another style has refuses the OK and keeps the dialog open. use craft::ui::contract::Bind; -use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use super::host; @@ -15,8 +16,10 @@ use crate::VectorcraftApp; /// The dialog kind of Graphic Style Options. pub const KIND: &str = "graphicStyleOptions"; +const OPENING: &str = "__opening"; /// What OK does with the name. +#[derive(Deserialize, Serialize)] enum Target { /// Name the style made from the selection. New, @@ -40,15 +43,24 @@ impl Target { /// Open the dialog with `name` in its field; OK runs `target`. fn open_with(app: &mut VectorcraftApp, name: String, target: Target) -> Result { - let document = app.session.active().ok_or("no document open")?.uid; + let active = app.session.active().ok_or("no document open")?; + let mut fields = DialogFields::from_pairs([("name", name.clone())]); + fields.set(OPENING, FieldValue::Json(json!({"uid": active.uid, "reverts": active.reverts, "target": target}))); let params = vec![Param::new("name", tl!("Style Name:").to_string(), ParamKind::text(name.clone()))]; let ctx = app.ui_ctx.clone().ok_or("no window")?; - let dialog = HostedParamDialog::command(&ctx, KIND, DialogFields::from_pairs([("name", name)]), move |fields| { + let dialog = HostedParamDialog::command(&ctx, KIND, fields, move |fields| { ParamDialog::command(KIND, tl!("Graphic Style Options").to_string(), params.clone()).values(Bind::bound(fields)) }); // An `Err` (a name another style has) keeps the dialog open with the reason. - let ok = move |app: &mut VectorcraftApp, result: &ParamResult| { - if !app.session.active().is_some_and(|active| active.uid == document) { + let ok = |app: &mut VectorcraftApp, result: &ParamResult| { + let Some(FieldValue::Json(opening)) = result.fields.get(OPENING) else { return Err("the graphic style target is missing".into()) }; + let document = opening["uid"].as_u64().ok_or("the graphic style target is missing")?; + let target = Target::deserialize(&opening["target"]).map_err(|e| e.to_string())?; + let active = app.session.active(); + if active.is_some_and(|active| active.uid == document && Some(active.reverts) != opening["reverts"].as_u64()) { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } + if !active.is_some_and(|active| active.uid == document) { return Err(tl!("This graphic style belongs to the document that opened the dialog.").to_owned()); } target.run(app, result.fields.text("name").unwrap_or_default()).map(|_| ()) @@ -164,4 +176,45 @@ mod tests { accept(&mut app, id); assert!(names(&app).iter().any(|name| name == "Source style")); } + + #[test] + fn graphic_style_options_leave_restored_definitions_alone() { + for action in ["rename", "merge", "new"] { + let mut app = app(); + let art = app.session.active().unwrap().selection.objects[0]; + app.run("graphicStyle.new", json!({"name": "First"})).unwrap(); + app.run("paint.setFill", json!({"ids": [art.0], "color": "#abcdef"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Second"})).unwrap(); + let saved = names(&app); + let dir = vectorcraft_testkit::TempDir::new("graphic-style-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("object.move", json!({"ids": [art.0], "dx": 10, "dy": 0})).unwrap(); + let open_action = |app: &mut VectorcraftApp| match action { + "rename" => open(app, Some("First")), + "merge" => open_merge(app, vec!["First".into(), "Second".into()]), + _ => open(app, None), + }; + open_action(&mut app).unwrap(); + let id = options(&app); + set(&app, id, "name", json!("Draft Style")); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [art.0]})).unwrap(); + let steps = app.session.active().unwrap().history.undo.len(); + accept(&mut app, id); + assert_eq!(names(&app), saved, "{action}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + assert_eq!(options(&app), id); + + let ctx = app.ui_ctx.clone().unwrap(); + app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, id)); + open_action(&mut app).unwrap(); + let id = options(&app); + set(&app, id, "name", json!("Current Style")); + accept(&mut app, id); + assert!(names(&app).iter().any(|name| name == "Current Style"), "{action}"); + } + } } diff --git a/crates/ui-egui/src/dialogs/host.rs b/crates/ui-egui/src/dialogs/host.rs index ad078b6022..0d61109b67 100644 --- a/crates/ui-egui/src/dialogs/host.rs +++ b/crates/ui-egui/src/dialogs/host.rs @@ -44,6 +44,7 @@ pub(crate) type Cancel = Box; type Drain = Box Option>; struct Record { + id: DialogId, drain: Drain, cancel: Option, } @@ -52,20 +53,39 @@ struct Record { #[derive(Default)] pub(crate) struct Held(Vec); -fn drain(id: DialogId, mut ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static) -> Drain { +impl Held { + fn reopened(&self, id: DialogId) -> bool { + self.0.iter().any(|record| record.id == id) + } +} + +fn drain(id: DialogId, serial: u64, mut ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static) -> Drain { Box::new(move |app| { // Without a window nothing can answer: the dialog counts as cancelled so its rollback runs. let Some(host) = app.dialogs() else { return Some(true) }; + match host.with(|h| h.open_serial(id)) { + None => return host.with(|h| h.take_by_id::(id)).map(|r| matches!(r, DialogResult::Cancel)), + Some(open) if open != serial => return Some(false), + Some(_) => {} + } if let Some(answer) = host.with(|h| h.get_mut_by_id::(id).and_then(D::take_ok)) { // The host's lock is released while `ok` runs: it may open dialogs. let verdict = ok(app, &answer).map_err(Into::into); + // A callback can reopen the same key. Its old verdict cannot answer that opening. + if app.held.reopened(id) { + return Some(false); + } host.with(|h| { - if let Some(d) = h.get_mut_by_id::(id) { + if h.open_serial(id) == Some(serial) + && let Some(d) = h.get_mut_by_id::(id) + { d.answer_ok(verdict); } }); } - host.with(|h| h.take_by_id::(id)).map(|r| matches!(r, DialogResult::Cancel)) + // A replace-by-open can leave the retired opening's Cancel under the same dialog ID. + // A live opening has no final result for this record yet. + None }) } @@ -88,11 +108,16 @@ pub(crate) fn open_held_with( ) -> Option { let host = app.dialogs()?; let dialog = dialog.held_ok(); - let id = host.with(|h| match options.parent { - Some(parent) => h.open_child(dialog, parent), - None => h.open(dialog), - }); - app.held.0.push(Record { drain: drain::(id, ok), cancel: options.cancel }); + let (id, serial) = host.with(|h| { + let id = match options.parent { + Some(parent) => h.open_child(dialog, parent), + None => h.open(dialog), + }; + h.open_serial(id).map(|serial| (id, serial)) + })?; + // A host key can be reopened before the previous result has been pumped. + app.held.0.retain(|record| record.id != id); + app.held.0.push(Record { id, drain: drain::(id, serial, ok), cancel: options.cancel }); Some(id) } @@ -226,6 +251,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { // A drain's `ok` may open held dialogs: those join the records that stay. let mut kept = Vec::new(); for mut record in std::mem::take(&mut app.held.0) { + if app.held.reopened(record.id) { + continue; + } match (record.drain)(app) { None => kept.push(record), Some(true) => { @@ -236,6 +264,119 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { Some(false) => {} } } + kept.retain(|record| !app.held.reopened(record.id)); kept.append(&mut app.held.0); app.held.0 = kept; } + +#[cfg(test)] +mod opening_tests { + use std::cell::RefCell; + use std::rc::Rc; + + use craft::ui::dialog::HeldOk; + use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog}; + use vectorcraft_engine::Session; + + use super::*; + + const KEY: &str = "testHeldOpening"; + + fn app() -> (VectorcraftApp, egui::Context) { + let app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let ctx = app.ui_ctx.clone().unwrap(); + (app, ctx) + } + + fn dialog(ctx: &egui::Context) -> HostedParamDialog { + HostedParamDialog::new(ctx, KEY, DialogFields::new(), |_| ParamDialog::new(KEY, "Test dialog", vec![])) + } + + #[test] + fn held_ok_uses_the_replacement_openings_callback() { + let (mut app, ctx) = app(); + let host = app.dialogs().unwrap(); + let retired = Rc::new(RefCell::new(Vec::new())); + let before = retired.clone(); + let first = open_held(&mut app, dialog(&ctx), move |_, _| { + before.borrow_mut().push("old"); + Ok(()) + }) + .unwrap(); + assert!(host.with(|h| h.cancel_by_id(&ctx, first))); + + let answers = retired.clone(); + let fresh = open_held(&mut app, dialog(&ctx), move |_, _| { + answers.borrow_mut().push("new"); + Ok(()) + }) + .unwrap(); + assert_eq!(first, fresh); + assert!(!host.with(|h| h.confirm_by_id(&ctx, fresh))); + assert_eq!(host.with(|h| h.held_state(fresh)), Some(HeldOk::Waiting)); + pump(&mut app, &ctx); + assert_eq!(*retired.borrow(), ["new"]); + assert_eq!(host.with(|h| h.held_state(fresh)), Some(HeldOk::Accepted)); + } + + #[test] + fn pumping_a_replacement_before_ok_keeps_its_callback() { + let (mut app, ctx) = app(); + let host = app.dialogs().unwrap(); + open_held(&mut app, dialog(&ctx), |_, _| panic!("the retired opening cannot answer")).unwrap(); + + let accepted = Rc::new(RefCell::new(Vec::new())); + let seen = accepted.clone(); + let fresh = open_held(&mut app, dialog(&ctx), move |_, _| { + seen.borrow_mut().push("new"); + Ok(()) + }) + .unwrap(); + + pump(&mut app, &ctx); + assert!(!host.with(|h| h.confirm_by_id(&ctx, fresh))); + pump(&mut app, &ctx); + assert_eq!(*accepted.borrow(), ["new"]); + assert_eq!(host.with(|h| h.held_state(fresh)), Some(HeldOk::Accepted)); + } + + #[test] + fn cancelling_a_replacement_runs_only_its_cancel_callback() { + let (mut app, ctx) = app(); + let host = app.dialogs().unwrap(); + let cancelled = Rc::new(RefCell::new(Vec::new())); + for flag in ["old", "new"] { + let log = cancelled.clone(); + open_held_with( + &mut app, + dialog(&ctx), + |_, _| Ok(()), + HeldOptions { parent: None, cancel: Some(Box::new(move |_| log.borrow_mut().push(flag))) }, + ) + .unwrap(); + } + assert!(host.with(|h| h.cancel_by_id(&ctx, craft::ui::dialog::dialog_id(KEY)))); + pump(&mut app, &ctx); + assert_eq!(*cancelled.borrow(), ["new"]); + } + + #[test] + fn an_old_verdict_does_not_answer_a_replacement_opened_by_its_callback() { + let (mut app, ctx) = app(); + let host = app.dialogs().unwrap(); + let replacement_ctx = ctx.clone(); + let id = open_held(&mut app, dialog(&ctx), move |app, _| { + let id = open_held(app, dialog(&replacement_ctx), |_, _| Ok(())).unwrap(); + let host = app.dialogs().unwrap(); + assert!(!host.with(|h| h.confirm_by_id(&replacement_ctx, id))); + assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Waiting)); + Err("old verdict".into()) + }) + .unwrap(); + assert!(!host.with(|h| h.confirm_by_id(&ctx, id))); + pump(&mut app, &ctx); + assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Waiting)); + pump(&mut app, &ctx); + assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Accepted)); + } +} diff --git a/crates/ui-egui/src/dialogs/hyphenation.rs b/crates/ui-egui/src/dialogs/hyphenation.rs index e9f5b04648..4187c342b9 100644 --- a/crates/ui-egui/src/dialogs/hyphenation.rs +++ b/crates/ui-egui/src/dialogs/hyphenation.rs @@ -9,6 +9,7 @@ //! (letters, 1..15), `hyphenLimit` (hyphens, 0..25, 0: no limit), `hyphenationZone` (pt) and //! `hyphenateCapitalized`, as `text.setFormat` takes them. +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; // PLAN: assumed paths of `UnitKind` and `LengthUnits` use craft::ui::runtime::env::{LengthUnits, UnitKind}; @@ -78,7 +79,9 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let initial = fields.clone(); let ctx = app.ui_ctx.clone().ok_or("no window")?; let lengths = crate::canvas::rulers::general_lengths(app); - let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| ParamDialog::new(KIND, tl!("Hyphenation"), rows(lengths))); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { + ParamDialog::new(KIND, tl!("Hyphenation"), rows(lengths)).values(Bind::bound(fields)) + }); super::host::open_held(app, dialog, move |app, result| { let mut p = params(&result.fields, &initial); if p.is_empty() { @@ -140,6 +143,147 @@ mod tests { } } + /// Actual focused Hyphenation edits keep the hosted draft and apply to both selected paragraphs. + #[test] + fn hyphenation_keeps_focused_edits_until_cancel_or_ok() { + use craft::automation::{ControlRequest, Reply}; + use egui::accesskit::{Node, Role, TreeUpdate}; + use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + fn control(tree: &TreeUpdate, source: &str, role: Role, scope: Option) -> Rect { + fn plain(s: &str) -> &str { + s.trim_end().trim_end_matches([':', ':']).trim_end() + } + fn bounds(node: &Node) -> Option { + let b = node.bounds()?; + Some(Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))) + } + let expected = crate::i18n::t(source); + tree.nodes + .iter() + .map(|(_, n)| n) + .filter(|n| n.role() == role && n.label().is_some_and(|label| plain(label) == plain(expected))) + .filter_map(bounds) + .find(|rect| scope.is_none_or(|scope| scope.contains(rect.center()))) + .unwrap_or_else(|| panic!("missing {role:?} {expected:?} in {scope:?}")) + } + + fn draft(app: &VectorcraftApp, ctx: &egui::Context) -> Value { + let ui = crate::control::inspect(app, ctx); + ui["dialogs"].as_array().unwrap().iter().find(|dialog| dialog["key"] == KIND).expect("open Hyphenation dialog")["fields"].clone() + } + + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let mut failures = Vec::new(); + for lang in ["en", "de", "fr", "ja"] { + for answer in ["Cancel", "OK", "ui.dialog.confirm"] { + let (mut app, id) = app(); + app.session.prefs.interface_language = lang.into(); + app.run("text.setFormat", json!({"ids": [id], "afterFirst": 2, "start": 5, "end": 5})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.1; + let raw = RawInput { events, time: Some(time), screen_rect: Some(screen), focused: true, ..Default::default() }; + crate::testing::app_frame(app, &ctx, raw).platform_output.accesskit_update.unwrap() + }; + let settle = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> TreeUpdate| { + for _ in 0..5 { + frame(app, vec![]); + } + frame(app, vec![]) + }; + let click = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> TreeUpdate, pos| { + frame(app, vec![Event::PointerMoved(pos)]); + for pressed in [true, false] { + frame(app, vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + frame(app, vec![]); + }; + let press = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> TreeUpdate, key, modifiers| { + for pressed in [true, false] { + frame( + app, + vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }], + ); + } + }; + let original = paras(&app, id); + let undo = app.session.active().unwrap().history.undo.len(); + settle(&mut app, &mut frame); + let apply = answer != "Cancel"; + app.run("ui.hyphenation", json!({})).unwrap(); + let tree = settle(&mut app, &mut frame); + let modal = control(&tree, "Hyphenation", Role::Dialog, None); + let count = control(&tree, "Words Longer Than:", Role::SpinButton, Some(modal)); + let enabled = control(&tree, "Hyphenation", Role::CheckBox, Some(modal)); + let footer = control(&tree, if apply { "OK" } else { "Cancel" }, Role::Button, Some(modal)); + assert!(screen.expand(0.5).contains_rect(modal)); + for bounds in [count, enabled, footer] { + assert!(bounds.is_positive() && modal.expand(0.5).contains_rect(bounds), "{lang}: {bounds:?} outside {modal:?}"); + } + let before = driver::fields(&app); + assert_eq!(before.number("wordsLongerThan"), Some(5.0)); + assert_eq!(before.bool("hyphenate"), Some(false)); + assert!(before.is_mixed("afterFirst")); + click(&mut app, &mut frame, count.center()); + press(&mut app, &mut frame, Key::A, Modifiers::COMMAND); + frame(&mut app, vec![Event::ModifiersChanged(Modifiers::NONE), Event::Text("8".into())]); + press(&mut app, &mut frame, Key::Tab, Modifiers::NONE); + settle(&mut app, &mut frame); + let typed = draft(&app, &ctx)["wordsLongerThan"].as_f64(); + click(&mut app, &mut frame, enabled.center()); + let inspected = draft(&app, &ctx); + let kept = (inspected["wordsLongerThan"].as_f64(), inspected["hyphenate"].as_bool()); + eprintln!("{lang}, {answer}: {modal:?}; ui.inspect after typing {typed:?}, after checkbox {kept:?}"); + if typed != Some(8.0) || kept != (Some(8.0), Some(true)) || !driver::fields(&app).is_mixed("afterFirst") { + failures.push(format!("{lang} {answer}: {typed:?}, {kept:?}")); + } + assert_eq!(paras(&app, id), original, "{lang}: only the draft changes while open"); + if answer == "ui.dialog.confirm" { + let (request, _) = ControlRequest::new(answer, json!({})); + match crate::control::handle(&mut app, &ctx, &request) { + Reply::Done(reply) => assert_eq!(reply["ok"], true, "{reply}"), + _ => panic!("confirmation should reply immediately"), + } + } else { + click(&mut app, &mut frame, footer.center()); + } + settle(&mut app, &mut frame); + assert!(!driver::is_open(&app), "{lang}: footer closed the dialog"); + let actual = paras(&app, id); + let undo_delta = app.session.active().unwrap().history.undo.len() - undo; + eprintln!( + "{lang}, {answer}: committed counts {}/{}, hyphenation {}/{}, after first {}/{}, undo {undo_delta}", + actual.0.hyphenation.words_longer_than, + actual.1.hyphenation.words_longer_than, + actual.0.hyphenate, + actual.1.hyphenate, + actual.0.hyphenation.after_first, + actual.1.hyphenation.after_first + ); + if apply { + let mut expected = original.clone(); + for p in [&mut expected.0, &mut expected.1] { + p.hyphenation.words_longer_than = 8; + p.hyphenate = true; + } + if actual != expected || undo_delta != 1 { + failures.push(format!( + "{lang} {answer}: left {:?} and {:?}, undo delta {undo_delta}", + actual.0.hyphenation, actual.1.hyphenation + )); + } + } else { + assert_eq!(actual, original, "{lang}: Cancel discards both edits"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + } + crate::i18n::set_current(crate::i18n::Lang::EN); + } + assert!(failures.is_empty(), "Hyphenation lost physical edits: {failures:?}"); + } + /// `ui.hyphenation` opens the dialog on the selected type; OK sets the paragraphs' hyphenation /// options in one undo step. #[test] diff --git a/crates/ui-egui/src/dialogs/indexed_color.rs b/crates/ui-egui/src/dialogs/indexed_color.rs index b823cd2e71..0f1aec1462 100644 --- a/crates/ui-egui/src/dialogs/indexed_color.rs +++ b/crates/ui-egui/src/dialogs/indexed_color.rs @@ -6,6 +6,7 @@ use std::sync::Arc; +use craft::ui::contract::Bind; use craft::ui::dialog::dialog_id; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::UnitKind; @@ -25,13 +26,22 @@ const PREVIEW_LABEL: &str = "Convert to Indexed Color"; pub(crate) struct Open { document: u64, + reverts: 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) + self.check_drawing(app).is_ok() + } + + fn check_drawing(&self, app: &VectorcraftApp) -> Result<(), &'static str> { + let st = app.session.active().filter(|st| st.uid == self.document).ok_or(tl!("Return to the original drawing to convert its images"))?; + if st.reverts != self.reverts { + return Err(tl!("Reopen Convert to Indexed Color after reverting the drawing")); + } + Ok(()) } fn cancel_preview(self, app: &mut VectorcraftApp) { @@ -77,7 +87,7 @@ fn build(fields: &mut DialogFields) -> ParamDialog<'_> { fields.set("colors", clamped); } } - ParamDialog::new(KIND, tl!("Convert to Indexed Color"), rows()).previews(true) + ParamDialog::new(KIND, tl!("Convert to Indexed Color"), rows()).values(Bind::bound(fields)).previews(true) } /// Open the dialog with the defaults of `edit.colors.toIndexed`. @@ -86,7 +96,7 @@ pub fn open(app: &mut VectorcraftApp) { app.status("no window".to_string()); return; }; - let Some(document) = app.session.active().map(|st| st.uid) else { + let Some((document, reverts)) = app.session.active().map(|st| (st.uid, st.reverts)) else { app.status(tl!("Open a drawing to convert its images")); return; }; @@ -98,9 +108,7 @@ pub fn open(app: &mut VectorcraftApp) { let cancelled = Arc::clone(&opening); let ok = |app: &mut VectorcraftApp, r: &ParamResult| { 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()); - } + open.check_drawing(app)?; if other_preview(app) { app.keep_typing()?; if other_preview(app) { @@ -123,7 +131,7 @@ pub fn open(app: &mut VectorcraftApp) { } }); 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() }); + app.object_dialogs.indexed = Some(Open { document, reverts, opening, preview: LivePreview::default() }); } else { app.status("no window".to_string()); } @@ -180,16 +188,24 @@ fn params(fields: &DialogFields) -> Value { #[cfg(test)] mod tests { use super::*; + use crate::tests::{panel_harness::Panel, picks::dialogs}; + use craft::ui::contract::Role; + use std::collections::BTreeSet; use vectorcraft_engine::Session; fn add_raster(app: &mut VectorcraftApp) -> vectorcraft_doc::NodeId { + add_raster_row(app, &[[200, 30, 90, 255], [20, 40, 220, 255]]) + } + + fn add_raster_row(app: &mut VectorcraftApp, rgba: &[[u8; 4]]) -> vectorcraft_doc::NodeId { app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let width = u32::try_from(rgba.len()).unwrap(); let img = craft_image_codecs::Image::from_raw( - 2, + width, 1, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, - vec![200, 30, 90, 255, 20, 40, 220, 255], + rgba.as_flattened().to_vec(), ) .unwrap(); let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); @@ -199,7 +215,7 @@ mod tests { let id = d.alloc_id(); let im = vectorcraft_doc::ImageObject { key: "pic".into(), - width: 2, + width, height: 1, xf: Default::default(), link: None, @@ -219,6 +235,43 @@ mod tests { &st.doc.images[&im.key] } + #[test] + fn indexed_color_form_edits_update_the_preview_and_confirmation() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let id = add_raster_row(&mut app, &[[200, 30, 90, 255], [20, 40, 220, 255], [220, 240, 70, 255]]); + let original = palette(&app, id).rgba().unwrap().2; + let undo = app.session.doc().unwrap().history.undo.len(); + let mut panel = Panel::new(app, dialogs); + let black_and_white = |panel: &mut Panel| { + panel.click_role("Reduction", Role::COMBO_BOX); + panel.click("Black & White"); + panel.click_role("Dither", Role::COMBO_BOX); + panel.click("No Dither"); + }; + + panel.app().run("ui.indexedColorDialog", json!({})).unwrap(); + panel.frame(); + panel.click_at(panel.rect_role("Colors", Role::SPIN_BUTTON).center()); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("2"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + let preview = palette(&panel.app(), id).rgba().unwrap().2; + assert_eq!(preview.as_chunks::<4>().0.iter().collect::>().len(), 2); + + black_and_white(&mut panel); + let preview = palette(&panel.app(), id).rgba().unwrap().2; + assert_eq!(preview, [0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255, 255]); + panel.click("Cancel"); + assert_eq!(palette(&panel.app(), id).rgba().unwrap().2, original); + assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), undo); + + panel.app().run("ui.indexedColorDialog", json!({})).unwrap(); + black_and_white(&mut panel); + panel.click("OK"); + assert_eq!(palette(&panel.app(), id).rgba().unwrap().2, preview); + assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), undo + 1); + } + #[test] fn commits_the_chosen_palette_as_one_step() { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); @@ -265,4 +318,38 @@ mod tests { crate::dialogs::host::pump(&mut app, &ctx); assert!(palette(&app, source).indexed_png()); } + + #[test] + fn indexed_color_preview_and_ok_leave_reloaded_pixels_unchanged() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let dir = vectorcraft_testkit::TempDir::new("indexed-color-image-revert"); + let image = add_raster(&mut app); + app.run("file.saveAs", json!({"path": dir.join("raster.vectorcraft")})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [image.0]})).unwrap(); + open(&mut app); + let st = app.session.active().unwrap(); + let version = (st.uid, st.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.uid, version.0); + assert_ne!(st.reverts, version.1); + let undo = st.history.undo.len(); + app.run("select.set", json!({"ids": [image.0]})).unwrap(); + let before = palette(&app, image).rgba().unwrap().2; + + let id = dialog_id(KIND); + crate::tests::picks::answer_dialog( + &mut app, + id, + &[("reduction", json!("blackWhite")), ("dither", json!("none")), ("preview", json!(true))], + false, + ); + assert_eq!(palette(&app, image).rgba().unwrap().2, before, "old Preview leaves the saved pixels in place"); + crate::tests::picks::answer_dialog(&mut app, id, &[("preview", json!(false))], true); + assert_eq!(palette(&app, image).rgba().unwrap().2, before, "old OK leaves the saved pixels in place"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } } diff --git a/crates/ui-egui/src/dialogs/justification.rs b/crates/ui-egui/src/dialogs/justification.rs index ebeeab02d1..d29451406b 100644 --- a/crates/ui-egui/src/dialogs/justification.rs +++ b/crates/ui-egui/src/dialogs/justification.rs @@ -38,7 +38,7 @@ pub(crate) struct Open { /// The dialog on the host. pub id: DialogId, /// The drawing that owns the text IDs and the preview. - document: u64, + document: (u64, u64), /// The preview on the canvas. pub preview: LivePreview, /// The `ids`, `start` and `end` the dialog's `text.setFormat` acts on. @@ -52,7 +52,7 @@ pub(crate) struct Open { impl Open { fn in_opening_document(&self, app: &VectorcraftApp) -> bool { - app.session.active().is_some_and(|st| st.uid == self.document) + app.session.active().is_some_and(|st| (st.uid, st.reverts) == self.document) } } @@ -118,7 +118,8 @@ fn form(fields: &mut DialogFields) -> ParamDialog<'_> { /// Open Justification on the paragraph attributes the Paragraph panel shows. pub fn open(app: &mut VectorcraftApp) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; - let document = app.session.active().ok_or("no document open")?.uid; + let active = app.session.active().ok_or("no document open")?; + let document = (active.uid, active.reverts); // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); let mut story = None; @@ -148,8 +149,13 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let id = super::host::open_held(app, dialog, |app, result| { let Some(open) = app.justification.take() else { return Ok(()) }; if !open.in_opening_document(app) { + let message = if app.session.active().is_some_and(|st| st.uid == open.document.0) { + tl!("The document was reverted. Reopen this dialog to continue.") + } else { + tl!("This dialog was opened in a different document.") + }; app.justification = Some(open); - return Err(tl!("This dialog was opened in a different document.").to_owned()); + return Err(message.to_owned()); } let p = params(app, &result.fields, &open); if !changes(&p) { @@ -215,7 +221,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut open) = app.justification.take() else { return }; let shown = app.dialogs().and_then(|d| d.with(|h| h.get_mut_by_id::(open.id).map(|d| (d.is_previewing(), d.fields().clone())))); - // A document switch ends that document's preview. The active drawing may have started a different one. + // A document switch or revert ends the opening preview. The active drawing may have started a different one. if !open.in_opening_document(app) { if shown.is_some() { open.preview = LivePreview::default(); @@ -604,4 +610,34 @@ mod tests { assert_eq!(paras(&app, id).0.justification.auto_leading, 190.0); assert!(app.session.in_interaction()); } + + #[test] + fn justification_does_not_preview_or_apply_after_revert() { + let (mut app, id) = app(); + let dir = vectorcraft_testkit::TempDir::new("justification-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("text.setFormat", json!({"ids": [id], "autoLeading": 145})).unwrap(); + app.run("ui.justification", json!({})).unwrap(); + driver::set(&mut app, "autoLeading", json!(180)); + driver::set(&mut app, "preview", json!(true)); + driver::pump(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + driver::pump(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0); + let dialog = craft::ui::dialog::dialog_id(KIND); + crate::tests::picks::answer_dialog(&mut app, dialog, &[], true); + assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0); + assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog)), Some(craft::ui::dialog::HeldOk::Refused(_)))); + + driver::cancel(&mut app); + app.run("ui.justification", json!({})).unwrap(); + driver::set(&mut app, "autoLeading", json!(180)); + driver::ok(&mut app); + assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0); + } } diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets.rs b/crates/ui-egui/src/dialogs/kinsoku_sets.rs index 6eb690989d..8c9c5075f5 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets.rs @@ -55,7 +55,8 @@ fn categories() -> [(&'static str, &'static str); 4] { /// What OK files for the pump: the document the dialog opened on, the names of its sets then, and the sets. #[derive(Clone)] struct Request { - doc: Option, + doc: u64, + reverts: u64, opened: Vec, sets: Value, } @@ -63,8 +64,9 @@ struct Request { /// The Kinsoku Shori Settings dialog on the host. pub(crate) struct KinsokuDialog { id: DialogId, - /// The uid of the document the dialog opened on, which OK sets the sets of. - doc: Option, + /// The drawing and its saved-content generation when the dialog opened. + doc: u64, + reverts: u64, /// The names of that document's sets when the dialog opened: OK keeps the sets the document gained /// since, after the dialog's own, and New's suggestion skips these names. opened: Vec, @@ -84,7 +86,7 @@ pub(crate) struct KinsokuDialog { /// Open Kinsoku Shori Settings on the active document's custom sets, the first one picked. pub fn open(app: &mut VectorcraftApp) -> Result { let st = app.session.active().ok_or("no document open")?; - let dialog = KinsokuDialog::new(st.uid, st.doc.kinsoku_sets.iter()); + let dialog = KinsokuDialog::new(st.uid, st.reverts, st.doc.kinsoku_sets.iter()); app.dialogs().ok_or("no window")?.with(|host| host.open(dialog)); Ok(Value::Null) } @@ -176,10 +178,11 @@ fn text_of(field: &str, value: &Value) -> Result { } impl KinsokuDialog { - fn new<'a>(doc: u64, document_sets: impl Iterator + Clone) -> Self { + fn new<'a>(doc: u64, reverts: u64, document_sets: impl Iterator + Clone) -> Self { let mut d = KinsokuDialog { id: dialog_id(COMMAND), - doc: Some(doc), + doc, + reverts, opened: document_sets.clone().map(|k| k.name.clone()).collect(), sets: Value::Array(document_sets.map(listed).collect()), selected: 0, @@ -340,7 +343,7 @@ impl KinsokuDialog { } self.commit(); self.problem = None; - self.held.file(Request { doc: self.doc, opened: self.opened.clone(), sets: self.sets.clone() }); + self.held.file(Request { doc: self.doc, reverts: self.reverts, opened: self.opened.clone(), sets: self.sets.clone() }); } /// The answer OK filed, once. @@ -517,7 +520,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { let Some(host) = app.dialogs() else { return }; let Some(request) = host.with(|h| h.get_mut::().and_then(KinsokuDialog::take_ok)) else { return }; let answer = apply(app, &request); - let gone = answer.is_err() && !app.session.documents().iter().any(|d| Some(d.uid) == request.doc); + let gone = answer.is_err() && !app.session.documents().iter().any(|d| d.uid == request.doc); // The command ran outside the host's lock, which a dialog's own methods take. host.with(|h| { if let Some(d) = h.get_mut::() { @@ -530,8 +533,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { } fn apply(app: &mut VectorcraftApp, request: &Request) -> Result<(), String> { - if app.session.active().map(|st| st.uid) != request.doc { - let index = app.session.documents().iter().position(|d| Some(d.uid) == request.doc).ok_or("that document is no longer open")?; + let (index, document) = + app.session.documents().iter().enumerate().find(|(_, st)| st.uid == request.doc).ok_or("that document is no longer open")?; + if document.reverts != request.reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + if app.session.active().is_none_or(|st| st.uid != request.doc) { app.run("document.activate", json!({ "index": index }))?; } // A `sets` that is not a list of sets goes to the command as it is, which refuses it. diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs index 887dbbc202..7d1755f51c 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs @@ -226,6 +226,47 @@ fn ok_sets_the_document_the_dialog_opened_on() { assert!(app.session.documents().iter().all(|d| d.doc.kinsoku_sets.is_empty())); } +#[test] +fn old_ok_keeps_restored_kinsoku_rules_and_the_current_tab() { + let mut app = app(); + app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Custom", "cannotStart": "ゝ"}]})).unwrap(); + let file = std::env::temp_dir().join(format!("vectorcraft-kinsoku-revert-{}.vectorcraft", std::process::id())); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": file.to_string_lossy()})).unwrap(); + let st = app.session.active().unwrap(); + let (uid, reverts) = (st.uid, st.reverts); + + app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Custom", "cannotStart": "ゞ"}]})).unwrap(); + open(&mut app).unwrap(); + set(&app, "cannotStart", json!("ー")); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let _ = std::fs::remove_file(file); + let st = app.session.active().unwrap(); + assert_eq!((st.uid, st.reverts), (uid, reverts + 1)); + assert_eq!(doc_sets(&app)[0].cannot_start, ['ゝ']); + let undo = steps(&app); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let other = app.session.active().unwrap().uid; + assert_ne!(uid, other); + + pump(&mut app); + let restored = app.session.documents().iter().find(|st| st.uid == uid).unwrap(); + assert_eq!(restored.doc.kinsoku_sets[0].cannot_start, ['ゝ'], "an old OK must keep the saved line-breaking rule"); + assert_eq!(restored.history.undo.len(), undo); + assert_eq!(app.session.active().unwrap().uid, other, "a stale OK does not activate the original tab"); + assert!(is_open(&app)); + dialog(&app, |d| assert_eq!(d.problem.as_deref(), Some("The document was reverted. Reopen this dialog to continue."))); + cancel(&app); + + assert!(app.session.set_active(0)); + open(&mut app).unwrap(); + set(&app, "cannotStart", json!("ー")); + pump(&mut app); + assert!(!is_open(&app)); + assert_eq!(doc_sets(&app)[0].cannot_start, ['ー'], "a fresh draft can edit the restored rule"); +} + /// OK keeps a set the document gained while the dialog was open, after the dialog's sets, and a /// set deleted in the dialog stays deleted. A `sets` field that is not a list of sets keeps the /// dialog open and leaves the document's sets as they are, and New refuses to start from it. diff --git a/crates/ui-egui/src/dialogs/live_paint_gaps.rs b/crates/ui-egui/src/dialogs/live_paint_gaps.rs index f03b2167e5..388ded4a68 100644 --- a/crates/ui-egui/src/dialogs/live_paint_gaps.rs +++ b/crates/ui-egui/src/dialogs/live_paint_gaps.rs @@ -52,15 +52,15 @@ 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 drawing and loaded contents that own the preview interaction. + document: (u64, 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) { + if app.session.active().is_some_and(|active| (active.uid, active.reverts) == self.document) { self.preview.cancel(app); } } @@ -69,7 +69,7 @@ impl Open { /// 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 active = app.session.active().ok_or("select a Live Paint group")?; - let document = active.uid; + let (document, reverts) = (active.uid, active.reverts); let groups: Vec = active .selection .objects @@ -87,13 +87,13 @@ 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, "document": document })).ok_or("no window")?; + option_form::open(app, &SPEC, values, json!({ "ids": groups, "document": document, "reverts": reverts })).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) +fn original_document(app: &VectorcraftApp, extra: &Value) -> Option<(u64, u64)> { + let document = (extra["document"].as_u64()?, extra["reverts"].as_u64()?); + app.session.active().filter(|active| (active.uid, active.reverts) == document).map(|_| document) } /// `livePaint.gapOptions` parameters from the values and the groups in `extra`. @@ -128,7 +128,13 @@ 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 document = original_document(app, extra).ok_or_else(|| tl!(WRONG_DOCUMENT).to_owned())?; + let document = original_document(app, extra).ok_or_else(|| { + if app.session.active().is_some_and(|active| extra["document"].as_u64() == Some(active.uid)) { + tl!("The document was reverted. Reopen this dialog to continue.").to_owned() + } 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)) } @@ -338,6 +344,44 @@ mod tests { assert_eq!(options(&app, group), GapOptions::default()); } + #[test] + fn gap_preview_and_ok_do_not_edit_live_paint_restored_by_revert() { + let mut app = app(); + let dir = vectorcraft_testkit::TempDir::new("live-paint-gap-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let group = gapped_group(&mut app); + let saved = options(&app, group); + app.run("file.saveAs", json!({"path": dir.join("Live Paint.vectorcraft")})).unwrap(); + app.run("shape.rectangle", json!({"x": 140, "y": 140, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + app.run("ui.livePaintGapOptions", json!({})).unwrap(); + set(&app, "detect", json!(true)).unwrap(); + set(&app, "preview", json!(true)).unwrap(); + pump_all(&mut app); + assert!(options(&app, group).detect); + + let source = app.session.active().unwrap(); + let (uid, reverts) = (source.uid, source.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let current = app.session.active().unwrap(); + assert_eq!((current.uid, current.reverts), (uid, reverts + 1)); + let undo = current.history.undo.len(); + pump_all(&mut app); + assert_eq!(options(&app, group), saved); + assert!(overlays(&app).is_empty()); + assert!(!press_ok(&mut app)); + assert_eq!(options(&app, group), saved); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + cancel(&mut app); + + app.run("select.set", json!({"ids": [group]})).unwrap(); + app.run("ui.livePaintGapOptions", json!({})).unwrap(); + set(&app, "detect", json!(true)).unwrap(); + assert!(press_ok(&mut app)); + assert!(options(&app, group).detect); + } + #[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/new_brush.rs b/crates/ui-egui/src/dialogs/new_brush.rs index 7fcb8ca726..81659dda3c 100644 --- a/crates/ui-egui/src/dialogs/new_brush.rs +++ b/crates/ui-egui/src/dialogs/new_brush.rs @@ -25,7 +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 (document, reverts) = (st.uid, st.reverts); let art = match &ids { Some(ids) => ids.as_array().is_some_and(|a| !a.is_empty()), None => !st.selection.is_empty(), @@ -38,8 +38,11 @@ pub fn open(app: &mut VectorcraftApp, ids: Option) -> Result) -> Result { let st = app.session.active().ok_or("no document open")?; - let document = st.uid; + let (document, reverts) = (st.uid, st.reverts); let art = !st.selection.is_empty(); let mut fields = DialogFields::new(); fields.set("name", st.doc.free_swatch_name("Color Group")); @@ -38,8 +38,11 @@ pub fn open(app: &mut VectorcraftApp, swatches: Vec) -> Result Result<(), String> { - if !app.session.active().is_some_and(|active| active.uid == document) { + let Some(source) = app.session.active().filter(|active| active.uid == document) else { return Err(tl!("Create this color group in the document that opened the dialog.").to_owned()); + }; + if source.reverts != reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); } app.run("swatch.newGroup", params(&answer.fields, &swatches)).map(|_| ()) }; @@ -65,6 +68,36 @@ mod tests { use super::*; + #[test] + fn a_color_group_draft_cannot_change_the_drawing_restored_by_revert() { + for swatches in [vec!["Saved Ink".to_owned()], Vec::new()] { + let dir = vectorcraft_testkit::TempDir::new("new-color-group-revert"); + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [id], "color": "#123456"})).unwrap(); + app.run("swatch.new", json!({"name": "Saved Ink", "color": "#446688"})).unwrap(); + app.run("file.saveAs", json!({"path": dir.join("Saved.vectorcraft")})).unwrap(); + app.run("paint.setFill", json!({"ids": [id], "color": "#abcdef"})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let before = app.session.active().unwrap(); + let (uid, reverts) = (before.uid, before.reverts); + open(&mut app, swatches).unwrap(); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let loaded = app.session.active().unwrap(); + assert_eq!((loaded.uid, loaded.reverts), (uid, reverts + 1)); + let (saved, undo) = (loaded.doc.clone(), loaded.history.undo.len()); + let refused = crate::dialogs::tests_export::try_confirm(&mut app); + let current = app.session.active().unwrap(); + assert_eq!(current.doc, saved); + assert_eq!(current.history.undo.len(), undo); + assert_eq!(refused.unwrap_err(), "The document was reverted. Reopen this dialog to continue."); + } + } + #[test] fn color_group_does_not_convert_the_other_drawings_artwork() { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); diff --git a/crates/ui-egui/src/dialogs/objects_on_path_options.rs b/crates/ui-egui/src/dialogs/objects_on_path_options.rs index 2233691bf2..cfc699334e 100644 --- a/crates/ui-egui/src/dialogs/objects_on_path_options.rs +++ b/crates/ui-egui/src/dialogs/objects_on_path_options.rs @@ -58,3 +58,143 @@ pub fn open(app: &mut VectorcraftApp) -> Value { } json!({ "dialog": KIND }) } + +/// The compact tool options expose translated Pivot corners and accept actual edits. +#[cfg(test)] +#[test] +fn compact_objects_on_path_options_pivot_rotate_reset_and_save() { + use egui::accesskit::{Node, Role, TreeUpdate}; + use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + use vectorcraft_engine::Session; + + fn bounds(node: &Node) -> Option { + let b = node.bounds()?; + Some(Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))) + } + + fn plain_label(label: &str) -> &str { + label.trim_end().trim_end_matches([':', ':']).trim_end() + } + + const PIVOT_NAMES: [&str; 9] = ["Top Left", "Top", "Top Right", "Left", "Center", "Right", "Bottom Left", "Bottom", "Bottom Right"]; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let mut untranslated = Vec::new(); + for lang in ["en", "de", "fr", "ja"] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.session.prefs.interface_language = lang.into(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("tool.setOption", json!({"tool": TOOL, "values": {"pivot": 1,"rotate": 17}})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.1; + let raw = RawInput { events, time: Some(time), screen_rect: Some(screen), focused: true, ..Default::default() }; + crate::testing::app_frame(app, &ctx, raw).platform_output.accesskit_update.unwrap() + }; + let settle = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> TreeUpdate| { + for _ in 0..5 { + frame(app, vec![]); + } + frame(app, vec![]) + }; + let click = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> TreeUpdate, pos| { + frame(app, vec![Event::PointerMoved(pos)]); + for pressed in [true, false] { + frame(app, vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + frame(app, vec![]); + }; + let press = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> TreeUpdate, key, modifiers| { + for pressed in [true, false] { + frame(app, vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }]); + } + }; + let draft = |app: &VectorcraftApp| { + app.dialogs() + .unwrap() + .with(|host| host.get::().map(|d| (d.fields().int("pivot").unwrap(), d.fields().number("rotate").unwrap()))) + }; + let actual = |app: &VectorcraftApp| { + let options = app.session.tool_options_of(TOOL); + (options["pivot"].as_i64().unwrap(), options["rotate"].as_f64().unwrap()) + }; + settle(&mut app, &mut frame); + for save in [false, true] { + assert_eq!(app.run("tool.options", json!({"tool": TOOL})).unwrap()["dialog"], KIND); + let tree = settle(&mut app, &mut frame); + let by_name = |role, label: &str| { + tree.nodes + .iter() + .find(|(_, n)| { + n.role() == role + && n.label().is_some_and(|actual| { + plain_label(actual) == plain_label(label) + || (role == Role::RadioGroup && plain_label(actual) == plain_label(crate::i18n::t("Pivot:"))) + }) + }) + .and_then(|(_, n)| bounds(n)) + .unwrap_or_else(|| { + let names: Vec<_> = tree.nodes.iter().filter(|(_, n)| n.role() == role).filter_map(|(_, n)| n.label()).collect(); + panic!("{lang}: missing {role:?} {label:?} in {names:?}") + }) + }; + let title = tool_options::title(TOOL); + let modal = by_name(Role::Dialog, title.as_str()); + let picker = by_name(Role::RadioGroup, crate::i18n::t("Reference Point")); + let rotate = by_name(Role::SpinButton, crate::i18n::t("Rotate:")); + let reset = by_name(Role::Button, crate::i18n::t("Reset")); + let footer = by_name(Role::Button, crate::i18n::t(if save { "Save" } else { "Cancel" })); + assert!(screen.expand(0.5).contains_rect(modal), "{lang}: modal {modal:?} off screen"); + for rect in [picker, rotate, reset, footer] { + assert!(rect.is_positive() && modal.expand(0.5).contains_rect(rect), "{lang}: {rect:?} outside modal {modal:?}"); + } + let mut cells: Vec<_> = tree + .nodes + .iter() + .filter(|(_, n)| n.role() == Role::RadioButton) + .filter_map(|(_, n)| Some((n.label()?, bounds(n)?))) + .filter(|(_, rect)| picker.expand(0.5).contains(rect.center())) + .collect(); + cells.sort_by(|(_, a), (_, b)| a.center().y.total_cmp(&b.center().y).then(a.center().x.total_cmp(&b.center().x))); + eprintln!( + "{lang}, save {save}: modal {modal:?}, pivot {picker:?}, cells {cells:?}, Rotate {rotate:?}, Reset {reset:?}, footer {footer:?}" + ); + assert_eq!(cells.len(), 9, "{lang}: all Pivot options"); + if save { + for ((name, _), legacy) in cells.iter().zip(PIVOT_NAMES) { + let expected = crate::i18n::t(legacy); + if expected != legacy && *name != expected { + untranslated.push(format!("{lang}: {name:?} instead of {expected:?}")); + } + } + } + assert!(cells.iter().all(|(_, cell)| picker.expand(0.5).contains_rect(*cell)), "{lang}: all cells lie in the picker"); + assert_eq!(draft(&app), Some((1, 17.0)), "{lang}: opens from saved tool preferences"); + click(&mut app, &mut frame, cells[8].1.center()); + assert_eq!(draft(&app), Some((8, 17.0)), "{lang}: bottom-right physical pointer"); + click(&mut app, &mut frame, rotate.center()); + press(&mut app, &mut frame, Key::A, Modifiers::COMMAND); + frame(&mut app, vec![Event::ModifiersChanged(Modifiers::NONE), Event::Text("42".to_owned())]); + press(&mut app, &mut frame, Key::Tab, Modifiers::NONE); + settle(&mut app, &mut frame); + assert_eq!(draft(&app), Some((8, 42.0)), "{lang}: real Rotate keyboard edit"); + if !save { + click(&mut app, &mut frame, reset.center()); + assert_eq!(draft(&app), Some((4, 0.0)), "{lang}: pointer Reset keeps the dialog open and resets both settings"); + } + assert_eq!(actual(&app), (1, 17.0), "{lang}: only a draft before accepting"); + click(&mut app, &mut frame, footer.center()); + settle(&mut app, &mut frame); + assert_eq!(draft(&app), None, "{lang}: footer closes the dialog"); + assert_eq!(actual(&app), if save { (8, 42.0) } else { (1, 17.0) }, "{lang}: footer persistence"); + } + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + settle(&mut app, &mut frame); + assert_eq!(draft(&app), Some((8, 42.0)), "{lang}: reopened saved values"); + press(&mut app, &mut frame, Key::Escape, Modifiers::NONE); + settle(&mut app, &mut frame); + assert_eq!(draft(&app), None, "{lang}: Escape dismisses reopened options"); + crate::i18n::set_current(crate::i18n::Lang::EN); + } + assert!(untranslated.is_empty(), "localized Pivot names were lost: {untranslated:?}"); +} diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 65179c95ca..12205dca03 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -129,6 +129,7 @@ pub(crate) struct Open { pub(crate) struct SplitOpen { id: DialogId, document: u64, + reverts: u64, preview: LivePreview, /// An interaction allocates its own selection snapshot, even when the selected objects did not change. preview_selection: Option>, @@ -139,12 +140,13 @@ impl SplitOpen { let Some(selection) = &self.preview_selection else { return false }; app.session.active().is_some_and(|state| { state.uid == self.document + && state.reverts == self.reverts && 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 }; + let Some(state) = app.session.active().filter(|state| state.uid == self.document && state.reverts == self.reverts) else { return }; if !self.owns_preview(app) { self.preview = LivePreview::default(); self.preview_selection = None; @@ -162,8 +164,11 @@ impl SplitOpen { } fn confirm(&mut self, app: &mut VectorcraftApp, fields: &DialogFields) -> Result<(), String> { - if app.session.active().is_none_or(|state| state.uid != self.document) { + let Some(state) = app.session.active().filter(|state| state.uid == self.document) else { return Err(tl!("Split Into Grid can only change the document where it was opened.").to_owned()); + }; + if state.reverts != self.reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").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()); @@ -512,6 +517,7 @@ pub(crate) fn open_split(app: &mut VectorcraftApp) { return; }; let document = state.uid; + let reverts = state.reverts; 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| { @@ -525,7 +531,7 @@ pub(crate) fn open_split(app: &mut VectorcraftApp) { old.cancel(app); } match open_held(app, dialog, ok) { - Some(id) => app.object_dialogs.split = Some(SplitOpen { id, document, preview: LivePreview::default(), preview_selection: None }), + Some(id) => app.object_dialogs.split = Some(SplitOpen { id, document, reverts, preview: LivePreview::default(), preview_selection: None }), None => app.status("There is no window to show the dialog in."), } } @@ -618,6 +624,7 @@ pub(crate) fn original_paths(app: &VectorcraftApp) -> Vec<(NodeId, &PathData)> { #[cfg(test)] mod split_tests { + use craft::ui::dialog::HeldOk; use serde_json::json; use super::*; @@ -633,6 +640,65 @@ mod split_tests { selected_rectangle(app, 150, 90); } + fn grid_after_file_revert(hold_ok: bool) -> VectorcraftApp { + let mut app = app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let folder = vectorcraft_testkit::TempDir::new("split-into-grid-revert"); + let path = folder.join("drawing.vectorcraft"); + selected_rectangle(&mut app, 112, 62); + let original = app.session.active().unwrap().selection.objects[0]; + app.run("file.saveAs", json!({"path": path})).unwrap(); + selected_rectangle(&mut app, 50, 30); + app.run("select.set", json!({"ids": [original.0]})).unwrap(); + let source = app.session.active().unwrap(); + let (uid, generation) = (source.uid, source.reverts); + open_split(&mut app); + set(&mut app, "columns", json!(3)); + set(&mut app, "preview", json!(false)); + if hold_ok { + let ctx = app.ui_ctx.clone().unwrap(); + let id = app.object_dialogs.split.as_ref().unwrap().id; + assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id))); + } + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let reloaded = app.session.active().unwrap(); + assert_eq!(reloaded.uid, uid); + assert_ne!(reloaded.reverts, generation); + app.run("select.set", json!({"ids": [original.0]})).unwrap(); + app + } + + #[test] + fn grid_revert_ignores_the_previous_generations_preview() { + let mut app = grid_after_file_revert(false); + let restored = app.session.active().unwrap().doc.clone(); + set(&mut app, "preview", json!(true)); + frame(&mut app, vec![]); + assert!(app.session.active().unwrap().doc == restored, "old grid preview reached the restored drawing"); + assert!(!app.session.in_interaction()); + } + + #[test] + fn grid_revert_ignores_a_held_ok_and_accepts_a_fresh_opening() { + let mut app = grid_after_file_revert(true); + let restored = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let id = app.object_dialogs.split.as_ref().unwrap().id; + frame(&mut app, vec![]); + assert!(app.session.active().unwrap().doc == restored, "old grid OK reached the restored drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + let Some(HeldOk::Refused(message)) = app.dialogs().unwrap().with(|host| host.held_state(id)) else { panic!("expected a held refusal") }; + assert_eq!(message.as_str(), "The document was reverted. Reopen this dialog to continue."); + assert!(cancel(&mut app)); + open_split(&mut app); + set(&mut app, "columns", json!(3)); + assert!(confirm(&mut app)); + let active = app.session.active().unwrap(); + assert_eq!(active.doc.layers[0].children().unwrap().len(), 6); + assert_eq!(active.history.undo.len(), undo + 1); + } + #[test] fn split_into_grid_skips_preview_in_the_other_drawing() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/perspective_grid.rs b/crates/ui-egui/src/dialogs/perspective_grid.rs index d75a811a74..f899a9d7e9 100644 --- a/crates/ui-egui/src/dialogs/perspective_grid.rs +++ b/crates/ui-egui/src/dialogs/perspective_grid.rs @@ -134,7 +134,7 @@ fn open_on(app: &mut VectorcraftApp, def: GridDefinition, mode: GridMode) -> Res let dialog = GridDialog::new( def, mode, - app.session.active().map(|st| st.uid), + app.session.active().map(|st| (st.uid, st.reverts)), (general_lengths(app).pixels_per_inch, app.session.prefs.numbers_without_units_are_points), app.session.perspective_presets(), app.session.new_perspective_preset_name(), @@ -172,8 +172,8 @@ pub fn open_edit(app: &mut VectorcraftApp, original: Option<&str>, base: &str) - pub(super) struct GridDialog { id: DialogId, mode: GridMode, - /// The document whose grid Define Grid edits. - source_document: Option, + /// The document and loaded contents whose grid Define Grid edits. + source_document: Option<(u64, u64)>, draft: GridDraft, /// The presets the Preset row offers, as the document and the preferences have them. presets: Vec, @@ -196,7 +196,7 @@ impl GridDialog { fn new( def: GridDefinition, mode: GridMode, - source_document: Option, + source_document: Option<(u64, u64)>, (ppi, bare_points): (f64, bool), presets: Vec, new_name: String, @@ -527,12 +527,16 @@ enum Next { Presets(String), } -fn file(app: &mut VectorcraftApp, mode: &GridMode, source_document: Option, def: &GridDefinition) -> Result { +fn file(app: &mut VectorcraftApp, mode: &GridMode, source_document: Option<(u64, u64)>, def: &GridDefinition) -> Result { let mut params = serde_json::to_value(def).map_err(|e| e.to_string())?; if *mode == GridMode::Define { - if app.session.active().map(|st| st.uid) != source_document { + let active = app.session.active().map(|st| (st.uid, st.reverts)); + if active.map(|(uid, _)| uid) != source_document.map(|(uid, _)| uid) { return Err(tl!("Define Grid can only change the document where it was opened.").to_owned()); } + if active != source_document { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } app.run("perspective.grid.define", params)?; return Ok(Next::Close); } diff --git a/crates/ui-egui/src/dialogs/perspective_options.rs b/crates/ui-egui/src/dialogs/perspective_options.rs index 7db0191871..87d3269327 100644 --- a/crates/ui-egui/src/dialogs/perspective_options.rs +++ b/crates/ui-egui/src/dialogs/perspective_options.rs @@ -5,6 +5,7 @@ //! Fields: `show` (bool), `position` (`topLeft`, `topRight`, `bottomLeft`, `bottomRight`), //! `anchorPoint` (bool) and `gridlineIntersection` (bool). +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; use serde_json::{Value, json}; use vectorcraft_tools::distort::perspective::widget::WidgetCorner; @@ -31,8 +32,8 @@ fn params() -> Vec { ] } -fn build(_fields: &mut DialogFields) -> ParamDialog<'_> { - ParamDialog::new(KIND, tl!("Perspective Grid Options"), params()) +fn build(fields: &mut DialogFields) -> ParamDialog<'_> { + ParamDialog::new(KIND, tl!("Perspective Grid Options"), params()).values(Bind::bound(fields)) } /// Open the dialog with the current options. @@ -51,3 +52,39 @@ pub fn open(app: &mut VectorcraftApp) { app.status("no window".to_string()); } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::{panel_harness::Panel, picks::dialogs}; + use craft::ui::contract::Role; + use vectorcraft_engine::Session; + + fn open_options(panel: &mut Panel) { + panel.app().run("tool.options", json!({"tool": "perspectiveGrid"})).unwrap(); + panel.frame(); + } + + #[test] + fn perspective_grid_options_show_and_apply_widget_preferences() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.perspective_widget.position = WidgetCorner::BottomRight; + let mut panel = Panel::new(app, dialogs); + open_options(&mut panel); + + assert_eq!(panel.value_role("Widget Position", Role::COMBO_BOX).as_deref(), Some("Bottom Right")); + panel.click_role("Widget Position", Role::COMBO_BOX); + panel.click("Top Right"); + panel.click("Intersection of Gridlines"); + panel.click("OK"); + let saved = panel.app().session.prefs.perspective_widget; + assert_eq!(saved.position, WidgetCorner::TopRight); + assert!(!saved.gridline_intersection); + + open_options(&mut panel); + assert_eq!(panel.value_role("Widget Position", Role::COMBO_BOX).as_deref(), Some("Top Right")); + panel.click("Show Active Plane Widget"); + panel.click("Cancel"); + assert_eq!(panel.app().session.prefs.perspective_widget, saved); + } +} diff --git a/crates/ui-egui/src/dialogs/placement_options.rs b/crates/ui-egui/src/dialogs/placement_options.rs index f647a20f69..b58aec49f2 100644 --- a/crates/ui-egui/src/dialogs/placement_options.rs +++ b/crates/ui-egui/src/dialogs/placement_options.rs @@ -16,6 +16,7 @@ use crate::VectorcraftApp; use crate::dialogs::tool_options::reference_param; const KEY: &str = "placementOptions"; +const OPENING: &str = "__opening"; const CMD: &str = "links.placementOptions"; /// (value, label) of each Preserve choice. const PRESERVE: [(&str, &str); 5] = [ @@ -43,16 +44,18 @@ 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 active = app.session.active().ok_or("no document open")?; + let source = (active.uid, active.reverts); 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"]; let align = ALIGN.iter().position(|a| Some(*a) == placement["align"].as_str()).unwrap_or(CENTRE); - let fields = DialogFields::from_pairs([ + let mut fields = DialogFields::from_pairs([ ("preserve", FieldValue::Text(placement["preserve"].as_str().unwrap_or("transforms").to_owned())), ("align", FieldValue::Int(align as i64)), ("clip", FieldValue::Bool(placement["clip"].as_bool().unwrap_or(false))), ]); + fields.set(OPENING, FieldValue::Json(json!({"uid": source.0, "reverts": source.1, "ids": ids}))); let ctx = app.ui_ctx.clone().ok_or("no window")?; let dialog = HostedParamDialog::new(&ctx, KEY, fields, |fields| { ParamDialog::new(KEY, tl!("Placement Options"), params()) @@ -60,13 +63,17 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { .footer_note(tl!("Applies when the linked file is relinked or updated.")) }) .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()); - } + crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| { let f = &result.fields; + let Some(FieldValue::Json(opening)) = f.get(OPENING) else { return Err("the Placement Options target is missing".into()) }; + let Some(active) = app.session.active().filter(|document| Some(document.uid) == opening["uid"].as_u64()) else { + return Err(tl!("Placement Options can only change the document where it was opened.").to_owned()); + }; + if Some(active.reverts) != opening["reverts"].as_u64() { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } 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) }); + let params = json!({ "ids": opening["ids"], "preserve": f.text("preserve"), "align": align, "clip": f.bool("clip").unwrap_or(false) }); app.run(CMD, params).map(|_| ()) }) .ok_or("no window")?; @@ -125,4 +132,40 @@ mod tests { assert_eq!(placement["preserve"], json!("fit")); assert_eq!(steps, starting.1 + 1); } + + #[test] + fn held_placement_options_do_not_edit_a_link_restored_by_file_revert() { + let dir = vectorcraft_testkit::TempDir::new("placement-options-revert"); + 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())); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let link = app.run("file.place", json!({"path": path, "at": [100, 100], "link": true})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + let placement = |app: &mut VectorcraftApp| app.run(CMD, json!({"ids": [link]})).unwrap()["placement"].clone(); + let original = placement(&mut app); + app.run(CMD, json!({"ids": [link], "preserve": "fill"})).unwrap(); + open(&mut app, &json!({"ids": [link]})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let dialog = dialog_id(KEY); + let host = app.dialogs().unwrap(); + host.with(|h| { + h.set_json_field(&ctx, dialog, "preserve", json!("fit")).unwrap(); + assert!(!h.confirm_by_id(&ctx, dialog)); + }); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + crate::dialogs::host::pump(&mut app, &ctx); + assert_eq!(placement(&mut app), original); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(host.with(|h| h.held_state(dialog)), Some(HeldOk::Refused(_)))); + + host.with(|h| h.cancel_by_id(&ctx, dialog)); + open(&mut app, &json!({"ids": [link]})).unwrap(); + crate::tests::picks::answer_dialog(&mut app, dialog, &[("preserve", json!("fit"))], true); + assert_eq!(placement(&mut app)["preserve"], "fit"); + } } diff --git a/crates/ui-egui/src/dialogs/print_presets.rs b/crates/ui-egui/src/dialogs/print_presets.rs index fc5e1b1d0b..1fa2fd7e8b 100644 --- a/crates/ui-egui/src/dialogs/print_presets.rs +++ b/crates/ui-egui/src/dialogs/print_presets.rs @@ -48,7 +48,7 @@ fn stored(app: &VectorcraftApp, name: &str) -> Value { fn detail(app: &VectorcraftApp, name: &str) -> Vec { let builtin = name == DEFAULT_PRESET; let title = if builtin { tl!(DEFAULT_PRESET).to_string() } else { name.to_string() }; - let mut out = vec![Detail::Title(title), Detail::Note(crate::i18n::fmt(tl!("Differences from {preset}:"), &[("preset", DEFAULT_PRESET)]))]; + let mut out = vec![Detail::Title(title), Detail::Note(crate::i18n::fmt(tl!("Differences from {preset}:"), &[("preset", tl!(DEFAULT_PRESET))]))]; let settings = app.session.prefs.print_presets.iter().find(|p| p.name == name).map(|p| &p.settings); let mut changed = settings.map(|s| changes(s, &Default::default())).unwrap_or_default(); changed.sort_by_key(|c| section_of(c["option"].as_str().unwrap_or_default()).0); diff --git a/crates/ui-egui/src/dialogs/profile_mismatch.rs b/crates/ui-egui/src/dialogs/profile_mismatch.rs index 594da48ea4..da1dcb1a37 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch.rs @@ -62,9 +62,8 @@ pub(crate) struct PasteAsk { params: Value, /// The models whose profiles differ, as `clipboard.profileMismatch` lists them. mismatches: Vec, - /// The uid of the document the question was asked in: a paste that runs at once pastes nothing - /// once another document is active. - doc: Option, + /// The drawing and content generation the question was asked in. + drawing: Option<(u64, u64)>, /// The chain of a deferred paste (one that waits for its clipboard), which placing answers. deferred: Option, } @@ -271,8 +270,8 @@ fn open_paste(app: &mut VectorcraftApp, command: &str, params: &Value, mismatche crate::placing::cancel_swatch_paste(app); } let dialog = paste_dialog(&ctx, &mismatches); - let doc = app.session.active().map(|st| st.uid); - app.pending_paste = Some(PasteAsk { command: command.to_string(), params: params.clone(), mismatches, doc, deferred: None }); + let drawing = app.session.active().map(|st| (st.uid, st.reverts)); + app.pending_paste = Some(PasteAsk { command: command.to_string(), params: params.clone(), mismatches, drawing, deferred: None }); dialogs.with(|h| h.open(dialog)); Some(Ok(json!({ "dialog": PASTE_KIND }))) } @@ -389,12 +388,11 @@ fn pump_paste(app: &mut VectorcraftApp) { } } -/// OK: run the paste with the choice; any Swatch Conflict question comes next. When another -/// document has become the active one since a paste that runs at once asked, it pastes nothing. When -/// the profiles that paste or drop would bring have changed since it asked (the clipboard, the -/// dragged objects' document or the destination's profile changed), it asks again about the new ones. +/// OK: run the paste with the choice; any Swatch Conflict question comes next. An immediate paste +/// is canceled if its drawing is inactive or reverted. When the profiles it would bring have changed +/// since it asked (the clipboard, dragged objects or destination changed), it asks about the new ones. fn paste_confirm(app: &mut VectorcraftApp, ask: PasteAsk, choice: Value) -> Result { - if ask.deferred.is_none() && ask.doc != app.session.active().map(|st| st.uid) { + if ask.deferred.is_none() && ask.drawing != app.session.active().map(|st| (st.uid, st.reverts)) { return Ok(json!({})); } let params = with_choice(&ask.params, choice); diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs index fc415fbcda..517f34b302 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -320,6 +320,31 @@ fn paste_asked_before_another_document_is_active(app: &mut VectorcraftApp) { app.run("document.activate", json!({ "index": asked_in })).unwrap(); } +/// The destination still has a mismatch after reopening the saved contents. Its old approval is retired. +fn paste_asked_before_its_drawing_is_reverted(app: &mut VectorcraftApp) { + let dir = vectorcraft_testkit::TempDir::new("immediate-profile-mismatch-revert"); + let path = dir.join("destination.vectorcraft"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + app.run("shape.rectangle", json!({"x": 60, "y": 60, "width": 20, "height": 20})).unwrap(); + assert_eq!(app.run("edit.paste", json!({})).unwrap(), json!({ "dialog": PASTE_KIND })); + let before = app.session.active().unwrap(); + let (uid, reverts) = (before.uid, before.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let restored = app.session.active().unwrap(); + assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1)); + assert!(app.pending_paste.is_some(), "the old question is still waiting"); + let saved = restored.doc.clone(); + let undo = restored.history.undo.len(); + + answer_ok(app, paste_id_open()); + let after = app.session.active().unwrap(); + assert!(after.doc == saved, "the old profile approval must leave the restored drawing intact"); + assert_eq!(after.history.undo.len(), undo); + assert!(app.pending_paste.is_none()); +} + /// A drag of the art of the document assigned Display P3 into the active one asks as Paste does: /// Cancel drops nothing, and OK drops it as chosen. When the source document's profile changes while /// the question is open, OK drops nothing and asks again about the new profile. `count` counts the @@ -467,6 +492,7 @@ fn opening_and_pasting_ask_about_profiles() { // Cancel pastes nothing; with the box off nothing asks. paste_canceled(&mut app, count); paste_asked_before_another_document_is_active(&mut app); + paste_asked_before_its_drawing_is_reverted(&mut app); drop_asks_as_paste_does(&mut app, count); let before = count(&app); app.run("edit.colorSettings", json!({"askMismatchPaste": false})).unwrap(); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index a377869b5b..06da91e399 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -123,7 +123,6 @@ use std::sync::{Arc, Weak}; use craft::behavior::edit_history::{EditHistory, Step}; use craft::behavior::{ColumnKey, ColumnWidth, EditEvent, IconId, Mixed, Selection, SelectionChange, keyed}; use craft::color_ui::ui::{ChannelRow, ChannelUnit, ColorPanelMode, DiscRadius, patch_at}; -use craft::host::PickRequest; use craft::theme::variant::Tone; use craft::theme::{ModelValues, Rgba, Srgba}; use craft::ui::buttons::{IconButton, ToggleButton}; @@ -260,6 +259,7 @@ pub(crate) struct Open { /// The dialog on the window's host. pub id: DialogId, document: u64, + reverts: u64, /// The preview the pump runs and OK commits. pub preview: LivePreview, /// The selection snapshot identifies the interaction that ran the preview. @@ -270,14 +270,17 @@ impl Open { 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.uid, state.reverts) == (self.document, self.reverts) && state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection)) }) } fn problem(&self, app: &VectorcraftApp) -> Option<&'static str> { - if app.session.active().is_none_or(|state| state.uid != self.document) { - Some("Return to the document where Recolor Artwork opened.") + let Some(state) = app.session.active().filter(|state| state.uid == self.document) else { + return Some("Return to the document where Recolor Artwork opened."); + }; + if state.reverts != self.reverts { + Some("The document was reverted. Reopen this dialog to continue.") } else if app.session.in_interaction() && !self.owns_preview(app) { Some("Finish the active edit before applying Recolor Artwork.") } else { @@ -338,7 +341,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { // A Recolor Artwork still open is replaced: its preview goes before the group's colours are read. cancel_open(app); let st = app.session.active().ok_or("no document open")?; - let document = st.uid; + let (document, reverts) = (st.uid, st.reverts); let group_colors: Option> = match group { Some(g) => { let g = st.doc.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| format!("no colour group `{g}`"))?; @@ -377,7 +380,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let dialog = RecolorDialog::new(app, d); let options = HeldOptions { cancel: Some(Box::new(cancelled)), ..HeldOptions::default() }; let id = open_held_with(app, dialog, confirm, options).ok_or("no window to show Recolor Artwork in")?; - app.color_dialogs.recolor = Some(Open { id, document, preview: LivePreview::default(), preview_selection: None }); + app.color_dialogs.recolor = Some(Open { id, document, reverts, preview: LivePreview::default(), preview_selection: None }); Ok(Value::Null) } @@ -1632,11 +1635,9 @@ fn randomize(app: &mut VectorcraftApp, d: &mut Fields, sb: bool) { /// Other Library…: import a library (.ase, .acb, .gpl, .vcswatches or a document's swatches) and /// limit to it. fn pick_library(app: &mut VectorcraftApp, opening: Arc<()>) { - let request = builtin_open_filters().fold(PickRequest::open("library"), |request, (name, exts)| request.filter(name, exts)); // A loaded library belongs to the session. The Limit to Library choice belongs to the opening that asked. - crate::file_asks::ask(app, request, crate::file_asks::Owner::Free, move |app, picked| { - let Some(path) = picked.first_path() else { return Ok(Value::Null) }; - let r = app.run("swatch.library.load", json!({ "path": path }))?; + let _ = crate::panels::library_panel::pick_library_file(app, None, builtin_open_filters().collect(), move |app, source| { + let r = app.run("swatch.library.load", source)?; let library = r["library"].clone(); if let Some(dialogs) = app.dialogs() { dialogs.with(|host| { @@ -3208,6 +3209,21 @@ mod tests { (rc, opening, other) } + #[test] + fn other_library_accepts_browser_contents_and_selects_the_loaded_library() { + let (mut rc, _, _) = two_red_drawings(); + let picker = crate::tests::picks::scripted(&mut rc.app()); + rc.settled().click_label("Other Library…").frame(); + assert_eq!(picker.requests().len(), 1); + let bytes = b"GIMP Palette\nName: Recolor Browser Palette\n#\n255 0 0\tRecolor Red\n"; + picker.answer_contents(&[("Recolor Browser Palette.gpl", bytes)]); + crate::file_asks::poll(&mut rc.app()); + rc.frame(); + let selected = rc.fields().str("limitTo"); + assert!(!selected.is_empty(), "Other Library selects the imported library"); + assert!(swatchlib::limit_palette(&rc.app().session, &selected).is_some()); + } + #[test] fn recolor_preview_does_not_change_the_other_drawings_art() { let (mut rc, opening, other) = two_red_drawings(); @@ -3281,6 +3297,51 @@ mod tests { assert!(group_hex(&rc.app(), "Shared").is_none()); } + #[test] + fn recolor_after_file_revert_does_not_restart_the_discarded_preview() { + struct SavedFile(std::path::PathBuf); + impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + let mut app = app(120); + let shape = square(&mut app, 10.0, "#ff0000"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-recolor-revert-{}.vectorcraft", std::process::id()))); + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + assert!(path.0.is_file()); + square(&mut app, 60.0, "#0000ff"); + app.run("select.set", json!({"ids": [shape]})).unwrap(); + let mut rc = opened(app, json!({})); + rc.set("method", json!(Method::Exact.id())).unwrap(); + rc.frame(); + rc.set("rows", json!([{"from": ["rgb 255 0 0"], "to": "rgb 0 255 0"}])).unwrap(); + rc.frame(); + assert_eq!(fill_hex(&rc, shape), "#00ff00", "the original preview is active"); + + { + let mut app = rc.app(); + let state = app.session.active().unwrap(); + let (uid, reverts) = (state.uid, state.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let state = app.session.active().unwrap(); + assert_eq!((state.uid, state.reverts), (uid, reverts + 1)); + assert!(state.doc.node(vectorcraft_doc::NodeId(shape)).is_some()); + app.run("select.set", json!({"ids": [shape]})).unwrap(); + } + assert_eq!(fill_hex(&rc, shape), "#ff0000"); + let history = undo_len(&rc.app()); + rc.frame(); + assert_eq!(fill_hex(&rc, shape), "#ff0000", "an open preview must leave the saved red fill alone"); + assert!(!rc.app().session.in_interaction()); + assert!(rc.confirm().is_err() && rc.is_open(), "the old draft cannot be applied"); + assert_eq!(fill_hex(&rc, shape), "#ff0000"); + assert_eq!(undo_len(&rc.app()), history); + } + #[test] fn recolor_dialog_keeps_the_default_model_without_an_extra_dropdown() { let rc = opened(app(100), json!({"colors": ["#ff8000"]})); diff --git a/crates/ui-egui/src/dialogs/recolor_preset.rs b/crates/ui-egui/src/dialogs/recolor_preset.rs index 61dfc60d6f..37e2d113d5 100644 --- a/crates/ui-egui/src/dialogs/recolor_preset.rs +++ b/crates/ui-egui/src/dialogs/recolor_preset.rs @@ -6,7 +6,7 @@ //! Fields: `limitTo` (a library id, `"document"` for the document's swatches, `""` for None), as //! Recolor Artwork's. -use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamKind, ParamResult}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind, ParamResult}; use craft::ui::runtime::env::Label; use serde_json::{Value, json}; @@ -16,6 +16,7 @@ use crate::VectorcraftApp; /// The dialog kind of Recolor with Preset. pub const KIND: &str = "recolorPreset"; +const OPENING: &str = "__opening"; /// Open the dialog for the preset of `p` (`colors`: a count; `library`: the library it starts on, /// "" the first library) on the selected art. @@ -24,7 +25,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if st.selection.is_empty() { return Err("select artwork to recolor".into()); } - let document = st.uid; + let (document, reverts) = (st.uid, st.reverts); if p.get("group").is_some_and(|g| !g.is_null()) { return Err("`group` does not apply to a preset".into()); } @@ -36,15 +37,20 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let options = library_choices(app).into_iter().map(|(key, name)| (key, Label::from(name))).collect(); let mut fields = DialogFields::new(); fields.set("limitTo", limit.clone()); + fields.set(OPENING, FieldValue::Json(json!({"uid": document, "reverts": reverts, "colors": colors}))); let rows = vec![Param::new("limitTo", field_label(tl!("Limit to Library:")), ParamKind::choice(options, Some(limit)))]; let dialog = hosted(&ctx, KIND, tl!("Recolor with Preset"), fields, rows, false); // Recolor Artwork takes the dialog's place; when it cannot open, this dialog stays. - let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { - if !app.session.active().is_some_and(|active| active.uid == document) { + let ok = |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { + let Some(FieldValue::Json(opening)) = answer.fields.get(OPENING) else { return Err("the Recolor with Preset target is missing".into()) }; + let Some(active) = app.session.active().filter(|active| Some(active.uid) == opening["uid"].as_u64()) else { return Err(tl!("Open the original drawing to continue with Recolor with Preset.").to_owned()); + }; + if Some(active.reverts) != opening["reverts"].as_u64() { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); } let mut p = serde_json::Map::new(); - if let Some(n) = colors { + if let Some(n) = opening["colors"].as_u64() { p.insert("colors".into(), json!(n)); } if let Some(limit) = answer.fields.text("limitTo").filter(|l| !l.is_empty()) { @@ -101,4 +107,34 @@ mod tests { let limit = super::super::recolor::limit_to(&host, dialog_id(super::super::recolor::KIND)); assert_eq!(limit.as_deref(), Some("document")); } + + #[test] + fn an_old_recolor_preset_does_not_open_on_restored_artwork() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let shape = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let dir = vectorcraft_testkit::TempDir::new("recolor-preset-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("paint.setFill", json!({"ids": [shape], "color": "#ff0000"})).unwrap(); + app.run("select.set", json!({"ids": [shape]})).unwrap(); + app.run("ui.recolorDialog", json!({"preset": true, "colors": 1})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + let id = dialog_id(KIND); + assert!(!host.with(|h| h.confirm_by_id(&ctx, id))); + assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Waiting)); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [shape]})).unwrap(); + super::super::host::pump(&mut app, &ctx); + assert!(app.color_dialogs.recolor.is_none()); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + host.with(|h| h.cancel_by_id(&ctx, id)); + app.run("ui.recolorDialog", json!({"preset": true, "colors": 1})).unwrap(); + assert!(super::super::tests::confirm(&mut app)); + assert!(app.color_dialogs.recolor.is_some()); + } } diff --git a/crates/ui-egui/src/dialogs/saturate.rs b/crates/ui-egui/src/dialogs/saturate.rs index 704776fc48..1a3a6c8310 100644 --- a/crates/ui-egui/src/dialogs/saturate.rs +++ b/crates/ui-egui/src/dialogs/saturate.rs @@ -46,9 +46,9 @@ fn params(fields: &DialogFields) -> Value { } fn rows() -> Vec { - vec![Param::custom("intensity", "Intensity", |ui, fields, _cx| { + vec![Param::custom("intensity", tl!("Intensity"), |ui, fields, _cx| { // The rail runs from grey to a fully saturated colour. - percent_row(ui, fields, "intensity", "Intensity", |x| Srgba::from(c32(&Color::from_hsb(12.0, x, 0.85)))); + percent_row(ui, fields, "intensity", tl!("Intensity"), |x| Srgba::from(c32(&Color::from_hsb(12.0, x, 0.85)))); ui.response() })] } diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index e7afa2c556..bd1c548175 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -42,7 +42,7 @@ const WRONG_DOCUMENT: &str = "Save for Web belongs to the document that opened t /// 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, + document: Option<(u64, u64)>, opening: Arc<()>, /// The rendering of the art before optimisation, by [`render_key`]. render: Option<(String, Result, String>)>, @@ -186,7 +186,8 @@ 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 { - let document = app.session.active().ok_or("no document")?.uid; + let active = app.session.active().ok_or("no document")?; + let document = (active.uid, active.reverts); 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. @@ -461,8 +462,13 @@ 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)) +fn document_problem(app: &VectorcraftApp) -> Option<&'static str> { + match (app.web_export.document, app.session.active()) { + (Some((uid, reverts)), Some(active)) if uid == active.uid => { + (reverts != active.reverts).then(|| tl!("The document was reverted. Reopen this dialog to continue.")) + } + _ => Some(tl!(WRONG_DOCUMENT)), + } } /// Answers the open dialog once per frame: its result when it closed, else its requests. @@ -479,7 +485,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { _ => {} } let Some(asked) = on_dialog(&host, Asked::take) else { return }; - if !on_original_document(app) { + if let Some(reason) = document_problem(app) { let restore = asked.tables.iter().any(|event| matches!(event.edit, ColorTableEdit::Restore)); if restore { color_table::restore(&mut app.web_export.table); @@ -494,7 +500,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { update_presets(app, &host, asked.presets, restore); if requested { on_dialog(&host, HostedSaveForWeb::cancel_requests); - app.status(tl!(WRONG_DOCUMENT).to_owned()); + app.status(reason); } return; } @@ -595,8 +601,8 @@ 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()); + if let Some(reason) = document_problem(app) { + app.status(reason); return true; } let rgb = |c: Srgba| { @@ -736,11 +742,11 @@ fn ask_path(app: &mut VectorcraftApp, host: &craft::ui::shell::WindowDialogs, id if !Arc::ptr_eq(&opening, &app.web_export.opening) { return Ok(Value::Null); } - if !on_original_document(app) { + if let Some(reason) = document_problem(app) { if let Some(host) = app.dialogs() { on_dialog(&host, HostedSaveForWeb::cancel_requests); } - app.status(tl!(WRONG_DOCUMENT).to_owned()); + app.status(reason); return Ok(Value::Null); } match picked.first_path() { @@ -765,12 +771,12 @@ 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 problem = document_problem(app).filter(|_| result.path.is_some()); 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()); + if let Some(reason) = problem { + return app.status(reason); } let params = settings_of(&result.options, &table, &kept, None); if let Err(e) = app.run("webExport.settings", params.clone()) { 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 b030f110db..6c79fb69da 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/tests.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests.rs @@ -355,6 +355,42 @@ fn save_for_web_does_not_write_another_drawing_when_the_picker_returns() { assert!(dir.join("Untitled-1.png").exists()); } +#[test] +fn save_for_web_requires_a_fresh_approval_after_file_revert() { + let dir = vectorcraft_testkit::TempDir::new("sfw-revert-output"); + let source = vectorcraft_testkit::TempDir::new("sfw-revert-drawing"); + let (mut app, _) = app(dir.as_ref(), false); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + let path = source.join("Source.vectorcraft"); + app.run("file.saveAs", json!({"path": path})).unwrap(); + app.run("shape.rectangle", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + let original = app.session.active().unwrap(); + let (uid, reverts) = (original.uid, original.reverts); + 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("file.revert", json!({"confirmed": true})).unwrap(); + let current = app.session.active().unwrap(); + assert_eq!((current.uid, current.reverts), (uid, reverts + 1)); + answer_saves(&mut app); + settle(&mut app); + assert_eq!(std::fs::read_dir(dir.as_ref()).unwrap().count(), 0); + assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue."); + + close(&mut app); + settle(&mut app); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "format", json!("png24")); + save(&mut app); + let outputs: Vec<_> = std::fs::read_dir(dir.as_ref()).unwrap().map(|entry| entry.unwrap().path()).collect(); + assert_eq!(outputs.len(), 1); + assert!(std::fs::read(&outputs[0]).unwrap().starts_with(b"\x89PNG")); +} + /// 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 9f06db67b8..80fed5d49f 100644 --- a/crates/ui-egui/src/dialogs/save_library.rs +++ b/crates/ui-egui/src/dialogs/save_library.rs @@ -36,7 +36,8 @@ 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 state = app.session.active().ok_or("no document open")?; + let document = (state.uid, state.reverts); 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; @@ -68,9 +69,12 @@ pub(super) fn open(app: &mut VectorcraftApp, library: Library, names: Vec(owner)); - if app.session.active().is_none_or(|st| Some(st.uid) != document) { + let document = ctx.data(|data| data.get_temp::<(u64, u64)>(owner)); + let Some(state) = app.session.active().filter(|st| document.is_some_and(|(uid, _)| st.uid == uid)) else { return Err(tl!("Return to the original drawing to save its library").into()); + }; + if document.is_some_and(|(_, reverts)| state.reverts != reverts) { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); } save(app, cmd, ext, result) }; @@ -155,4 +159,58 @@ mod tests { assert_eq!(output.len(), 1); assert!(output[0].0.contains("Other Marks")); } + + #[test] + fn an_old_save_library_approval_cannot_export_definitions_restored_by_revert() { + let (mut app, written) = tests_export::app(1); + app.services.read = Some(Box::new(|path: &str| std::fs::read(path).map_err(|error| error.to_string()))); + let output = written.clone(); + app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| { + if path.ends_with(".vectorcraft") { + std::fs::write(path, bytes).map_err(|error| error.to_string()) + } else { + output.borrow_mut().push((path.to_string(), bytes.to_vec())); + Ok(()) + } + })); + let id = app.session.active().unwrap().selection.objects[0]; + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Mark", "id": id.0})).unwrap(); + let saved_fill = app.session.active().unwrap().doc.graphic_style("Mark").unwrap().appearance.fill_paint(); + let temp = vectorcraft_testkit::TempDir::new("save-library-revert"); + let file = temp.join("library-source.vectorcraft"); + app.run("file.saveAs", json!({"path": file})).unwrap(); + assert!(file.is_file()); + let state = app.session.active().unwrap(); + let (uid, reverts) = (state.uid, state.reverts); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + app.run("graphicStyle.redefine", json!({"name": "Mark", "id": id.0})).unwrap(); + assert_ne!(app.session.active().unwrap().doc.graphic_style("Mark").unwrap().appearance.fill_paint(), saved_fill); + super::super::save_style_library::open(&mut app, vec!["Mark".into()]).unwrap(); + tests_export::set(&mut app, "saveTo", json!("file")); + tests_export::set(&mut app, "selectedOnly", json!(true)); + tests_export::set(&mut app, "name", json!("Draft Marks")); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let state = app.session.active().unwrap(); + assert_eq!((state.uid, state.reverts), (uid, reverts + 1)); + assert_eq!(state.doc.graphic_style("Mark").unwrap().appearance.fill_paint(), saved_fill); + let undo = state.history.undo.len(); + assert!(tests_export::try_confirm(&mut app).is_err(), "old approval must not export the restored library"); + assert!(written.borrow().is_empty(), "no output is written for the retired draft"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(tests_export::fields(&app)["name"], "Draft Marks", "refusal preserves the user's draft"); + + tests_export::cancel(&mut app); + super::super::save_style_library::open(&mut app, vec!["Mark".into()]).unwrap(); + tests_export::set(&mut app, "saveTo", json!("file")); + tests_export::set(&mut app, "selectedOnly", json!(true)); + tests_export::set(&mut app, "name", json!("Restored Marks")); + tests_export::try_confirm(&mut app).unwrap(); + let output = written.borrow(); + assert_eq!(output.len(), 1); + let text = std::str::from_utf8(&output[0].1).unwrap(); + let library = vectorcraft_doc::style_libs::read(text, "Restored Marks").unwrap(); + assert_eq!(library.style("Mark").unwrap().appearance.fill_paint(), saved_fill, "fresh approval exports the restored definition"); + } } diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index b03cf32bcd..506ef94fce 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -38,7 +38,7 @@ const WRONG_DOCUMENT: &str = "Return to the original drawing to save the PDF or /// What the Save PDF dialog was opened for; the preset editor has none. pub(crate) struct SavePdfJob { /// The drawing this job reads and writes. - document: u64, + pub(crate) document: u64, /// The file the PDF goes to; none: the write asks. pub(crate) path: Option, /// The save command (`file.saveAs`, `file.saveCopy`) this PDF finishes; none: a plain PDF copy. diff --git a/crates/ui-egui/src/dialogs/smart_punctuation.rs b/crates/ui-egui/src/dialogs/smart_punctuation.rs index 9e68c0507b..c3c1549d2a 100644 --- a/crates/ui-egui/src/dialogs/smart_punctuation.rs +++ b/crates/ui-egui/src/dialogs/smart_punctuation.rs @@ -6,6 +6,8 @@ //! Fields: the switches `fiLigatures`, `flLigatures`, `quotes`, `spaces`, `dashes`, `ellipsis` and //! `fractions`, `scope` (`selection` or `document`) and `report`. +use std::collections::HashSet; + use craft::ui::contract::{Bind, SaveKey}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::Label; @@ -51,6 +53,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let source = app.session.active().ok_or("no document")?; let document = source.uid; let selected = !source.selection.is_empty(); + let selection = source.selection.objects.iter().copied().collect::>(); let mut params: Vec = options() .into_iter() .map(|(key, _, label)| Param::new(key, label, ParamKind::bool(matches!(key, "quotes" | "dashes" | "ellipsis")))) @@ -72,10 +75,18 @@ pub fn open(app: &mut VectorcraftApp) -> Result { 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) { + let Some(active) = app.session.active().filter(|st| Some(st.uid) == document) else { return Err(tl!("Return to the original drawing to replace its punctuation").into()); + }; + let params = params_of(result); + if params["scope"] == "selection" + && (active.selection.is_empty() + || active.selection.objects.len() != selection.len() + || active.selection.objects.iter().any(|id| !selection.contains(id))) + { + return Err(tl!("The selected text changed. Restore the selection to continue.").into()); } - let r = app.run(COMMAND, params_of(result))?; + let r = app.run(COMMAND, params)?; result.remember(&ctx); if result.fields.bool("report") == Some(true) { let lines: Vec = options() @@ -208,4 +219,47 @@ mod tests { app.run("document.activate", json!({"index": 0})).unwrap(); assert_eq!(plain(&app, source), "a--b"); } + + fn selected_text_pair() -> (VectorcraftApp, u64, u64) { + let (mut app, selected) = app_with_text("a--b"); + let other = app.run("text.create", json!({"x": 10, "y": 70, "text": "c--d", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [selected]})).unwrap(); + open(&mut app).unwrap(); + assert_eq!(entry(&app, COMMAND).unwrap().fields.unwrap()["scope"], "selection"); + (app, selected, other) + } + + #[test] + fn selected_text_only_does_not_expand_to_the_document_after_clearing_selection() { + let (mut app, selected, other) = selected_text_pair(); + let undo = app.session.active().unwrap().history.undo.len(); + app.run("select.none", json!({})).unwrap(); + assert_eq!(entry(&app, COMMAND).unwrap().fields.unwrap()["scope"], "selection"); + + let answer = super::super::tests_export::try_confirm(&mut app); + assert_eq!([plain(&app, selected), plain(&app, other)], ["a--b", "c--d"], "Selected Text Only must not expand to the document"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(answer, Err("The selected text changed. Restore the selection to continue.".into())); + + app.run("select.set", json!({"ids": [selected]})).unwrap(); + ok(&mut app); + assert_eq!([plain(&app, selected), plain(&app, other)], ["a–b", "c--d"], "retry changes only the original selection"); + } + + #[test] + fn selected_text_only_refuses_later_art_but_entire_document_still_works() { + let (mut app, selected, other) = selected_text_pair(); + app.run("select.set", json!({"ids": [other]})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + + let answer = super::super::tests_export::try_confirm(&mut app); + assert_eq!([plain(&app, selected), plain(&app, other)], ["a--b", "c--d"], "Selected Text Only must not change later artwork"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(answer, Err("The selected text changed. Restore the selection to continue.".into())); + + set(&app, "scope", json!("document")); + ok(&mut app); + assert_eq!([plain(&app, selected), plain(&app, other)], ["a–b", "c–d"], "an explicit Entire Document still works"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } } diff --git a/crates/ui-egui/src/dialogs/svg_filter.rs b/crates/ui-egui/src/dialogs/svg_filter.rs index aaf3021f6d..22388092d3 100644 --- a/crates/ui-egui/src/dialogs/svg_filter.rs +++ b/crates/ui-egui/src/dialogs/svg_filter.rs @@ -474,7 +474,10 @@ fn ask_import(app: &mut VectorcraftApp, source: Option>) -> Value { // The browser answers with the file's contents, not a path. Picked::Contents(files) => { let (_, bytes) = files.first().ok_or("cancelled")?; - json!({ "svg": String::from_utf8_lossy(bytes) }) + if bytes.len() > vectorcraft_engine::cmd::MAX_SVG_FILTER_IMPORT_BYTES { + return Err("The SVG file is larger than 16 MB".into()); + } + json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) }) } other => json!({ "path": other.first_path().ok_or("cancelled")?.to_string_lossy() }), }; @@ -499,6 +502,25 @@ mod tests { const SHIFT: &str = r#""#; + #[test] + fn browser_filter_import_keeps_the_picked_file_encoding() { + let svg = r#""#; + let utf16: Vec = [0xfe, 0xff].into_iter().chain(svg.encode_utf16().flat_map(u16::to_be_bytes)).collect(); + let latin1: Vec = format!("{svg}").chars().map(|c| c as u8).collect(); + for bytes in [utf16, latin1] { + let mut app = app(); + let picker = scripted(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + open(&mut app, &json!({})).unwrap(); + import_file(&mut app).unwrap(); + picker.answer_contents(&[("filter.svg", &bytes)]); + poll(&mut app, &ctx); + assert_eq!(app.session.active().unwrap().doc.svg_filters[0].name, "café"); + assert_eq!(fields(&app)[SELECTED], "café"); + assert_eq!(app.session.active().unwrap().history.undo.len(), 1); + } + } + fn app() -> VectorcraftApp { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); diff --git a/crates/ui-egui/src/dialogs/swatch_conflict.rs b/crates/ui-egui/src/dialogs/swatch_conflict.rs index b0d7b34fa0..abc4e8d644 100644 --- a/crates/ui-egui/src/dialogs/swatch_conflict.rs +++ b/crates/ui-egui/src/dialogs/swatch_conflict.rs @@ -56,7 +56,7 @@ const CHOICES: [(Choice, &str, &str); 2] = [ ]; /// The question about the swatches a paste brings that the document names differently. Its answer is the value -/// [`take`] hands the paste: `command`, `params` (with `swatchConflict`), `deferred`, `asked` and `doc`. +/// [`take`] hands the paste: `command`, `params` (with `swatchConflict`), `deferred`, `asked` and `drawing`. struct SwatchConflictDialog { id: DialogId, /// The conflicts as `clipboard.conflicts` lists them: `[{name, document, clipboard, spot}]`. @@ -70,15 +70,15 @@ struct SwatchConflictDialog { /// The paste command and its parameters. command: String, params: Value, - /// The uid of the document the question is about. - doc: Option, + /// The drawing and content generation the question is about. + drawing: Option<(u64, u64)>, /// The deferred paste waiting on the answer ([`defer`]). deferred: Option, open: bool, } impl SwatchConflictDialog { - fn new(conflicts: Vec, command: &str, params: &Value, doc: Option) -> Self { + fn new(conflicts: Vec, command: &str, params: &Value, drawing: Option<(u64, u64)>) -> Self { SwatchConflictDialog { id: dialog_id(KIND), conflicts, @@ -88,7 +88,7 @@ impl SwatchConflictDialog { choices: Map::new(), command: command.to_owned(), params: Some(params).filter(|p| p.is_object()).cloned().unwrap_or_else(|| json!({})), - doc, + drawing, deferred: None, open: true, } @@ -115,7 +115,7 @@ impl SwatchConflictDialog { } let mut params = self.params.clone(); params["swatchConflict"] = Value::Object(self.choices.clone()); - Some(json!({"command": self.command, "params": params, "deferred": self.deferred, "asked": self.conflicts, "doc": self.doc})) + Some(json!({"command": self.command, "params": params, "deferred": self.deferred, "asked": self.conflicts, "drawing": self.drawing})) } } @@ -221,7 +221,8 @@ pub fn ask(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option Option { app.dialogs()?.with(|h| h.get_by_id::(id).map(|_| id)) } -/// What the question `id` answered this pass. A question about another document than the active one, with no -/// deferred paste to go back to, answers Cancel. +/// What the question `id` answered this pass. An immediate question whose drawing is inactive or +/// reverted answers Cancel. Placing checks deferred answers against their original drawing. pub(crate) fn take(app: &VectorcraftApp, id: DialogId) -> Taken { let Some(host) = app.dialogs() else { return Taken::Open }; match host.with(|h| h.take_by_id::(id)) { Some(Answer::Ok(value)) => { - let elsewhere = value["deferred"].is_null() && value["doc"].as_u64() != app.session.active().map(|doc| doc.uid); - if elsewhere { Taken::Cancelled } else { Taken::Answered(value) } + let drawing = app.session.active().map(|doc| (doc.uid, doc.reverts)); + let retired = value["deferred"].is_null() && value["drawing"] != json!(drawing); + if retired { Taken::Cancelled } else { Taken::Answered(value) } } Some(_) => Taken::Cancelled, None => Taken::Open, diff --git a/crates/ui-egui/src/dialogs/swatch_options.rs b/crates/ui-egui/src/dialogs/swatch_options.rs index 107da9afa1..b0e91b5ba1 100644 --- a/crates/ui-egui/src/dialogs/swatch_options.rs +++ b/crates/ui-egui/src/dialogs/swatch_options.rs @@ -48,7 +48,7 @@ pub(crate) struct Open { /// The held dialog. pub(crate) id: DialogId, opening: Arc<()>, - document: u64, + document: (u64, u64), preview_reset: u64, /// The name of the swatch being edited. swatch: String, @@ -291,7 +291,8 @@ 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 active = app.session.active().ok_or("no drawing")?; + let document = (active.uid, active.reverts); let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?; let dialog = hosted(&ctx, KIND, tl!("Swatch Options"), fields, rows, true); if owns_preview(app) { @@ -301,8 +302,11 @@ fn launch(app: &mut VectorcraftApp, swatch: &str, fields: DialogFields, rows: Ve 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) { + let Some(active) = app.session.active().filter(|st| st.uid == open.document.0) else { return Err(tl!("Return to the original drawing to edit this swatch").into()); + }; + if active.reverts != open.document.1 { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); } let edited = open.swatch.clone(); // The edit replaces the preview, so the preview is dropped first. @@ -345,15 +349,17 @@ 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)) + && app.session.active().is_some_and(|st| { + (st.uid, st.reverts) == 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(open) = app.ui.swatch_options.as_ref().filter(|open| app.session.active().is_some_and(|st| st.uid == open.document)) else { return }; + let Some(open) = app.ui.swatch_options.as_ref().filter(|open| app.session.active().is_some_and(|st| (st.uid, st.reverts) == 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); @@ -674,4 +680,36 @@ mod tests { app.run("edit.undo", json!({})).unwrap(); assert_eq!(swatch(&app, "Sky").0.map(|c| c.to_hex()), Some("#0000fe".into()), "one undo step"); } + + #[test] + fn swatch_options_cannot_preview_or_rename_a_restored_swatch() { + let (ctx, mut app) = setup(); + app.run("swatch.new", json!({"name": "Editable", "color": "#123456"})).unwrap(); + let dir = vectorcraft_testkit::TempDir::new("swatch-options-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + app.run("swatch.edit", json!({"name": "Editable", "color": "#654321"})).unwrap(); + open(&mut app, "Editable").unwrap(); + let name = "Renamed"; + set(&app, &ctx, &[("name", json!(name)), ("preview", json!(true))]); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.active().unwrap().doc.swatch(name).is_some()); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(app.session.active().unwrap().doc.swatch(name).is_none()); + let color = swatch(&app, "Editable").0.unwrap(); + assert_eq!(color.to_hex(), "#123456"); + let id = dialog_id(KIND); + crate::tests::picks::answer_dialog(&mut app, id, &[], true); + assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_)))); + assert!(app.session.active().unwrap().doc.swatch(name).is_none()); + + app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, id)); + crate::dialogs::host::pump(&mut app, &ctx); + open(&mut app, "Editable").unwrap(); + crate::tests::picks::answer_dialog(&mut app, id, &[("name", json!(name))], true); + assert!(app.session.active().unwrap().doc.swatch(name).is_some()); + } } diff --git a/crates/ui-egui/src/dialogs/symbol_delete.rs b/crates/ui-egui/src/dialogs/symbol_delete.rs index dfee6d6427..1a4e06b1f8 100644 --- a/crates/ui-egui/src/dialogs/symbol_delete.rs +++ b/crates/ui-egui/src/dialogs/symbol_delete.rs @@ -2,10 +2,10 @@ //! selected symbol?" with Yes and No ([`KIND`]); a symbol with placed instances gets Expand //! Instances, Delete Instances and Cancel ([`USED`]). //! -//! The question carries the [`vectorcraft_engine::DocState::uid`] of the document it was asked in and -//! the symbol names. Yes or either Instances button deletes the symbol only while that document is -//! the active one and still has the symbol; an unused symbol that has gained instances since asks -//! the in-use question instead. +//! The question carries the opening document, its revert generation, and the symbol names. Yes or +//! either Instances button deletes the symbol only while that document is active, has not been +//! reverted, and still has the symbol. An unused symbol that has gained instances asks the in-use +//! question instead. use craft::ui::dialog::{PromptChoice, StandardPrompt}; use serde_json::{Value, json}; @@ -28,6 +28,7 @@ enum Target { /// whether it is the in-use question. struct Ask { doc: u64, + reverts: u64, target: Target, used: bool, } @@ -42,7 +43,7 @@ crate::dialogs::confirm::wrapped_dialog!(SymbolQuestion, StandardPrompt, KIND); /// what becomes of them; an unused one is deleted at once with `now` (Alt-click on the panel's /// button) and asked about otherwise. pub(crate) fn ask(app: &mut VectorcraftApp, name: &str, now: bool) { - let Some(uid) = app.session.active().map(|st| st.uid) else { return }; + let Some((uid, reverts)) = app.session.active().map(|st| (st.uid, st.reverts)) else { return }; match instances(app, uid, name) { None => {} Some(0) if now => { @@ -50,7 +51,7 @@ pub(crate) fn ask(app: &mut VectorcraftApp, name: &str, now: bool) { app.status(e); } } - Some(n) => open(app, Ask { doc: uid, target: Target::One(name.to_string()), used: n > 0 }), + Some(n) => open(app, Ask { doc: uid, reverts, target: Target::One(name.to_string()), used: n > 0 }), } } @@ -58,12 +59,12 @@ pub(crate) fn ask(app: &mut VectorcraftApp, name: &str, now: bool) { /// ("Delete the selected symbols?", or the singular for one), or at once with `now`. Only those still /// unused then (`symbol.unused`: brush art, patterns and nested instances count) go, in one undo step. pub(crate) fn ask_many(app: &mut VectorcraftApp, names: &[String], now: bool) { - let Some(uid) = app.session.active().map(|st| st.uid) else { return }; + let Some((uid, reverts)) = app.session.active().map(|st| (st.uid, st.reverts)) else { return }; if now { // An error already went to the status bar. let _ = delete_unused(app, uid, names); } else { - open(app, Ask { doc: uid, target: Target::Many(names.to_vec()), used: false }); + open(app, Ask { doc: uid, reverts, target: Target::Many(names.to_vec()), used: false }); } } @@ -109,12 +110,20 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { // The host lock is released before any command runs. let Some(mut answer) = dialogs.with(|host| host.take::()).and_then(|result| result.ok()) else { return }; let Some(ask) = answer.take_tag::() else { return }; - let r = match (ask.used, answer.choice) { - (false, PromptChoice::Proceed) => confirm_unused(app, ask), - (true, PromptChoice::Proceed) => confirm_used(app, ask, true), - (true, PromptChoice::Alternate) => confirm_used(app, ask, false), + let expand_instances = match (ask.used, answer.choice) { + (false, PromptChoice::Proceed) => None, + (true, PromptChoice::Proceed) => Some(true), + (true, PromptChoice::Alternate) => Some(false), _ => return, }; + if app.session.active().is_some_and(|st| st.uid == ask.doc && st.reverts != ask.reverts) { + app.status(tl!("The document was reverted. Reopen this dialog to continue.")); + return; + } + let r = match expand_instances { + Some(expand) => confirm_used(app, ask, expand), + None => confirm_unused(app, ask), + }; if let Err(e) = r { app.status(e); } @@ -132,14 +141,14 @@ fn instances(app: &mut VectorcraftApp, uid: u64, name: &str) -> Option { /// Yes: deletes the symbol, or asks the in-use question when it has gained instances. fn confirm_unused(app: &mut VectorcraftApp, ask: Ask) -> Result { - let Ask { doc, target, .. } = ask; + let Ask { doc, reverts, target, .. } = ask; match target { Target::Many(names) => delete_unused(app, doc, &names), Target::One(name) => match instances(app, doc, &name) { None => Ok(Value::Null), Some(0) => app.run("symbol.delete", json!({ "name": name })), Some(_) => { - open(app, Ask { doc, target: Target::One(name), used: true }); + open(app, Ask { doc, reverts, target: Target::One(name), used: true }); Ok(Value::Null) } }, diff --git a/crates/ui-egui/src/dialogs/symbol_options.rs b/crates/ui-egui/src/dialogs/symbol_options.rs index 470f78e55e..af60827b95 100644 --- a/crates/ui-egui/src/dialogs/symbol_options.rs +++ b/crates/ui-egui/src/dialogs/symbol_options.rs @@ -12,6 +12,8 @@ //! Help: //! . +use std::collections::HashSet; + use craft::ui::contract::{Bind, Outcome as _, Show as _}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::pickers::{Anchor9, ReferencePoint, ReferencePointLook}; @@ -100,13 +102,25 @@ fn rows(name: &str) -> Vec { /// edited), applies the fields to it; `keep_art` leaves the selection as ordinary art for a new one; /// `opened` are the guides the dialog opened with. fn open_dialog(app: &mut VectorcraftApp, fields: DialogFields, edit: Option, keep_art: bool, opened: [f64; 4]) -> Result { - let document = app.session.active().ok_or("no document open")?.uid; + let st = app.session.active().ok_or("no document open")?; + let (document, reverts) = (st.uid, st.reverts); + let selection = edit.is_none().then(|| st.selection.objects.iter().copied().collect::>()); let ctx = app.ui_ctx.clone().ok_or("no window")?; let name = fields.text("name").unwrap_or_default().to_string(); - let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| ParamDialog::new(KIND, tl!("Symbol Options"), rows(&name))); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { + ParamDialog::new(KIND, tl!("Symbol Options"), rows(&name)).values(Bind::bound(fields)) + }); let ok = move |app: &mut VectorcraftApp, result: &ParamResult| -> Result<(), String> { - if !app.session.active().is_some_and(|active| active.uid == document) { - return Err(tl!("This symbol belongs to the document that opened the dialog.").to_owned()); + let Some(active) = app.session.active().filter(|st| st.uid == document) else { + return Err(tl!("This symbol belongs to the document that opened the dialog.").into()); + }; + if active.reverts != reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + if let Some(selection) = &selection + && (active.selection.objects.len() != selection.len() || active.selection.objects.iter().any(|id| !selection.contains(id))) + { + return Err(tl!("The selected artwork changed. Restore the selection to continue.").into()); } let f = &result.fields; let name = f.text("name").unwrap_or_default().trim().to_string(); @@ -195,10 +209,83 @@ fn merge(into: &mut Value, extra: Value) { #[cfg(test)] mod document_tests { use craft::ui::dialog::dialog_id; + use vectorcraft_doc::NodeId; use vectorcraft_engine::Session; - use super::super::tests_warp::{accept, set, windowed}; + use super::super::tests_warp::{accept, dismiss, set, windowed}; use super::*; + use crate::tests::picks::answer_dialog; + + #[test] + fn keyboard_and_pointer_edits_reach_new_and_existing_symbol_options() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + + fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + super::super::host::pump(app, ui.ctx()); + } + + for editing in [false, true] { + let mut app = windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 40})).unwrap(); + if editing { + app.run("symbol.new", json!({"name": "Badge", "type": "static", "alignToPixelGrid": true})).unwrap(); + } + let mut panel = Panel::new(app, draw); + panel.room(egui::vec2(800.0, 800.0)); + if editing { + open_edit(&mut panel.app(), Some("Badge")).unwrap(); + } else { + open(&mut panel.app(), false).unwrap(); + } + panel.frame(); + let undo = panel.app().session.active().unwrap().history.undo.len(); + assert_eq!( + panel.toggled("Align to Pixel Grid"), + Some(craft::behavior::Mixed::Same(editing)), + "the options open with the symbol's current pixel-alignment setting" + ); + panel.click_role("Name", Role::TEXT_INPUT); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("Keyboard badge"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + assert_eq!(super::super::tests_warp::json_fields(&panel.app(), dialog_id(KIND))["name"], "Keyboard badge"); + assert_eq!(super::super::tests_warp::json_fields(&panel.app(), dialog_id(KIND))["type"], if editing { "static" } else { "dynamic" }); + panel.click_role(if editing { "Dynamic Symbol" } else { "Static Symbol" }, Role::RADIO_BUTTON); + assert_eq!(super::super::tests_warp::json_fields(&panel.app(), dialog_id(KIND))["type"], if editing { "dynamic" } else { "static" }); + panel.click_role("Align to Pixel Grid", Role::CHECK_BOX); + panel.click_role("Enable Guides for 9-Slice Scaling", Role::CHECK_BOX); + for (label, key, input, value) in [ + ("Left", "sliceLeft", "10", 10.0), + ("Top", "sliceTop", "20", 20.0), + ("Right", "sliceRight", "30", 30.0), + ("Bottom", "sliceBottom", "40", 40.0), + ] { + panel.click_role(label, Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(input); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + assert_eq!(super::super::tests_warp::json_fields(&panel.app(), dialog_id(KIND))[key], value); + } + panel.click("OK"); + assert!(!super::super::tests_warp::open_ids(&panel.app()).contains(&dialog_id(KIND))); + let app = panel.app(); + let state = app.session.active().unwrap(); + let symbol = state.doc.symbols.iter().find(|symbol| symbol.name == "Keyboard badge").unwrap(); + assert_eq!(symbol.dynamic, editing); + assert_eq!(state.doc.symbol_pixel_aligned("Keyboard badge"), !editing); + assert_eq!( + state.doc.symbol_nine_slice("Keyboard badge"), + Some(vectorcraft_doc::SymbolNineSlice { left: 0.1, top: 0.2, right: 0.3, bottom: 0.4 }) + ); + assert_eq!(state.doc.symbols.len(), 1); + assert_eq!(state.history.undo.len(), undo + 1); + } + } #[test] fn editing_symbol_options_does_not_rename_another_drawings_symbol() { @@ -225,4 +312,67 @@ mod document_tests { accept(&mut app, id); assert!(app.session.active().unwrap().doc.symbols.iter().any(|symbol| symbol.name == "Source badge")); } + + #[test] + fn new_symbol_does_not_replace_art_selected_after_opening() { + let mut app = windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let original = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); + let other = app.run("shape.rectangle", json!({"x": 60, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [original]})).unwrap(); + open(&mut app, false).unwrap(); + let id = dialog_id(KIND); + set(&app, id, "name", json!("Badge")); + app.run("select.set", json!({"ids": [other]})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + + answer_dialog(&mut app, id, &[], true); + assert!(app.session.active().unwrap().doc == before, "OK cannot turn the later selection into a symbol"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + app.run("select.set", json!({"ids": [original]})).unwrap(); + answer_dialog(&mut app, id, &[], true); + let symbols = app.run("symbol.list", json!({})).unwrap(); + assert_eq!(symbols["symbols"][0]["name"], "Badge"); + assert_eq!(symbols["symbols"][0]["size"], json!([30.0, 30.0]), "the original art becomes the symbol"); + assert!(app.session.active().unwrap().doc.node(NodeId(other)).is_some(), "the unrelated rectangle remains"); + } + + #[test] + fn editing_symbol_options_keeps_the_definition_restored_by_revert() { + let mut app = windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap(); + app.run("symbol.new", json!({"name": "Badge"})).unwrap(); + let file = std::env::temp_dir().join(format!("vectorcraft-symbol-options-revert-{}.vectorcraft", std::process::id())); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": file.to_string_lossy()})).unwrap(); + let st = app.session.active().unwrap(); + let (uid, reverts) = (st.uid, st.reverts); + + app.run("symbol.options", json!({"name": "Badge", "registration": 0})).unwrap(); + open_edit(&mut app, Some("Badge")).unwrap(); + let id = dialog_id(KIND); + set(&app, id, "name", json!("Edited badge")); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let _ = std::fs::remove_file(file); + let st = app.session.active().unwrap(); + assert_eq!((st.uid, st.reverts), (uid, reverts + 1)); + assert_eq!(st.doc.symbol_registration("Badge").0, 4); + let restored = st.doc.clone(); + let undo = st.history.undo.len(); + + answer_dialog(&mut app, id, &[], true); + assert_eq!(app.session.active().unwrap().doc.symbols[0].name, "Badge", "the restored symbol keeps its name"); + assert_eq!(app.session.active().unwrap().doc, restored); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + dismiss(&mut app, id); + open_edit(&mut app, Some("Badge")).unwrap(); + set(&app, id, "name", json!("New badge")); + accept(&mut app, id); + assert_eq!(app.session.active().unwrap().doc.symbols[0].name, "New badge"); + } } diff --git a/crates/ui-egui/src/dialogs/tate_chu_yoko.rs b/crates/ui-egui/src/dialogs/tate_chu_yoko.rs index 73b2f604de..e2f32ef4fd 100644 --- a/crates/ui-egui/src/dialogs/tate_chu_yoko.rs +++ b/crates/ui-egui/src/dialogs/tate_chu_yoko.rs @@ -39,7 +39,8 @@ fn rows(lengths: LengthUnits) -> Vec { /// Open Tate-chu-yoko Settings on the characters the Character panel acts on. pub fn open(app: &mut VectorcraftApp) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; - let document = app.session.active().ok_or("no document")?.uid; + let active = app.session.active().ok_or("no document")?; + let (document, reverts) = (active.uid, active.reverts); let (up, right) = crate::panels::character::shared_tcy_offsets(app); let mut fields = DialogFields::new(); for (key, v) in KEYS.into_iter().zip([up, right]) { @@ -56,8 +57,13 @@ pub fn open(app: &mut VectorcraftApp) -> Result { if p.is_empty() { return Ok(()); } - if !app.session.active().is_some_and(|active| active.uid == document) { - return Err(tl!("Tate-chu-yoko Settings can only change the document where it was opened.").to_owned()); + let active = app + .session + .active() + .filter(|active| active.uid == document) + .ok_or_else(|| tl!("Tate-chu-yoko Settings can only change the document where it was opened.").to_owned())?; + if active.reverts != reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); } crate::panels::character::run_format(app, Value::Object(p)).map(|_| ()) }) @@ -199,4 +205,35 @@ mod tests { driver::ok(&mut app); assert_eq!(offsets(&app, id), [(0.0, 6.0), (0.0, 0.0)]); } + + #[test] + fn tate_chu_yoko_approval_refuses_to_change_restored_text() { + let (mut app, id) = app(); + let dir = vectorcraft_testkit::TempDir::new("tate_chu_yoko-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + let before = offsets(&app, id); + app.run("text.setFormat", json!({"ids": [id], "tcyUpDown": 3})).unwrap(); + app.run("ui.tateChuYokoSettings", json!({})).unwrap(); + driver::set(&mut app, "tcyUpDown", json!(7)); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + let dialog = craft::ui::dialog::dialog_id(KIND); + crate::tests::picks::answer_dialog(&mut app, dialog, &[], true); + assert_eq!(offsets(&app, id), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!( + app.dialogs().unwrap().with(|h| h.held_state(dialog)), + Some(craft::ui::dialog::HeldOk::Refused(reason)) if reason.as_str().contains("document was reverted") + )); + + driver::cancel(&mut app); + app.run("ui.tateChuYokoSettings", json!({})).unwrap(); + driver::set(&mut app, "tcyUpDown", json!(7)); + driver::ok(&mut app); + assert_eq!(offsets(&app, id)[0].0, 7.0); + } } diff --git a/crates/ui-egui/src/dialogs/tests_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index abbd37dfb7..ce286be347 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -137,6 +137,39 @@ fn define_grid_applies_only_to_the_document_where_it_opened() { assert_eq!(grid(&app).right_color.hex(), "#112233"); } +#[test] +fn define_grid_requires_a_fresh_opening_after_native_revert() { + let mut app = app(); + let dir = vectorcraft_testkit::TempDir::new("define-grid-revert"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("perspective.grid.define", json!({"rightColor": "#123456"})).unwrap(); + app.run("file.saveAs", json!({"path": dir.join("Grid.vectorcraft")})).unwrap(); + app.run("perspective.grid.define", json!({"rightColor": "#765432"})).unwrap(); + let source = app.session.active().unwrap(); + let (uid, reverts) = (source.uid, source.reverts); + app.run("ui.perspectiveGridDialog", json!({})).unwrap(); + set(&mut app, "rightColor", json!("#abcdef")).unwrap(); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let restored = app.session.active().unwrap(); + assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1)); + let undo = restored.history.undo.len(); + ok(&mut app); + assert_eq!(grid(&app).right_color.hex(), "#123456"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + let id = dialog_id(super::perspective_grid::KIND); + assert!(matches!(host(&app, |h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + let ctx = window(&app); + assert!(host(&app, |h| h.cancel_by_id(&ctx, id))); + frame(&mut app); + app.run("ui.perspectiveGridDialog", json!({})).unwrap(); + set(&mut app, "rightColor", json!("#abcdef")).unwrap(); + ok(&mut app); + assert_eq!(grid(&app).right_color.hex(), "#abcdef"); +} + #[test] fn define_grid_loads_and_saves_presets() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/tests_print_presets.rs b/crates/ui-egui/src/dialogs/tests_print_presets.rs index a14ad40635..edd26c2a9d 100644 --- a/crates/ui-egui/src/dialogs/tests_print_presets.rs +++ b/crates/ui-egui/src/dialogs/tests_print_presets.rs @@ -119,6 +119,88 @@ fn the_manager_adds_edits_and_deletes_presets_through_the_editor() { assert!(!is_open(&app), "Close"); } +#[test] +fn print_presets_difference_caption_uses_the_visible_default_name() { + use egui::accesskit::{Node, NodeId, Role}; + use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + fn modal_nodes(out: &[(NodeId, Node)]) -> Vec<&Node> { + let modal = out.iter().find(|(_, node)| node.role() == Role::Dialog).expect("Print Presets dialog").0; + let by_id: std::collections::HashMap<_, _> = out.iter().map(|(id, node)| (*id, node)).collect(); + let mut pending = vec![modal]; + let mut nodes = Vec::new(); + while let Some(id) = pending.pop() { + let Some(node) = by_id.get(&id) else { continue }; + nodes.push(*node); + pending.extend_from_slice(node.children()); + } + nodes + } + + let mut failures = Vec::new(); + let name = "Épreuve — Δοκιμή"; + for lang in ["en", "fr", "el"] { + for height in [500.0, 800.0] { + let mut app = new_app(Default::default()); + app.session.prefs.interface_language = lang.into(); + app.run("print.presets.save", json!({"name": name, "settings": {"copies": 2}})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + ctx.enable_accesskit(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, height)); + 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.printPresetsDialog", json!({})).unwrap(); + for _ in 0..6 { + draw(&mut app, vec![]); + } + let default_label = crate::i18n::t(DEFAULT_PRESET); + if lang != "en" { + assert_ne!(default_label, DEFAULT_PRESET, "the tested locale has its own Default name"); + } + let expected = crate::i18n::fmt(crate::i18n::t("Differences from {preset}:"), &[("preset", default_label)]); + let stock = crate::i18n::fmt(crate::i18n::t("Differences from {preset}:"), &[("preset", DEFAULT_PRESET)]); + let frame = draw(&mut app, vec![]).platform_output.accesskit_update.unwrap().nodes; + let nodes = modal_nodes(&frame); + let row = |label| { + nodes + .iter() + .find(|node| matches!(node.role(), Role::ListItem | Role::ListBoxOption) && node.label() == Some(label)) + .unwrap_or_else(|| panic!("{lang} at 800 by {height}: missing preset row {label:?}")) + }; + assert_eq!(row(default_label).is_selected(), Some(true)); + let bounds = row(name).bounds().unwrap(); + let click = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32); + assert!(screen.contains(click)); + if !nodes.iter().any(|node| node.label() == Some(expected.as_str())) { + failures.push(format!( + "{lang} at 800 by {height}, Default: expected {expected:?}, English name present: {}", + nodes.iter().any(|node| node.label() == Some(stock.as_str())) + )); + } + draw(&mut app, vec![Event::PointerMoved(click)]); + for pressed in [true, false] { + draw(&mut app, vec![Event::PointerButton { pos: click, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + draw(&mut app, vec![]); + assert_eq!(fields(&app)["selected"], name); + let frame = draw(&mut app, vec![]).platform_output.accesskit_update.unwrap().nodes; + let nodes = modal_nodes(&frame); + if !nodes.iter().any(|node| node.label() == Some(expected.as_str())) { + failures.push(format!( + "{lang} at 800 by {height}, saved preset: expected {expected:?}, English name present: {}", + nodes.iter().any(|node| node.label() == Some(stock.as_str())) + )); + } + crate::i18n::set_current(crate::i18n::Lang::EN); + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + #[test] fn presets_files_import_and_export() { let dir = std::env::temp_dir().join(format!("vc-printpresets-ui-{}", std::process::id())); diff --git a/crates/ui-egui/src/dialogs/text_export.rs b/crates/ui-egui/src/dialogs/text_export.rs index 0e4b8d262a..ab33e24e2c 100644 --- a/crates/ui-egui/src/dialogs/text_export.rs +++ b/crates/ui-egui/src/dialogs/text_export.rs @@ -6,6 +6,7 @@ use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::Label; use serde_json::Value; +use vectorcraft_doc::NodeId; use super::export_host::{self, After, Export, Open, options}; use super::form; @@ -32,11 +33,28 @@ fn params(can_select: bool) -> Vec { ] } +/// The drawing and selected objects a Selection Only export started with. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct SelectionSource { + drawing: (u64, u64), + objects: Vec, +} + +impl SelectionSource { + fn of(app: &VectorcraftApp) -> Option { + let state = app.session.active()?; + let mut objects = state.selection.objects.clone(); + objects.sort_unstable(); + Some(Self { drawing: (state.uid, state.reverts), objects }) + } +} + /// Open the options for exporting the document's text to `path`; `selection` when Export Selection opened them. pub fn open(app: &mut VectorcraftApp, path: &str, selection: bool) -> Result<(), String> { let ctx = app.ui_ctx.clone().ok_or("no window")?; // Export Selection keeps Selection Only on. - let can_select = !selection && app.session.active().is_some_and(|st| !st.selection.objects.is_empty()); + let source = SelectionSource::of(app); + let can_select = !selection && source.as_ref().is_some_and(|source| !source.objects.is_empty()); // The platform's own line endings by default. let eol = if cfg!(windows) { LINE_ENDINGS[1] } else { LINE_ENDINGS[0] }; let mut fields = DialogFields::from_pairs([("format", "txt"), ("path", path), ("encoding", ENCODINGS[0]), ("lineEndings", eol)]); @@ -44,12 +62,15 @@ pub fn open(app: &mut VectorcraftApp, path: &str, selection: bool) -> Result<(), let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { ParamDialog::new(KIND, tl!("Text Export Options"), params(can_select)).values(Bind::bound(fields)).ok_label(Label::from("Export")) }); - export_host::open(app, Export::Text, selection, dialog).map(|_| ()).ok_or_else(|| "no window".into()) + export_host::open(app, Export::Text { source }, selection, dialog).map(|_| ()).ok_or_else(|| "no window".into()) } /// Write the text file (the command runs first, so a bad option keeps the dialog open). Opened by /// Export Selection, it writes `document.exportSelection`'s text. -pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result { +pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, source: Option<&SelectionSource>, fields: &DialogFields) -> Result { + if (open.selection || fields.bool("selectionOnly") == Some(true)) && SelectionSource::of(app).as_ref() != source { + return Err(tl!("Select the original artwork to export it, or reopen Text Export Options.").into()); + } let mut params = Value::Object(form::json_of(¶ms(true), fields)); let id = if open.selection { if let Some(o) = params.as_object_mut() { @@ -62,3 +83,43 @@ pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFiel io::save_command_output(app, id, "txt", params, |_, _| Ok(Value::Null))?; Ok(None) } + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::super::tests_export::{app_saving, frame, kind, set, try_confirm}; + + #[test] + fn selection_only_text_export_stays_on_the_opening_artwork() { + for export_selection in [true, false] { + let (mut app, written) = app_saving(1, |_| "/output/selection.txt".into()); + let first = app.run("text.create", json!({"x": 5, "y": 10, "text": "First text"})).unwrap()["id"].clone(); + let second = app.run("text.create", json!({"x": 5, "y": 25, "text": "Second text"})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [first]})).unwrap(); + if export_selection { + app.run("document.exportSelection", json!({})).unwrap(); + frame(&mut app); + } else { + app.run("file.exportAs", json!({"format": "txt"})).unwrap(); + try_confirm(&mut app).unwrap(); + set(&mut app, "selectionOnly", json!(true)); + } + assert_eq!(kind(&app).as_deref(), Some("txtOptions")); + + app.run("select.set", json!({"ids": [second]})).unwrap(); + let why = try_confirm(&mut app).expect_err("the original selection is required"); + assert!(why.contains("original artwork")); + assert_eq!(kind(&app).as_deref(), Some("txtOptions")); + assert!(written.borrow().is_empty()); + + app.run("select.set", json!({"ids": [first]})).unwrap(); + try_confirm(&mut app).unwrap(); + let output = written.borrow(); + assert_eq!(output.len(), 1); + let contents = std::str::from_utf8(&output[0].1).unwrap(); + assert!(contents.contains("First text")); + assert!(!contents.contains("Second text")); + } + } +} diff --git a/crates/ui-egui/src/dialogs/tool_options.rs b/crates/ui-egui/src/dialogs/tool_options.rs index 8617273aa3..f83ddd7ee9 100644 --- a/crates/ui-egui/src/dialogs/tool_options.rs +++ b/crates/ui-egui/src/dialogs/tool_options.rs @@ -4,10 +4,11 @@ // PLAN: ui-egui reaches the framework through `craft::..`; the crate's Cargo.toml needs the `craft` dependency // (hub-w1 owns the manifest). use craft::behavior::Anchor9; +use craft::i18n::Word; use craft::ui::contract::{Bind, Show as _}; use craft::ui::patterns::form_dialogs::{DialogFields, Param}; use craft::ui::pickers::{ReferencePoint, ReferencePointLook}; -use craft::ui::runtime::env::Label; +use craft::ui::runtime::env::{Label, WordRows, WordsOverride, with_env}; use serde_json::{Map, Value, json}; use vectorcraft_doc::Unit; @@ -30,13 +31,35 @@ pub(crate) fn reference_index(fields: &DialogFields, key: &str) -> usize { fields.int(key).map_or(0, |n| n.clamp(0, 8) as usize) } +/// The dialog reference picker's corner labels use the app catalog's existing title-case keys. +fn localized_reference_corners() -> WordRows { + [ + (Word::keyed("referencePoint.topLeft", "Top left"), "Top Left"), + (Word::keyed("referencePoint.topRight", "Top right"), "Top Right"), + (Word::keyed("referencePoint.bottomLeft", "Bottom left"), "Bottom Left"), + (Word::keyed("referencePoint.bottomRight", "Bottom right"), "Bottom Right"), + ] + .into_iter() + .fold(WordRows::new(), |rows, (word, source)| { + let translated = tl!(source); + if translated == source { rows } else { rows.row(word, translated) } + }) +} + /// A row of the nine-point reference picker over the index `key` holds ([`reference_index`]). pub(crate) fn reference_param(key: &str, label: impl Into