diff --git a/Cargo.lock b/Cargo.lock index e6d867905b..28a8205997 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8670,6 +8670,7 @@ name = "vectorcraft-js" version = "0.24.1" dependencies = [ "chrono", + "craft-xml", "getrandom 0.4.3", "proptest", "unicode-properties", diff --git a/ROADMAP.md b/ROADMAP.md index c8c020dcd3..abd6bea6bf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. + - 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged. - 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged. @@ -255,6 +257,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. | | 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. The Essentials readiness row's Shape Builder item names what its 4–8 h still covers (checking #937's fix on the reporter's file, still unconfirmed). Headline numbers unchanged. | | 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). | | 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index b5c993a865..7c96cc6104 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -57,6 +57,37 @@ impl Document { pick(&|r| r.contains(p)).or_else(|| pick(&|r| artboard_holds(r, p))) } + /// Which artboard in the document owns object bounds `b`: the artboard that holds its center, + /// or the one it has the greatest overlap area with if its center lies outside all artboards. + /// Bounds with no width or no height (a straight horizontal or vertical line) have no area, so + /// for them the overlap is the length of the line on the artboard. + pub fn artboard_for_bounds(&self, b: Rect) -> Option { + let c = b.center(); + if let Some(i) = self.artboard_holding(c, false) { + return Some(i); + } + let (flat_x, flat_y) = (b.x1 - b.x0 <= 1e-9, b.y1 - b.y0 <= 1e-9); + let mut best: Option<(usize, f64)> = None; + for (i, a) in self.artboards.iter().enumerate() { + let r = a.rect; + let w = b.x1.min(r.x1) - b.x0.max(r.x0); + let h = b.y1.min(r.y1) - b.y0.max(r.y0); + if w < 0.0 || h < 0.0 { + continue; + } + let overlap = match (flat_x, flat_y) { + (true, true) => 0.0, + (true, false) => h, + (false, true) => w, + (false, false) => w * h, + }; + if overlap > 1e-9 && best.is_none_or(|(_, max)| overlap > max + 1e-9) { + best = Some((i, overlap)); + } + } + best.map(|(i, _)| i) + } + /// The art that moves with an artboard at `rect`: top-level objects (children of layers and /// sublayers) lying entirely inside it, with symbol instances measured by their art. Locked and /// hidden objects and layers stay put unless `locked_and_hidden` (Selection & Anchor Display › @@ -89,6 +120,54 @@ impl Document { art } + /// The art that is copied when artboard `index` is duplicated or copied: objects wholly inside + /// the artboard (with rounding tolerance), objects within its bleed rectangle, and artwork + /// placed on/overlapping this artboard that belongs to it by center or primary overlap + /// ([`Document::artboard_for_bounds`]). + pub fn art_for_artboard_copy(&self, index: usize, locked_and_hidden: bool) -> Vec { + let Some(rect) = self.artboards.get(index).map(|a| a.rect) else { return vec![] }; + let r = rect.inflate(1e-6, 1e-6); + let on_copy = |b: Rect| -> bool { + // 1. Wholly inside the artboard (edges included, with tolerance). + if b.x0 >= r.x0 && b.y0 >= r.y0 && b.x1 <= r.x1 && b.y1 <= r.y1 { + return true; + } + // 2. Within the artboard's bleed rectangle (if document setup specifies bleed). + if self.setup.has_bleed() { + let br = self.setup.bleed_rect(rect).inflate(1e-6, 1e-6); + if b.x0 >= br.x0 && b.y0 >= br.y0 && b.x1 <= br.x1 && b.y1 <= br.y1 { + return self.artboard_for_bounds(b).is_none_or(|owner| owner == index); + } + } + // 3. Artwork that intersects this artboard and belongs to it (#4479). + let inter_x0 = b.x0.max(r.x0); + let inter_y0 = b.y0.max(r.y0); + let inter_x1 = b.x1.min(r.x1); + let inter_y1 = b.y1.min(r.y1); + if inter_x1 < inter_x0 || inter_y1 < inter_y0 { + return false; + } + self.artboard_for_bounds(b) == Some(index) + }; + fn collect(n: &Node, s: &SymbolBoxes, on: &dyn Fn(Rect) -> bool, all: bool, out: &mut Vec) { + for c in n.children().into_iter().flatten().filter(|c| c.rides_with_artboard(all)) { + if c.is_layer() { + collect(c, s, on, all, out); + } else if let Some(b) = c.geometric_bounds_with(s) + && on(b) + { + out.push(c.id); + } + } + } + let symbols = self.symbol_boxes(); + let mut art = vec![]; + for l in self.layers.iter().filter(|l| l.rides_with_artboard(locked_and_hidden)) { + collect(l, &symbols, &on_copy, locked_and_hidden, &mut art); + } + art + } + /// Does any artwork lie on `rect` (an artboard)? Artwork is any object under the layers, /// hidden and locked ones and those on template layers included, whose visual bounds (symbol /// instances measured by their art) meet `rect`; touching its edge counts. A group (not a clip diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 0801187b6d..a39260ee91 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -435,6 +435,142 @@ fn art_on_artboard_tolerates_roundoff_at_each_edge() { } } +#[test] +fn art_for_artboard_copy_takes_artwork_larger_than_artboard_or_with_bleed() { + let mut d = Document::new(200.0, 200.0); + d.setup.bleed = [9.0; 4]; + let layer = d.layers[0].id; + // An oversized background (250x250 centered on the 200x200 artboard, #4479). + let bg = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(bg, shapes::rectangle(Rect::new(-25.0, -25.0, 225.0, 225.0)), Appearance::default_art())).unwrap(); + // A shape with 5pt bleed over the top-right corner. + let bleed = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(bleed, shapes::rectangle(Rect::new(150.0, -5.0, 205.0, 50.0)), Appearance::default_art())).unwrap(); + // A shape lying entirely in the bleed margin without touching the artboard itself (-8..-2 vs 0..200). + let bleed_margin_only = d.alloc_id(); + d.insert( + Some(layer), + usize::MAX, + Node::path(bleed_margin_only, shapes::rectangle(Rect::new(-8.0, 50.0, -2.0, 100.0)), Appearance::default_art()), + ) + .unwrap(); + // A small shape hanging 20pt over the left edge (center outside, more than bleed). + let hanging = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(hanging, shapes::rectangle(Rect::new(-20.0, 90.0, 10.0, 120.0)), Appearance::default_art())) + .unwrap(); + // A straight line hanging 60pt over the left edge (center outside, no area): it lies on the + // artboard for 40pt, so it is copied as a thin rectangle there would be. + let line = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(line, shapes::line(Point::new(-60.0, 150.0), Point::new(40.0, 150.0)), Appearance::default_art())) + .unwrap(); + // A shape completely outside the artboard. + let outside = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(outside, shapes::rectangle(Rect::new(300.0, 300.0, 400.0, 400.0)), Appearance::default_art())) + .unwrap(); + + // Standard art_on_artboard keeps strict containment: none of the overhanging shapes are on it. + let strict_art = d.art_on_artboard(Rect::new(0.0, 0.0, 200.0, 200.0), false); + assert!(!strict_art.contains(&bg), "strict art_on_artboard excludes oversized background"); + assert!(!strict_art.contains(&bleed), "strict art_on_artboard excludes bleed shape"); + assert!(!strict_art.contains(&bleed_margin_only), "strict art_on_artboard excludes bleed-margin-only shape"); + assert!(!strict_art.contains(&hanging), "strict art_on_artboard excludes hanging shape"); + assert!(!strict_art.contains(&outside), "strict art_on_artboard excludes outside shape"); + + // Copying the artboard takes the artwork touching this artboard that belongs to it, or within bleed. + let copy_art = d.art_for_artboard_copy(0, false); + assert!(copy_art.contains(&bg), "oversized background is copied with artboard: {copy_art:?}"); + assert!(copy_art.contains(&bleed), "bleed shape is copied with artboard: {copy_art:?}"); + assert!(copy_art.contains(&bleed_margin_only), "bleed-margin-only shape is copied with artboard: {copy_art:?}"); + assert!(copy_art.contains(&hanging), "touching shape owned by artboard 0 is copied: {copy_art:?}"); + assert!(copy_art.contains(&line), "a line hanging over the edge is copied: {copy_art:?}"); + assert!(!copy_art.contains(&outside), "outside shape is not copied: {copy_art:?}"); + + // If Artboard 1 is added next to Artboard 0, art primarily on Artboard 1 is not copied with Artboard 0: + d.artboards.push(Artboard { + id: 2, + name: "Artboard 2".into(), + rect: Rect::new(200.0, 0.0, 400.0, 200.0), + locked: false, + show_center_mark: false, + show_cross_hairs: false, + 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(); + d.insert(Some(layer), usize::MAX, Node::path(neighbor_art, shapes::rectangle(Rect::new(190.0, 50.0, 300.0, 150.0)), Appearance::default_art())) + .unwrap(); + + let copy_art0 = d.art_for_artboard_copy(0, false); + assert!(!copy_art0.contains(&neighbor_art), "art owned by neighboring Artboard 1 is not copied with Artboard 0"); + let copy_art1 = d.art_for_artboard_copy(1, false); + assert!(copy_art1.contains(&neighbor_art), "art owned by Artboard 1 is copied with Artboard 1"); +} + +#[test] +fn artboard_for_bounds_edge_cases_and_tie_breaks() { + let mut d = Document::new(100.0, 100.0); + // Artboard 0: (0, 0, 100, 100) + // Artboard 1: (200, 0, 300, 100) + d.artboards.push(Artboard { + id: 2, + name: "Artboard 2".into(), + rect: Rect::new(200.0, 0.0, 300.0, 100.0), + locked: false, + show_center_mark: false, + show_cross_hairs: false, + 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: + // Bounds: (50, -100, 150, 50) -> Center: (100, -25) which is outside all artboards. + // Overlap with Board 0: 50x50 = 2500; Board 1: 0. + let b_center_outside = Rect::new(50.0, -100.0, 150.0, 50.0); + assert_eq!(d.artboard_for_bounds(b_center_outside), Some(0)); + + // 2. Equal overlap on two boards (defined tie-break: the lower index, board 0): + // Bounds: (50, -50, 250, 50) -> Center: (150, 0) outside all boards. + // Overlap with Board 0: (50..100) x (0..50) = 2500; Board 1: (200..250) x (0..50) = 2500. + let b_equal_overlap = Rect::new(50.0, -50.0, 250.0, 50.0); + assert_eq!(d.artboard_for_bounds(b_equal_overlap), Some(0), "equal overlap picks lower index"); + + // 3. No overlap at all: returns None. + let b_no_overlap = Rect::new(500.0, 500.0, 600.0, 600.0); + assert_eq!(d.artboard_for_bounds(b_no_overlap), None); + + // 4. Rotated object bounds (bounds, not the inner geometry): + // A 40x40 square rotated 45 deg centered at (50, 50) has bounding box ~56.57x56.57. + let b_rotated_bounds = Rect::new(50.0 - 28.28, 50.0 - 28.28, 50.0 + 28.28, 50.0 + 28.28); + assert_eq!(d.artboard_for_bounds(b_rotated_bounds), Some(0)); + + // 5. Zero-size bounds (a point): + // On board 0: + let b_zero_on_board = Rect::new(50.0, 50.0, 50.0, 50.0); + assert_eq!(d.artboard_for_bounds(b_zero_on_board), Some(0)); + // Outside all boards: + let b_zero_outside = Rect::new(150.0, 50.0, 150.0, 50.0); + assert_eq!(d.artboard_for_bounds(b_zero_outside), None); + + // 6. Straight lines whose center is outside every board: owned by the board they lie on most, + // as a rectangle of any thickness would be (they have no area to compare). + // Horizontal, from x = -100 to 50 on board 0: center (-25, 50). + assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.0)), Some(0)); + assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.1)), Some(0), "the same as a thin rectangle"); + // Vertical, from y = -100 to 50 on board 1: center (250, -25). + assert_eq!(d.artboard_for_bounds(Rect::new(250.0, -100.0, 250.0, 50.0)), Some(1)); + // Below both boards. + assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 120.0, 260.0, 120.0)), None); + // Across the gap between the boards, 20 pt on board 0 and 60 on board 1. + assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 50.0, 260.0, 50.0)), Some(1), "center (170, 50) in the gap: board 1 holds more of it"); + // Only touching a board's corner from outside: no overlap. + assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 0.0, 0.0, 0.0)), None); +} + /// The art on a locked artboard (each object of a layer whose bounds overlap it, a group as one /// object) can't be edited, and Select All, a click and a marquee pass over it; art flush with /// the artboard from outside isn't on it, a layer is on no artboard, and new art isn't on one. 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/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 0d25a6e57a..5344159583 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -562,16 +562,30 @@ fn mode_converter(mode: ColorMode, intent: Option, grays: Grays) -> impl } /// The name and color of each global swatch of `d`, for [`mode_color`]. -fn global_bases(d: &vectorcraft_doc::Document) -> Vec<(String, Color)> { - d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect() +fn global_bases(d: &vectorcraft_doc::Document) -> BTreeMap { + let mut first = BTreeMap::new(); + for w in d.swatches_iter() { + // An ineligible first record still shadows a later global solid of the same name. + first.entry(w.name.as_str()).or_insert(w); + } + first + .into_values() + .filter_map(|w| { + if !w.global { + return None; + } + let Paint::Solid { color, swatch: None, .. } = &w.paint else { return None }; + Some((w.name.clone(), d.linked_color(*color, w.spot))) + }) + .collect() } /// The color Document Color Mode gives `col` (swatch link `link`): a tint of a global swatch in /// `bases` (already converted) is that swatch's color at its tint; any other color goes through /// `conv` ([`mode_converter`]). -fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: &dyn Fn(&Color) -> Color) -> Color { - match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) { - Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint), +fn mode_color(col: &Color, link: proof::Link, bases: &BTreeMap, conv: &dyn Fn(&Color) -> Color) -> Color { + match link.and_then(|(name, tint)| Some((bases.get(name)?, tint))) { + Some((base, tint)) if tint < 1.0 => base.tinted(tint), _ => conv(col), } } @@ -685,8 +699,8 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co vectorcraft_brush::store(d, &brushes); } // This pass gives tint swatches their converted swatch's color at their tint; the passes above already did the same for the art's tints. - d.map_solid_paints(&mut |c, link, tint| match bases.iter().find(|(n, _)| Some(n) == link.as_ref()) { - Some((_, base)) if *tint < 1.0 => { + d.map_solid_paints(&mut |c, link, tint| match link.as_ref().and_then(|name| bases.get(name)) { + Some(base) if *tint < 1.0 => { *c = base.tinted(*tint); true } 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/edit.rs b/crates/engine/src/cmd/edit.rs index 3922a8e1f0..032aa87927 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -815,6 +815,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { turned.recost_paints(); st.history.redo.push(turned); st.history.trim(); + st.history_restores += 1; st.revision += 1; st.selection.prune(&st.doc); // Guides locked and slices locked or hidden since the step was made stay deselected. @@ -852,6 +853,7 @@ fn redo(s: &mut Session, _: &Value) -> Result { turned.recost_paints(); st.history.undo.push(turned); st.history.trim(); + st.history_restores += 1; st.revision += 1; st.selection.prune(&st.doc); crate::deselect_hidden(&menu, &st.doc, &mut st.selection); diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index da5bbea659..01e0a5a732 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -124,6 +124,17 @@ impl StopOwner { } } +/// The drawing paints affected by an edit from the Gradient panel. +#[derive(PartialEq)] +pub struct GradientEditPaints(Vec); + +#[derive(PartialEq)] +struct EditedPaint { + id: NodeId, + item: Option, + paints: Vec, +} + impl Session { /// Does `paint.editGradient` without `ids` edit objects on the fill (or the stroke, `stroke`)? It does not /// while the active tool paints with the chosen fill (or stroke: [`Session::tool_paints`]) or when nothing it @@ -136,6 +147,36 @@ impl Session { .is_ok_and(|item| item.of_kind(self, !stroke).targets_for(self, &p, !stroke).is_ok_and(|ids| !ids.is_empty())) } + /// Snapshot the paints a gradient edit without explicit targets would write, by object and + /// appearance item. Text without an item has one paint per run. The proxy can display just + /// the first paint when an edit goes to several objects or text runs. + pub fn gradient_edit_paints(&self, stroke: bool) -> Result { + const CMD: &str = "paint.editGradient"; + let p = json!({ "stroke": stroke }); + if super::paint::for_tool(self, &p, stroke) { + return Ok(GradientEditPaints(Vec::new())); + } + let doc = &self.doc()?.doc; + let item = item_target(self, &p, CMD)?.of_kind(self, !stroke); + let ids = item.targets_for(self, &p, !stroke)?; + let ids = super::appearance::drop_design_art_rows(self, ids, item, !stroke, CMD)?; + let mut out = Vec::with_capacity(ids.len()); + for (id, item) in ids.iter().copied().zip(item.per_target(self, &ids)) { + let (Some(node), Some(item)) = (doc.node(id), item) else { continue }; + let index = item.resolve(&node.appearance, !stroke, CMD)?; + let (item, paints) = if index.is_none() + && let NodeKind::Text(text) = &node.kind + { + (None, text.runs.iter().map(|run| if stroke { run.style.stroke.clone() } else { run.style.fill.clone() }).collect()) + } else { + let item = index.or_else(|| node.appearance.items.iter().rposition(|row| row.is_fill() != stroke)); + (item, node.appearance.paint_at(index, !stroke).cloned().into_iter().collect()) + }; + out.push(EditedPaint { id, item, paints }); + } + Ok(GradientEditPaints(out)) + } + /// The selected gradient stop (`gradient.selectStop`), while the gradient it was selected on /// is still the one behind the active proxy. Callers check it against the stop count (an undo /// can remove stops). diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 77cdfdcb7d..433c69202c 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -8,6 +8,7 @@ use vectorcraft_geom::{Rect, Vec2}; use super::{Affine, CommandSpec, NodeId, Result, Session, bad, bool_or, check_switches, cmd, has_doc, index, ok, switch_or}; use crate::{Clipboard, EngineError}; +/// The panel command specifications registered with the engine. pub fn specs() -> Vec { vec![ cmd!("artboard.reorder", "Move Artboard Up/Down", [], None, "{index, to} change an artboard's number", has_doc, artboard_reorder), @@ -16,7 +17,7 @@ pub fn specs() -> Vec { "Duplicate Artboard", ["Window", "Artboards"], None, - "{index?: n | indices?: [n…] (default: the artboards the Artboard tool has selected), selectedArtboards?: [n…] (the journal records that default here, for a replay), art?: bool (default: the Artboard tool's moveArt option), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (locked and hidden art goes too; default: prefs moveLockedWithArtboard), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the copies go together on that side of the artboards they copy, 20 pt away)} a copy of each artboard, the copies placed together right of the last artboard as they lay (or on `side`), with copies of the art fully inside each when `art`, in one undo step → {index: the first copy's index, indices: the copies' indices, ids: the art's copies}", + "{index?: n | indices?: [n…] (default: the artboards the Artboard tool has selected), selectedArtboards?: [n…] (the journal records that default here, for a replay), art?: bool (default: the Artboard tool's moveArt option), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (locked and hidden art goes too; default: prefs moveLockedWithArtboard), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the copies go together on that side of the artboards they copy, 20 pt away)} a copy of each artboard, the copies placed together right of the last artboard as they lay (or on `side`), with copies of the art on each (fully inside, within its bleed or centered/overlapping on it, #4479) when `art`, in one undo step → {index: the first copy's index, indices: the copies' indices, ids: the art's copies}", has_doc, artboard_duplicate ), @@ -25,7 +26,7 @@ pub fn specs() -> Vec { "Copy Artboard", [], None, - "{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} (defaults as artboard.duplicate) put the artboards, and the art fully inside each when `art`, on the clipboard: edit.paste adds a copy of each, together right of the last artboard as they lay, edit.pasteInPlace/InFront/InBack where they were, in this or another document (one undo step; edit.pasteOnAllArtboards pastes only the art); edit.copy runs this while the Artboard tool is chosen → {copied: objects}", + "{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} (defaults as artboard.duplicate) put the artboards, and the art on each (fully inside, within its bleed or centered/overlapping on it, #4479) when `art`, on the clipboard: edit.paste adds a copy of each, together right of the last artboard as they lay, edit.pasteInPlace/InFront/InBack where they were, in this or another document (one undo step; edit.pasteOnAllArtboards pastes only the art); edit.copy runs this while the Artboard tool is chosen → {copied: objects}", has_doc, |s, p| { boards_and_art_noted(s, p, "artboard.copy")?; @@ -37,7 +38,7 @@ pub fn specs() -> Vec { "Cut Artboard", [], None, - "{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} artboard.copy, then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}", + "{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}", has_doc, |s, p| { boards_and_art_noted(s, p, "artboard.cut")?; @@ -288,16 +289,19 @@ pub(crate) fn locked_and_hidden(s: &mut Session, p: &Value, art: bool, cmd: &str Ok(all) } -/// The art that goes with artboard `i` when `art`: the objects fully inside it (locked and hidden -/// ones only when `all`), in paint order. With `moving` (a move or a cut), the art also on another -/// locked artboard stays unless `all` ([`vectorcraft_doc::Document::art_moving_with`]); a copy -/// takes it. +/// The art that goes with artboard `i` when `art`: when copying, the art on the artboard (fully +/// inside, within its bleed or centered/overlapping on it, #4479); with `moving` (a move or a cut), +/// the objects fully inside it (locked and hidden ones only when `all`), in paint order. With +/// `moving`, the art also on another locked artboard stays unless `all` +/// ([`vectorcraft_doc::Document::art_moving_with`]); a copy takes it. pub(crate) fn artboard_art(s: &Session, i: usize, art: bool, all: bool, moving: bool) -> Result> { let d = &s.doc()?.doc; - let rect = d.artboards.get(i).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?; + if i >= d.artboards.len() { + return Err(EngineError::Other("no such artboard".into())); + } Ok(match (art, moving) { (false, _) => vec![], - (true, false) => d.art_on_artboard(rect, all), + (true, false) => d.art_for_artboard_copy(i, all), (true, true) => d.art_moving_with(i, all), }) } diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index ce90a79649..a14b89fd25 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -177,6 +177,13 @@ fn opened_document_art( super::super::links::resolve(&mut l.doc, super::super::links::LinkBase::file(path), false, false); } l.doc.drop_edit_modes(); + // The native file does not store type's layout bounds. Measure them before cropping or + // copying the art, so the placed group keeps the positions of aligned point type. + for warning in crate::Session::refresh_text_bounds(&mut l.doc) { + if !l.warnings.contains(&warning) { + l.warnings.push(warning); + } + } let n = l.doc.artboards.len(); let board = (page as usize).checked_sub(1).and_then(|i| l.doc.artboards.get(i)).map(|a| a.rect); let artboards = if n == 1 { "artboard" } else { "artboards" }; 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/doc_state.rs b/crates/engine/src/doc_state.rs index 9c80d284ca..9a17cb9c56 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -74,6 +74,9 @@ pub struct DocState { /// pasted bitmap) is dropped when this has changed by the time it finishes; edits do not /// change it, and a batch that fails puts it back with the document. pub reverts: u64, + /// Advances when Undo or Redo restores an older document snapshot. The same node ID can name different objects + /// across that boundary. + pub history_restores: u64, /// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared, /// the UI opens it in a floating window of its own. pub opened_as_tab: bool, @@ -419,6 +422,7 @@ impl DocState { recalled_selection: RecalledSelection::default(), uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), reverts: 0, + history_restores: 0, opened_as_tab: true, mask_view: None, spelling_ignored: Default::default(), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b1a7d37277..722192a185 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,7 +30,7 @@ pub use cmd::clipboard::{Clipboard, SourceLayer}; pub use cmd::create::constrain_click; pub use cmd::distortcmds::{perspective_click, width_point_pair}; pub use cmd::flare::flare_settings; -pub use cmd::gradient::StopOwner; +pub use cmd::gradient::{GradientEditPaints, StopOwner}; pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject}; pub use cmd::params::{check_keys, check_params}; pub use cmd::pathops::auto_simplify_level; diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 9d4c90aed4..a457b4374a 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1684,8 +1684,12 @@ fn millis(t: Option) -> Data { /// One host function of `__vcFiles`, counted and charged as a host call of the run `link` holds. fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> HostItem { + HostItem::Function(call_function(link, f)) +} + +fn call_function(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> vectorcraft_js::HostFunction { let l = link.clone(); - HostItem::Function(Rc::new(move |a| { + Rc::new(move |a| { let h = super::current(&l)?; bump(&h.counts.file_calls); let r = f(&h, &a); @@ -1693,7 +1697,7 @@ fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> let r = r?; h.charge_call(super::data_size(&r).saturating_add(a.iter().map(super::data_size).sum()))?; Ok(r) - })) + }) } /// `Ok(true)`, or `{error}` for a failure. @@ -1875,6 +1879,228 @@ fn copy(host: &Host, a: &[Data]) -> Result { Ok(done(r.map_err(|_| WRITE_FAILED))) } +/// Is `path` an XMP sidecar file, by its `.xmp` extension in any case? +fn is_sidecar(path: &str) -> bool { + Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("xmp")) +} + +/// The text of a sidecar's bytes and its character form as `XMPFile.getPacketInfo` gives it: 0 for +/// UTF-8, 2 for UTF-16 big-endian and 3 for UTF-16 little-endian, by its byte order mark. +fn sidecar_text(bytes: &[u8]) -> Option<(String, u32)> { + let utf16 = |rest: &[u8], big: bool| { + let units = rest.as_chunks::<2>().0.iter().map(|&pair| if big { u16::from_be_bytes(pair) } else { u16::from_le_bytes(pair) }); + rest.len().is_multiple_of(2).then(|| char::decode_utf16(units).collect::>().ok()).flatten() + }; + match bytes { + [0xEF, 0xBB, 0xBF, rest @ ..] => std::str::from_utf8(rest).ok().map(|t| (t.to_string(), 0)), + [0xFE, 0xFF, rest @ ..] => utf16(rest, true).map(|t| (t, 2)), + [0xFF, 0xFE, rest @ ..] => utf16(rest, false).map(|t| (t, 3)), + _ => std::str::from_utf8(bytes).ok().map(|t| (t.to_string(), 0)), + } +} + +/// `xmpOpen(path, update, scan)`: the XMP packet of the file at `path` for `XMPFile`, read under +/// the rules for reading; with `update`, a file that can take a packet must also be one the run may write. A `.xmp` file +/// is read whole as its packet unless `scan`; any other file is scanned for its first UTF-8 packet. +/// → `{packet, offset, length, writeable, sidecar, charForm}`, with `packet` null when the file has +/// none. +fn xmp_open(host: &Host, a: &[Data]) -> Result { + let path = arg_text(a, 0); + let (update, scan) = (matches!(a.get(1), Some(Data::Bool(true))), matches!(a.get(2), Some(Data::Bool(true)))); + let mut disk = host.disk.borrow_mut(); + match disk.stat(&path) { + Ok(Some(e)) if !e.file => return Ok(error(NOT_REGULAR)), + Ok(Some(e)) if e.len > MAX_FILE_BYTES as u64 => return Ok(error(TOO_LARGE)), + Ok(Some(_)) => {} + Ok(None) => return Ok(error(NOT_FOUND)), + Err(m) => return Ok(error(m)), + } + let (real, bytes) = match disk.scope.read(Path::new(&path), MAX_FILE_BYTES) { + Ok(read) => read, + Err(ScriptRead::TooLarge) => return Ok(error(TOO_LARGE)), + Err(ScriptRead::Missing) => return Ok(error(NOT_FOUND)), + Err(ScriptRead::Refused) => return Ok(error(ACCESS_DENIED)), + Err(ScriptRead::Failed(_)) => return Ok(error(READ_FAILED)), + }; + disk.charge_read(&real, bytes.len())?; + let sidecar = is_sidecar(&path) && is_sidecar(&real.to_string_lossy()) && !scan; + // Only a file that can take a packet needs to be one the run may write. + if update + && sidecar + && let Err(m) = disk.target(&path, true) + { + return Ok(error(m)); + } + let number = |n: usize| Data::Number(n as f64); + let (packet, offset, length, writeable, char_form) = if sidecar { + let Some((text, form)) = sidecar_text(&bytes) else { return Ok(error(UNDECODABLE)) }; + (Data::String(text), 0, bytes.len(), true, form) + } else { + match vectorcraft_js::find_xmp_packet(&bytes) { + Some(span) => match bytes.get(span.start..span.end).map(std::str::from_utf8) { + Some(Ok(text)) => (Data::String(text.to_string()), span.start, span.end - span.start, span.writeable, 0), + _ => return Ok(error(UNDECODABLE)), + }, + None => (Data::Null, 0, 0, false, 0), + } + }; + Ok(Data::Object(vec![ + ("packet".into(), packet), + ("offset".into(), number(offset)), + ("length".into(), number(length)), + ("writeable".into(), Data::Bool(writeable)), + ("sidecar".into(), Data::Bool(sidecar)), + ("charForm".into(), Data::Number(f64::from(char_form))), + ])) +} + +fn xmp_utf8_packet(text: &str) -> Result, &'static str> { + let body = text.strip_prefix('\u{feff}').unwrap_or(text); + if body.starts_with(" Ok(body.as_bytes()[events.span().start..].to_vec()), + _ => Err(UNDECODABLE), + } + } else { + Ok(text.as_bytes().to_vec()) + } +} + +/// `xmpWrite(path, packet, safely)`: the `.xmp` file at `path` replaced by `packet` in UTF-8, under +/// the rules for writing. The packet goes to a temporary file in the same folder that then takes the +/// file's name, when the run may write there; otherwise to the file itself, unless `safely`, which +/// fails and leaves the file as it is. Open objects of the file hold the new bytes. +/// The writer omits a leading XML declaration. +/// On Unix, the destination folder is flushed after writing. A folder flush failure returns an +/// error after the written path is recorded and open readers receive the replacement packet. +fn xmp_write(host: &Host, a: &[Data]) -> Result { + let path = arg_text(a, 0); + let packet = match xmp_utf8_packet(&arg_text(a, 1)) { + Ok(packet) => packet, + Err(message) => return Ok(error(message)), + }; + let safely = matches!(a.get(2), Some(Data::Bool(true))); + if !is_sidecar(&path) { + return Ok(error(ACCESS_DENIED)); + } + if packet.len() > MAX_FILE_BYTES { + return Ok(error(TOO_LARGE)); + } + let mut disk = host.disk.borrow_mut(); + let target = match disk.target(&path, true) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + // A `.xmp` link that leads to another kind of file does not make that file a sidecar. + if !is_sidecar(&target.to_string_lossy()) { + return Ok(error(ACCESS_DENIED)); + } + if std::fs::metadata(&target).is_ok_and(|m| !m.is_file()) { + return Ok(error(NOT_REGULAR)); + } + // An open object of the file with changes not yet written keeps them: the packet is not written + // over them. + if disk.open.values().any(|o| o.dirty && o.holds(&target)) { + return Ok(error(WRITE_FAILED)); + } + let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let temp_name = |n: u32| target.with_file_name(format!(".{name}.{}.{n}.tmp", std::process::id())); + let first = temp_name(0); + let temp_allowed = disk.target(&first.to_string_lossy(), false).is_ok_and(|t| t == first); + // A safe update writes only through a temporary file. + if safely && !temp_allowed { + return Ok(error(WRITE_FAILED)); + } + let holders = disk.open.values().filter(|o| o.holds(&target)).count(); + disk.charge_write(packet.len().saturating_mul(holders.saturating_add(1)))?; + // `changed` is whether the file's bytes may differ from before: after a replacement, or once a + // direct write has opened (and so emptied) the file. + let (r, changed) = if temp_allowed { + // The temporary file takes a name no file or link has, so only the sidecar is replaced; when + // none of the names is free the sidecar is left as it is. + // Each name is checked against the places the run may write before it is made. + let allowed = |t: &Path| disk.target(&t.to_string_lossy(), false).is_ok_and(|r| r == t); + let new_file = |t: &Path| { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + // On Unix the file starts readable and writable by its owner alone, until the packet is in + // it and the sidecar's permission bits are copied to it. + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + allowed(t).then(|| options.open(t).ok()).flatten() + }; + let Some((temp, mut out)) = (0..16).map(temp_name).find_map(|t| new_file(&t).map(|f| (t, f))) else { + return Ok(error(WRITE_FAILED)); + }; + let mut write_temp = || { + #[cfg(test)] + if XMP_WRITE_FAILS.with(std::cell::Cell::get) { + return Err(std::io::Error::other("write failed")); + } + #[cfg(all(test, unix))] + { + let mode = std::os::unix::fs::PermissionsExt::mode(&out.metadata()?.permissions()); + XMP_TEMP_MODE.with(|m| m.set(Some(mode))); + } + std::io::Write::write_all(&mut out, &packet)?; + // The packet is on the disk before it takes the sidecar's name, as a saved document's is. + #[cfg(not(target_arch = "wasm32"))] + vectorcraft_format::sync_file(&out)?; + Ok(()) + }; + let r = write_temp(); + drop(out); + // The replacement keeps the sidecar's permission bits, group and (Linux) access ACL, or is + // readable by its owner alone, as a saved document is (`vectorcraft_format::keep_permissions`). + // On Windows the only permission is the read-only attribute, and a read-only temporary file + // could not be removed after a failed rename. The web build has no such files. Keeping them + // is best effort, as for a saved document: a volume without Unix permissions (SMB, FAT) refuses them, and the + // update still goes through. + #[cfg(not(target_arch = "wasm32"))] + if r.is_ok() { + let _ = vectorcraft_format::keep_permissions(&target, &temp); + } + let r = r.and_then(|()| std::fs::rename(&temp, &target)).inspect_err(|_| { + let _ = std::fs::remove_file(&temp); + }); + let changed = r.is_ok(); + (r, changed) + } else { + match std::fs::File::create(&target) { + Ok(mut f) => (std::io::Write::write_all(&mut f, &packet), true), + Err(e) => (Err(e), false), + } + }; + if changed { + disk.wrote(&target); + } + if r.is_ok() { + for file in disk.open.values_mut().filter(|o| o.holds(&target)) { + let reset = file.bytes.starts_with(&[0xEF, 0xBB, 0xBF]) || matches!(file.encoding, Encoding::Utf16Le | Encoding::Utf16Be); + file.bytes.clone_from(&packet); + // `File` readers with a UTF-8 byte order mark or UTF-16 encoding restart in UTF-8. + if reset { + file.encoding = Encoding::Utf8; + file.name = Encoding::Utf8.name().to_string(); + file.pos = 0; + } + file.pos = file.pos.min(packet.len()); + file.dirty = false; + } + } + #[cfg(all(unix, not(target_arch = "wasm32")))] + let r = r.and_then(|()| { + #[cfg(test)] + if XMP_DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) { + return Err(std::io::Error::other("directory flush failed")); + } + vectorcraft_format::sync_parent(&target) + }); + Ok(done(r.map_err(|_| WRITE_FAILED))) +} + /// `remove(path)`: the file, or the folder when it is empty; a link itself, never what it leads to. fn remove(host: &Host, a: &[Data]) -> Result { let mut disk = host.disk.borrow_mut(); @@ -2480,8 +2706,20 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr ("setHidden".into(), call(link, set_hidden)), ("createAlias".into(), call(link, create_alias)), ("pick".into(), call(link, pick)), + ("xmpOpen".into(), call(link, xmp_open)), + ( + "xmpWrite".into(), + HostItem::FunctionWithLimits { + limits: vectorcraft_js::DataLimits { + bytes: 3 * vectorcraft_js::XMP_MAX_BYTES + (128 << 10), + ..vectorcraft_js::DataLimits::default() + }, + function: call_function(link, xmp_write), + }, + ), ]; - realm.define_file_classes(items) + realm.define_file_classes(items)?; + realm.define_external_object() } /// Tests: what the next `copy` does with its source's path, as given and as its real path, after @@ -2501,6 +2739,13 @@ thread_local! { pub(crate) static BEFORE_ALIAS_LINK: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; /// Tests: while set, the bytes `flush` writes fail after the file was opened for them. pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: while set, `xmpWrite` fails after its checks and before it writes. + pub(crate) static XMP_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; + #[cfg(unix)] + pub(crate) static XMP_DIRECTORY_SYNC_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: the permission bits of the last temporary file `xmpWrite` made, before it wrote to it. + #[cfg(unix)] + pub(crate) static XMP_TEMP_MODE: std::cell::Cell> = const { std::cell::Cell::new(None) }; } #[cfg(test)] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c87b51fddd..f0c8393339 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -184,6 +184,7 @@ mod script_include; mod script_io; mod script_run; mod script_tags; +mod script_xmp; mod scripts; mod segment_nudge; mod select_effects; diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 3e64f1557d..c5a480323b 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -1165,3 +1165,174 @@ fn gamut_check_refuses_colors_that_are_not_a_list() { assert_eq!(r, s.execute("color.gamutCheck", &json!({})).unwrap()); assert!(r["outOfGamut"].as_array().unwrap().iter().any(|v| v["hex"] == "#0000ff"), "{r}"); } + +fn mode_index_swatch(name: &str, paint: Paint, global: bool) -> vectorcraft_color::Swatch { + vectorcraft_color::Swatch { name: name.into(), paint, global, spot: false } +} + +fn mode_index_link(color: Color, name: &str, tint: f32) -> Paint { + Paint::Solid { color, swatch: Some(name.into()), tint } +} + +fn mode_index_gradient() -> Paint { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![GradientStop::new(0.0, Color::rgb(0.1, 0.2, 0.3)), GradientStop::new(1.0, Color::rgb(0.8, 0.7, 0.6))], + )))) +} + +/// A later global cannot replace the first exact-name record, even when that first record +/// cannot supply a global base. These legacy palettes exercise the public conversion command. +#[test] +fn document_mode_index_keeps_ineligible_first_name_shadowing() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let stored = Color::rgb(0.123_457, 0.456_789, 0.789_123); + let shadows = [ + (Paint::solid(Color::rgb(0.8, 0.1, 0.2)), false), + (mode_index_link(Color::rgb(0.6, 0.3, 0.4), "Underlying", 0.5), true), + (mode_index_gradient(), true), + ]; + for grouped in [false, true] { + for (paint, global) in &shadows { + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!(stored)); + s.edit("legacy duplicate palette", |d, _| { + let first = mode_index_swatch("Shadow", paint.clone(), *global); + let later = mode_index_swatch("Shadow", Paint::solid(Color::rgb(0.1, 0.8, 0.2)), true); + d.swatches = vec![mode_index_swatch("Underlying", Paint::solid(Color::rgb(0.2, 0.4, 0.6)), true)].into(); + d.swatch_groups.clear(); + if grouped { + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "First".into(), swatches: vec![first] }); + } else { + d.swatches.push(first); + } + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Later".into(), swatches: vec![later] }); + d.node_mut(id).unwrap().appearance.set_fill(mode_index_link(stored, "Shadow", 0.25)); + Ok(()) + }) + .unwrap(); + assert_eq!(s.doc().unwrap().doc.global_color("Shadow"), None); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + assert_eq!(fill_of(&s, id), mode_index_link(to_cmyk(stored), "Shadow", 0.25), "grouped={grouped}, first={paint:?}"); + } + } +} + +/// A first eligible record wins over later groups, and its converted base supplies art, +/// gradient-stop and tint-swatch colors. Undo/Redo retain the complete duplicate palette. +#[test] +fn document_mode_index_uses_the_first_global_base_across_groups() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let base = Color::rgb(0.271_937, 0.314_773, 0.583_119); + let other = Color::rgb(0.812_345, 0.234_567, 0.456_789); + for grouped in [false, true] { + let mut s = session(); + let filled = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!(base)); + let gradient = rect(&mut s, 20.0, 0.0, 10.0, 10.0, json!(other)); + s.edit("legacy grouped palette", |d, _| { + let first = mode_index_swatch("Shared", Paint::solid(base), true); + let later = mode_index_swatch("Shared", Paint::solid(other), true); + d.swatches = vec![mode_index_swatch("Shared tint", mode_index_link(base.tinted(0.3), "Shared", 0.3), false)].into(); + d.swatch_groups.clear(); + if grouped { + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "First".into(), swatches: vec![first] }); + } else { + d.swatches.push(first); + } + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Later".into(), swatches: vec![later] }); + d.node_mut(filled).unwrap().appearance.set_fill(mode_index_link(base.tinted(0.25), "Shared", 0.25)); + let stop = GradientStop { swatch: Some("Shared".into()), tint: 0.6, ..GradientStop::new(0.0, base.tinted(0.6)) }; + d.node_mut(gradient).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![stop, GradientStop::new(1.0, other)], + ))))); + Ok(()) + }) + .unwrap(); + let before = s.doc().unwrap().doc.clone(); + let history = s.doc().unwrap().history.undo.len(); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let converted = to_cmyk(base); + assert_eq!(fill_of(&s, filled), mode_index_link(converted.tinted(0.25), "Shared", 0.25)); + assert_eq!(s.doc().unwrap().doc.swatch("Shared").unwrap().paint.color(), Some(converted)); + assert_eq!(s.doc().unwrap().doc.swatch("Shared tint").unwrap().paint, mode_index_link(converted.tinted(0.3), "Shared", 0.3)); + let Paint::Gradient(paint) = fill_of(&s, gradient) else { panic!("gradient lost") }; + assert_eq!( + (paint.gradient.stops[0].color, paint.gradient.stops[0].swatch.as_deref(), paint.gradient.stops[0].tint), + (converted.tinted(0.6), Some("Shared"), 0.6) + ); + assert_eq!(paint.gradient.stops[1].color, to_cmyk(other)); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + let after = s.doc().unwrap().doc.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *after); + } +} + +/// Grouped Lab spots keep their definitions; both Spot Colors choices supply their own linked +/// base to document art, tint swatches and the new-art fill when the document mode changes. +#[test] +fn document_mode_index_keeps_grouped_lab_spot_options_and_new_art() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let lab = Color::Lab { l: 61.5, a: 42.25, b: -17.75 }; + for use_lab in [false, true] { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Indexed Lab", "color": lab, "spot": true})).unwrap(); + s.execute("swatch.new", &json!({"swatch": "Indexed Lab", "tint": 70})).unwrap(); + s.edit("group the spot", |d, _| { + let ink = d.remove_swatch("Indexed Lab").unwrap(); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Spot group".into(), swatches: vec![ink] }); + Ok(()) + }) + .unwrap(); + s.execute("swatch.spotOptions", &json!({"useLab": use_lab})).unwrap(); + let id = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!("#000000")); + s.execute("paint.setFill", &json!({"ids": [id.0], "swatch": "Indexed Lab", "tint": 40})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let old_paint = s.paint.clone(); + let base = if use_lab { lab } else { to_cmyk(lab) }; + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let ink = s.doc().unwrap().doc.swatch("Indexed Lab").unwrap(); + assert!(ink.global && ink.spot); + assert_eq!(ink.paint, Paint::solid(lab)); + let expected = mode_index_link(base.tinted(0.4), "Indexed Lab", 0.4); + assert_eq!(fill_of(&s, id), expected); + assert_eq!(s.paint.fill, expected, "new art follows the same spot choice"); + assert_eq!(s.doc().unwrap().doc.swatch("Indexed Lab 70%").unwrap().paint, mode_index_link(base.tinted(0.7), "Indexed Lab", 0.7)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before); + assert_eq!(s.paint, old_paint); + } +} + +/// The implicit Registration lookup is not a stored palette record. Only an explicit global +/// record supplies its tint base here; an unresolved link keeps conversion of its stored color. +#[test] +fn document_mode_index_keeps_registration_and_missing_link_fallbacks() { + use vectorcraft_color::swatch::{REGISTRATION, registration}; + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let stored = Color::rgb(0.321_987, 0.654_321, 0.876_543); + for explicit in [false, true] { + let mut s = session(); + let mark = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!(stored)); + let missing = rect(&mut s, 20.0, 0.0, 10.0, 10.0, json!(stored)); + s.edit("legacy registration and missing link", |d, _| { + d.swatches = (if explicit { vec![registration().clone()] } else { vec![] }).into(); + d.swatch_groups.clear(); + d.node_mut(mark).unwrap().appearance.set_fill(mode_index_link(stored, REGISTRATION, 0.25)); + d.node_mut(missing).unwrap().appearance.set_fill(mode_index_link(stored, "Missing", 0.5)); + Ok(()) + }) + .unwrap(); + assert!(s.doc().unwrap().doc.swatch(REGISTRATION).is_some(), "the implicit lookup exists in both fixtures"); + assert_eq!(s.doc().unwrap().doc.swatches_iter().count(), usize::from(explicit)); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let color = if explicit { Color::cmyk(1.0, 1.0, 1.0, 1.0).tinted(0.25) } else { to_cmyk(stored) }; + assert_eq!(fill_of(&s, mark), mode_index_link(color, REGISTRATION, 0.25)); + assert_eq!(fill_of(&s, missing), mode_index_link(to_cmyk(stored), "Missing", 0.5)); + } +} diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 0e4bdf0ab9..397c9252b5 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -475,6 +475,38 @@ fn duplicate_artboard_copies_its_art() { assert_eq!(ids(&s.execute("artboard.duplicate", &json!({"index": 0, "art": true})).unwrap()["ids"]).len(), 1); } +#[test] +fn duplicate_artboard_and_alt_drag_copy_artwork_larger_than_artboard() { + let mut s = session(); + // Default artboard is 800x600 at (0, 0). + // An oversized background (900x700 centered at (400, 300), hanging 50pt off all 4 edges, #4479). + let bg = s.execute("shape.rectangle", &json!({"x": -50, "y": -50, "width": 900, "height": 700})).unwrap(); + let bg_id = bg["id"].as_u64().unwrap(); + // An oversized banner across the artboard with overhang (900x100 at x: -50, y: 100). + let banner = s.execute("shape.rectangle", &json!({"x": -50, "y": 100, "width": 900, "height": 100})).unwrap(); + let banner_id = banner["id"].as_u64().unwrap(); + + // 1. Menu duplication (artboard.duplicate with art: true). + let dup = s.execute("artboard.duplicate", &json!({"index": 0, "art": true})).unwrap(); + let dup_copies = ids(&dup["ids"]); + assert_eq!(dup_copies.len(), 2, "copies both oversized background and banner artwork: {dup_copies:?}"); + assert!(!dup_copies.contains(&bg_id) && !dup_copies.contains(&banner_id)); + s.execute("edit.undo", &json!({})).unwrap(); + + // 2. Alt-drag with Artboard tool (artboard.move with copy: true and moveArt: true). + let alt_drag = s.execute("artboard.move", &json!({"index": 0, "dx": 1000, "dy": 0, "copy": true, "moveArt": true})).unwrap(); + let alt_copies = ids(&alt_drag["moved"]); + assert_eq!(alt_copies.len(), 2, "Alt-drag copies both oversized background and banner artwork: {alt_copies:?}"); + assert!(!alt_copies.contains(&bg_id) && !alt_copies.contains(&banner_id)); + s.execute("edit.undo", &json!({})).unwrap(); + + // 3. Move artboard with Artboard tool / command (artboard.move with moveArt: true). + // Under strict containment (#890 / #1295), overhanging art stays behind during plain move. + let moved = s.execute("artboard.move", &json!({"index": 0, "dx": 200, "dy": 100, "moveArt": true})).unwrap(); + let moved_ids = ids(&moved["moved"]); + assert_eq!(moved_ids.len(), 0, "move leaves overhanging artwork behind: {moved_ids:?}"); +} + /// New Artboard and Artboard Options trim the name they are given, as the Artboards panel's rename /// does, and a blank name gives the artboard its default name, Artboard N for the Nth artboard. #[test] diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index 38636102e2..7086c7f92e 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -657,6 +657,28 @@ fn pdf_pages_and_native_artboards_place_as_clipped_groups() { } } +/// Place and Set Bounds use the layout of native point type, including its alignment. +#[test] +fn bounding_native_placement_measures_aligned_point_type() { + for (justify, x) in [("center", 190), ("right", 275)] { + let mut src = session(); + let square = src.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 180, "height": 180})).unwrap()["id"].clone(); + src.execute("paint.setStroke", &json!({"id": square, "none": true})).unwrap(); + src.execute("text.create", &json!({"text": "Sample test", "x": x, "y": 150, "size": 18, "justify": justify})).unwrap(); + let shown = vectorcraft_render::encode::art_bounds(&src.doc().unwrap().doc).unwrap(); + let width = node(&src, &square).geometric_bounds().unwrap().width(); + assert!(close(shown.width(), width), "the {justify}-aligned text starts inside the square"); + let native = serialize(&mut src, "vectorcraft"); + + let mut placed = session(); + let r = place(&mut placed, "aligned.vectorcraft", &native, json!({"crop": "bounding", "link": false})); + assert!(close(r["width"].as_f64().unwrap(), width), "{justify}: {r}"); + placed.execute("object.setBounds", &json!({"width": width, "proportional": true})).unwrap(); + let after = vectorcraft_render::encode::art_bounds(&placed.doc().unwrap().doc).unwrap(); + assert!(close(after.width(), shown.width()), "{justify}: {shown:?} became {after:?}"); + } +} + /// With crop "bounding", the art's box is the box of what shows, as an export measures it: a hidden /// member of a group does not count, and is still placed, hidden. #[test] diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs new file mode 100644 index 0000000000..3a4f8952f4 --- /dev/null +++ b/crates/engine/src/tests/script_xmp.rs @@ -0,0 +1,815 @@ +//! `XMPFile` in a script: reading and writing a sidecar packet through the script's file places, +//! scanning another file for its packet, and the paths and packets it refuses. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +const LOAD: &str = "new ExternalObject('lib:AdobeXMPScript');\n"; + +const PACKET: &str = "\ +\ +\ +image/svg+xmlab\ +"; + +#[test] +fn a_large_supported_packet_crosses_the_sidecar_write_transport() { + let base = folder("large-write-transport"); + let payload = "x".repeat(6 << 20); + let packet = PACKET.replace("image/svg+xml", &payload); + let mut session = with_data(&base); + let setup = logged(&mut session, &base, "vc.log(Folder.userData.fsName + '/large.xmp');"); + let path = PathBuf::from(setup[0].as_str().unwrap()); + write(&path, packet.as_bytes()); + let log = logged( + &mut session, + &base, + "var p = Folder.userData.fsName + '/large.xmp'; var x = new XMPFile(p, XMPConst.FILE_XML, XMPConst.OPEN_FOR_UPDATE); var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'title', 'changed-for-write'); x.putXMP(m); x.closeFile(); vc.log(true);", + ); + assert_eq!(log, json!([true])); + let written = std::fs::read_to_string(path).unwrap(); + assert!(written.contains(&payload)); + assert!(written.contains("changed-for-write")); +} + +struct Folder { + _guard: vectorcraft_testkit::TempDir, + path: PathBuf, +} + +impl std::ops::Deref for Folder { + type Target = PathBuf; + + fn deref(&self) -> &Self::Target { + &self.path + } +} + +impl AsRef for Folder { + fn as_ref(&self) -> &Path { + &self.path + } +} + +/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real path. +fn folder(name: &str) -> Folder { + let guard = vectorcraft_testkit::TempDir::new(&format!("script-xmp-{name}")); + let base = std::fs::canonicalize(&*guard).unwrap(); + std::fs::create_dir_all(base.join("main")).unwrap(); + Folder { _guard: guard, path: base } +} + +fn write(path: &Path, bytes: &[u8]) { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(path, bytes).unwrap(); +} + +/// A session whose scripts keep their data folders in `base/settings/Script Data`. +fn with_data(base: &Path) -> Session { + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s +} + +/// Runs `main/main.jsx` in `base` with the XMP library loaded and the text `text` in `s`. +fn run_in(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + write(&main, format!("{LOAD}{text}").as_bytes()); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +/// The values the run of `text` logged. +fn logged(s: &mut Session, base: &Path, text: &str) -> Value { + match run_in(s, base, text) { + Ok(r) => r["log"].clone(), + Err(e) => panic!("{text}\n{e}"), + } +} + +/// A sidecar in the script's data folder reads, takes a changed packet and holds it after +/// `closeFile`; a new `XMPFile` reads it back. +#[test] +fn a_sidecar_packet_reads_and_writes() { + let base = folder("sidecar"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!( + "var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.encoding = 'UTF-8'; f.open('w'); f.write({PACKET:?}); f.close();\n\ + var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); var info = x.getFileInfo();\n\ + var out = [m.getProperty(XMPConst.NS_DC, 'format').value, m.countArrayItems(XMPConst.NS_DC, 'subject'), info.format == XMPConst.FILE_XML, x.canPutXMP(m)];\n\ + m.setProperty(XMPConst.NS_DC, 'format', 'text/plain'); m.appendArrayItem(XMPConst.NS_DC, 'subject', 'c');\n\ + x.putXMP(m); x.closeFile();\n\ + var y = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); var n = y.getXMP();\n\ + out.push(n.getProperty(XMPConst.NS_DC, 'format').value, n.getArrayItem(XMPConst.NS_DC, 'subject', 3).value, y.getPacketInfo().offset, y.canPutXMP(n));\n\ + y.closeFile(); vc.log(out); vc.log(p);" + ), + ); + assert_eq!(log[0], json!(["image/svg+xml", 2, true, true, "text/plain", "c", 0, false])); + let path = PathBuf::from(log[1].as_str().unwrap()); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("text/plain"), "{text}"); + let leftovers: Vec<_> = std::fs::read_dir(path.parent().unwrap()).unwrap().filter_map(|e| e.ok()).map(|e| e.file_name()).collect(); + assert_eq!(leftovers.len(), 1, "no temporary file stays: {leftovers:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A file that is not a sidecar is scanned for its packet, read only, and a file with none gives +/// `null`. +#[test] +fn another_file_is_scanned_for_its_packet() { + let base = folder("scan"); + let mut bytes = b"\x89binary\x00head".to_vec(); + bytes.extend_from_slice(PACKET.as_bytes()); + bytes.extend_from_slice(b"\x00tail"); + write(&base.join("main/art.bin"), &bytes); + write(&base.join("main/none.bin"), b"no packet here"); + let mut s = Session::new(); + let log = logged( + &mut s, + &base, + "var x = new XMPFile(File('art.bin').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); var i = x.getPacketInfo();\n\ + var out = [x.getXMP().getProperty(XMPConst.NS_DC, 'format').value, i.offset, i.length, i.writeable, x.canPutXMP(x.getXMP())];\n\ + try { x.putXMP(x.getXMP()); out.push('put'); } catch (e) { out.push(e.message); }\n\ + out.push(new XMPFile(File('none.bin').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ).getXMP());\n\ + x.closeFile(); try { x.getXMP(); } catch (e) { out.push(e.message); } vc.log(out);", + ); + assert_eq!( + log[0], + json!([ + "image/svg+xml", + 12, + PACKET.len(), + true, + false, + "XMPFile.putXMP: the file cannot be updated", + null, + "XMPFile.getXMP: the file is closed" + ]) + ); + let _ = std::fs::remove_dir_all(base); +} + +/// `getPacketInfo().padSize` gives the bytes of whitespace before the packet's trailer: twice the +/// characters in a UTF-16 packet, and 0 in a packet with none. +#[test] +fn packet_info_gives_the_padding() { + let base = folder("pad"); + let padded = PACKET.replace("');\n\ + function text() {{ var g = new File(p); g.open('r'); var t = g.read(); g.close(); return t; }}\n\ + var out = []; try {{ x.closeFile(); }} catch (e) {{ out.push(e.message); }} f.close(); out.push(text().indexOf('kept') > 0);\n\ + x.closeFile(); out.push(text().indexOf('changed') > 0); vc.log(out);" + ), + ); + assert_eq!(log[0], json!(["Script file could not be written", true, true]), "the File's changes are written, then the packet"); + let _ = std::fs::remove_dir_all(base); +} + +/// A file with the name of the temporary file is left alone: the packet goes through another name +/// and replaces only the sidecar. +#[test] +fn a_file_in_the_temporary_name_is_left_alone() { + let base = folder("taken"); + let mut s = with_data(&base); + let path = logged( + &mut s, + &base, + &format!("var f = new File(Folder.userData.fsName + '/t.xmp'); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(f.fsName);"), + ); + let path = PathBuf::from(path[0].as_str().unwrap()); + let taken = path.with_file_name(format!(".t.xmp.{}.0.tmp", std::process::id())); + write(&taken, b"someone else's"); + let log = logged( + &mut s, + &base, + "var x = new XMPFile(Folder.userData.fsName + '/t.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile(); vc.log('closed');", + ); + assert_eq!(log, json!(["closed"])); + assert_eq!(std::fs::read(&taken).unwrap(), b"someone else's"); + assert!(std::fs::read_to_string(&path).unwrap().contains("changed")); + let names: Vec = + std::fs::read_dir(path.parent().unwrap()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names.iter().filter(|n| n.ends_with(".tmp")).count(), 1, "no temporary file is left behind: {names:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// Pumps the run until it waits for a file dialog (`None`) or ends. +fn pump_to_picker(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_picker().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +/// Starts `main/main.jsx` in `base` with the XMP library loaded and the text `text`, in the app. +fn start_framed(s: &mut Session, base: &Path, text: &str) { + s.script_frames = true; + let main = base.join("main/main.jsx"); + write(&main, format!("{LOAD}{text}").as_bytes()); + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); +} + +/// With only the sidecar and the first temporary name granted, a taken first name does not make +/// the packet go to another name outside the grants: `closeFile()` throws and no file is made. +#[test] +fn temporary_names_outside_the_grants_are_not_made() { + let base = folder("tempgrant"); + let (sidecar, taken) = (base.join("picked/t.xmp"), base.join(format!("picked/.t.xmp.{}.0.tmp", std::process::id()))); + write(&sidecar, PACKET.as_bytes()); + write(&taken, b"someone else's"); + let mut s = with_data(&base); + start_framed( + &mut s, + &base, + "var a = File.saveDialog('a'), b = File.saveDialog('b');\n\ + var x = new XMPFile(a.fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\ + try { x.closeFile(); vc.log('closed'); } catch (e) { vc.log(e.message); }", + ); + for path in [&sidecar, &taken] { + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![path.to_string_lossy().into_owned()], always: false })); + } + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!(["Script file could not be written"])); + assert_eq!(std::fs::read_to_string(&sidecar).unwrap(), PACKET); + assert_eq!(std::fs::read(&taken).unwrap(), b"someone else's"); + let names: Vec = std::fs::read_dir(base.join("picked")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names.len(), 2, "no other file is made: {names:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A `.xmp` link to another kind of file is scanned and takes no packet, and a link that leads to +/// another kind of file by the time of `closeFile()` is not written through. +#[cfg(unix)] +#[test] +fn a_link_to_another_kind_of_file_is_not_written() { + let base = folder("link"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!( + "var d = Folder.userData.fsName, l = d + '/l.xmp';\n\ + function put(n) {{ var f = new File(d + '/' + n); f.open('w'); f.write({PACKET:?}); f.close(); }}\n\ + function link(n) {{ var f = new File(l); if (f.exists) f.remove(); return !!new File(l).createAlias(d + '/' + n); }}\n\ + put('other.txt'); put('real.xmp'); var out = [link('other.txt')];\n\ + var a = new XMPFile(l, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); out.push(a.canPutXMP(a.getXMP())); a.closeFile();\n\ + out.push(link('real.xmp'));\n\ + var x = new XMPFile(l, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); var m = x.getXMP();\n\ + m.setProperty(XMPConst.NS_DC, 'format', 'changed'); out.push(x.canPutXMP(m)); x.putXMP(m);\n\ + out.push(link('other.txt'));\n\ + try {{ x.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message); }}\n\ + vc.log(out); vc.log(d);" + ), + ); + assert_eq!(log[0], json!([true, false, true, true, true, "Script file access denied"])); + let d = PathBuf::from(log[1].as_str().unwrap()); + assert_eq!(std::fs::read_to_string(d.join("other.txt")).unwrap(), PACKET); + assert_eq!(std::fs::read_to_string(d.join("real.xmp")).unwrap(), PACKET); + let _ = std::fs::remove_dir_all(base); +} + +/// A sidecar replaced through a temporary file keeps its permission bits. +#[cfg(unix)] +#[test] +fn a_replaced_sidecar_keeps_its_permissions() { + use std::os::unix::fs::PermissionsExt; + let base = folder("mode"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"), + ); + let path = PathBuf::from(log[0].as_str().unwrap()); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + logged( + &mut s, + &base, + "var x = new XMPFile(Folder.userData.fsName + '/a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();", + ); + assert!(std::fs::read_to_string(&path).unwrap().contains("changed")); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + let _ = std::fs::remove_dir_all(base); +} + +/// A sidecar in UTF-16 is read by its byte order mark, and one that is not text is refused. +#[test] +fn a_utf16_sidecar_reads_by_its_byte_order_mark() { + let base = folder("utf16"); + let mut le = vec![0xFF, 0xFE]; + le.extend(PACKET.encode_utf16().flat_map(u16::to_le_bytes)); + write(&base.join("main/le.xmp"), &le); + write(&base.join("main/bad.xmp"), &[0xFF, 0xFE, 0x00]); + let mut s = Session::new(); + let log = logged( + &mut s, + &base, + "var x = new XMPFile(File('le.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ);\n\ + var out = [x.getXMP().getProperty(XMPConst.NS_DC, 'format').value, x.getPacketInfo().charForm];\n\ + try { new XMPFile(File('bad.xmp').fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); } catch (e) { out.push(e.message); } vc.log(out);", + ); + assert_eq!(log[0], json!(["image/svg+xml", 3, "Script file cannot be decoded"])); + let _ = std::fs::remove_dir_all(base); +} + +/// A `File` open on a UTF-16 sidecar reads the UTF-8 packet `closeFile()` wrote, from the start. +#[test] +fn an_open_utf16_file_reads_the_written_packet() { + let base = folder("utf16open"); + let mut s = with_data(&base); + let d = logged(&mut s, &base, "vc.log(Folder.userData.fsName);"); + let d = PathBuf::from(d[0].as_str().unwrap()); + let mut le = vec![0xFF, 0xFE]; + le.extend(PACKET.encode_utf16().flat_map(u16::to_le_bytes)); + write(&d.join("u.xmp"), &le); + let log = logged( + &mut s, + &base, + "var p = Folder.userData.fsName + '/u.xmp'; var f = new File(p); f.open('r'); var out = [f.encoding, f.read(5)];\n\ + var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); var m = x.getXMP();\n\ + m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();\n\ + var t = f.read(), e = f.encoding; f.close(); out.push(e, t.slice(0, 9), t.indexOf('changed') > 0); vc.log(out);", + ); + assert_eq!(log[0], json!(["UTF-16LE", "\n{PACKET}\n"); + let packet = format!("{body}"); + let mut bytes = vec![0xFF, 0xFE]; + bytes.extend(packet.encode_utf16().flat_map(u16::to_le_bytes)); + write(&data.join("declared.xmp"), &bytes); + logged( + &mut session, + &base, + "var x = new XMPFile(Folder.userData.fsName + '/declared.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE); var packet = x.getPacketInfo().packet; x.putXMP(packet); x.closeFile();", + ); + let written = std::fs::read_to_string(data.join("declared.xmp")).unwrap(); + assert_eq!(written, body); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn an_xmp_update_resets_bom_readers_and_keeps_unmarked_reader_positions() { + for bom in [true, false] { + let base = folder(if bom { "utf8bomopen" } else { "utf8open" }); + let mut session = with_data(&base); + let data = logged(&mut session, &base, "vc.log(Folder.userData.fsName);"); + let data = PathBuf::from(data[0].as_str().unwrap()); + let mut bytes = if bom { vec![0xEF, 0xBB, 0xBF] } else { Vec::new() }; + bytes.extend_from_slice(PACKET.as_bytes()); + write(&data.join("u.xmp"), &bytes); + let log = logged( + &mut session, + &base, + &format!( + "var p = Folder.userData.fsName + '/u.xmp', f = new File(p); f.open('r');\n\ + if (!{bom}) f.read(3); var before = f.tell();\n\ + var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE), m = x.getXMP();\n\ + m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();\n\ + var after = f.tell(), text = f.read(); f.close(); vc.log([before, after, text.slice(0, 9)]);" + ), + ); + assert_eq!(log[0], if bom { json!([3, 0, " Option { + for entry in std::fs::read_dir(dir).ok()?.filter_map(|e| e.ok()) { + let path = entry.path(); + if path.is_dir() { + if let Some(found) = find_file(&path, name) { + return Some(found); + } + } else if entry.file_name() == name { + return Some(path); + } + } + None +} + +/// A write that fails leaves the sidecar as it was and the `XMPFile` open with its packet, so a +/// later `closeFile` of the same object writes it. +#[test] +fn a_failed_write_keeps_the_packet_for_a_later_close() { + let base = folder("fails"); + let mut s = with_data(&base); + crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(true)); + start_framed( + &mut s, + &base, + &format!( + "var p = Folder.userData.fsName + '/k.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\ + var kept = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = kept.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); kept.putXMP(m);\n\ + var out = []; try {{ kept.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message, kept.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }}\n\ + File.saveDialog('pause'); kept.closeFile(); out.push('closed'); vc.log(out); vc.log(p);" + ), + ); + let paused = pump_to_picker(&mut s); + crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(false)); + assert!(paused.is_none(), "the run waits at the dialog: {paused:?}"); + let path = find_file(&base.join("settings"), "k.xmp").unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), PACKET, "the failed write leaves the file as it was"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"][0], json!(["Script file could not be written", "changed", "closed"])); + assert!(std::fs::read_to_string(&path).unwrap().contains("changed"), "the same XMPFile writes on its next close"); + let _ = std::fs::remove_dir_all(base); +} + +#[cfg(unix)] +#[test] +fn a_directory_flush_failure_keeps_the_written_packet_and_allows_retry() { + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + } + } + let _reset = Reset; + let base = folder("directory-flush"); + let mut session = with_data(&base); + let dir = logged(&mut session, &base, "vc.log(Folder.userData.fsName);"); + let path = PathBuf::from(dir[0].as_str().unwrap()).join("packet.xmp"); + write(&path, format!("\u{FEFF}{PACKET}").as_bytes()); + crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + start_framed( + &mut session, + &base, + &format!( + "Folder.userData; var p = {:?}, reader = new File(p); reader.open('r'); reader.read(7);\n\ + var kept = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var meta = kept.getXMP(); meta.setProperty(XMPConst.NS_DC, 'format', 'changed'); kept.putXMP(meta);\n\ + var out = []; try {{ kept.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message, kept.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }}\n\ + out.push(reader.tell() === 0, reader.read().indexOf('changed') >= 0); reader.close();\n\ + File.saveDialog('pause'); kept.closeFile(); out.push('closed'); vc.log(out);", + path.to_string_lossy() + ), + ); + let paused = pump_to_picker(&mut session); + crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + assert!(paused.is_none(), "the run waits before retrying: {paused:?}"); + assert!(std::fs::read_to_string(&path).unwrap().contains("changed"), "the replacement already wrote the packet"); + assert!(session.script_pick(crate::script::files::PickAnswer::Deny)); + let report = pump_to_picker(&mut session).unwrap().unwrap(); + assert_eq!(report["log"][0], json!(["Script file could not be written", "changed", true, true, "closed"])); + assert_eq!(report["written"], json!([path.to_string_lossy()]), "the written replacement is reported once"); +} + +/// An `XMPFile` from an earlier run of a named engine is closed. +#[test] +fn an_xmp_file_from_an_earlier_run_is_closed() { + let base = folder("earlier"); + let mut s = with_data(&base); + let engine = |text: &str| format!("#targetengine xmp\n{LOAD}{text}"); + let main = base.join("main/main.jsx"); + write(&main, engine(&format!("var f = new File(Folder.userData.fsName + '/k2.xmp'); f.open('w'); f.write({PACKET:?}); f.close();")).as_bytes()); + s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + write( + &main, + engine("$.global.kept = new XMPFile(Folder.userData.fsName + '/k2.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);").as_bytes(), + ); + s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + write(&main, engine("try { kept.getXMP(); vc.log('open'); } catch (e) { vc.log(e.message); }").as_bytes()); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!(["XMPFile.getXMP: the file is closed"]), "an XMPFile from an earlier run is closed"); + let _ = std::fs::remove_dir_all(base); +} + +/// The temporary file a sidecar is replaced through is readable by its owner alone while the +/// packet is written to it, and the sidecar keeps its own permission bits. +#[cfg(unix)] +#[test] +fn a_temporary_file_starts_private() { + use std::os::unix::fs::PermissionsExt; + let base = folder("private"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"), + ); + let path = PathBuf::from(log[0].as_str().unwrap()); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + crate::script::files::XMP_TEMP_MODE.with(|m| m.set(None)); + logged( + &mut s, + &base, + "var x = new XMPFile(Folder.userData.fsName + '/a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();", + ); + assert_eq!(crate::script::files::XMP_TEMP_MODE.with(std::cell::Cell::get).map(|m| m & 0o777), Some(0o600)); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o644); + let _ = std::fs::remove_dir_all(base); +} + +/// A replaced sidecar that had no access ACL takes none from its folder's default ACL, whose named +/// users the sidecar's group bits would let in. (Skipped where `setfacl` or ACLs are missing.) +#[cfg(target_os = "linux")] +#[test] +fn a_replaced_sidecar_takes_no_inherited_acl() { + let base = folder("acl"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!("var p = Folder.userData.fsName + '/a.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close(); vc.log(p);"), + ); + let path = PathBuf::from(log[0].as_str().unwrap()); + let set = std::process::Command::new("setfacl").args(["-d", "-m", "u:nobody:rw"]).arg(path.parent().unwrap()).status(); + if !set.is_ok_and(|s| s.success()) { + let _ = std::fs::remove_dir_all(base); + return; + } + logged( + &mut s, + &base, + "var x = new XMPFile(Folder.userData.fsName + '/a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m); x.closeFile();", + ); + assert!(std::fs::read_to_string(&path).unwrap().contains("changed")); + let acl = std::process::Command::new("getfacl").args(["--omit-header", "--absolute-names"]).arg(&path).output().unwrap(); + let acl = String::from_utf8_lossy(&acl.stdout); + assert!(!acl.contains("nobody"), "the replacement takes no ACL entry the sidecar lacked: {acl}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A packet argument whose conversion closes the `XMPFile` leaves it closed: `canPutXMP` and +/// `putXMP` throw that the file is closed, and nothing is written. +#[test] +fn converting_the_packet_cannot_close_the_file() { + let base = folder("reentrant"); + let mut s = with_data(&base); + let log = logged( + &mut s, + &base, + &format!( + "var p = Folder.userData.fsName + '/r.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\ + function closing(x) {{ var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); var s = m.serialize();\n\ + return {{ toString: function () {{ x.closeFile(); return s; }} }}; }}\n\ + var out = [], a = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + try {{ out.push(a.canPutXMP(closing(a))); }} catch (e) {{ out.push(e.message); }}\n\ + var b = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + try {{ b.putXMP(closing(b)); out.push('put'); }} catch (e) {{ out.push(e.message); }}\n\ + b.closeFile(); vc.log(out); vc.log(p);" + ), + ); + assert_eq!(log[0], json!(["XMPFile.canPutXMP: the file is closed", "XMPFile.putXMP: the file is closed"])); + assert_eq!(std::fs::read_to_string(log[1].as_str().unwrap()).unwrap(), PACKET); + let _ = std::fs::remove_dir_all(base); +} + +/// With `CLOSE_UPDATE_SAFELY`, a sidecar whose folder takes no temporary file is left as it is and +/// the `XMPFile` keeps its packet; a later `closeFile()` without the flag writes the file itself. +#[test] +fn a_safe_close_writes_only_through_a_temporary_file() { + let base = folder("safely"); + let sidecar = base.join("picked/s.xmp"); + write(&sidecar, PACKET.as_bytes()); + let mut s = with_data(&base); + start_framed( + &mut s, + &base, + "var a = File.saveDialog('a');\n\ + var x = new XMPFile(a.fsName, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\ + var m = x.getXMP(); m.setProperty(XMPConst.NS_DC, 'format', 'changed'); x.putXMP(m);\n\ + var out = []; try { x.closeFile(XMPConst.CLOSE_UPDATE_SAFELY); out.push('closed'); } catch (e) { out.push(e.message, x.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }\n\ + File.saveDialog('pause'); x.closeFile(); out.push('written'); vc.log(out);", + ); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![sidecar.to_string_lossy().into_owned()], always: false })); + assert!(pump_to_picker(&mut s).is_none()); + assert_eq!(std::fs::read_to_string(&sidecar).unwrap(), PACKET, "the safe close leaves the file as it was"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["Script file could not be written", "changed", "written"]])); + assert!(std::fs::read_to_string(&sidecar).unwrap().contains("changed")); + let names: Vec = std::fs::read_dir(base.join("picked")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["s.xmp"], "no other file is made"); + let _ = std::fs::remove_dir_all(base); +} 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/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 1c44685198..1bef3c82be 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,6 +37,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"), ("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"), ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), + ("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. @@ -50,6 +51,8 @@ const INSIDE: &[(&str, &str)] = &[ ("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="), ("localize.", "length"), ("toSource.", "length"), + ("ExternalObject.", "length prototype search"), + ("ExternalObject.prototype.", "constructor terminate"), ( "$.", "about appEncoding appEncoding= bp build buildDate colorPicker decimalPoint engineName error fileName flags \ diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 65875c5a52..69a3da38a3 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1014,6 +1014,17 @@ pub(super) fn paints_apart(look: &Node) -> bool { } let mut paths = vec![]; leaves(look, &mut paths); + // A gradient or pattern instance (`Bb … BB`) wraps only the last path of a compound path, the paths before it + // keep the default paint: many paths alike, then one that paints with a gradient, are one compound path's + // subpaths and its paint (see `compound`), not several paints. + if let [rest @ .., last] = paths.as_slice() + && rest.len() >= 2 + && rest.windows(2).all(|w| matches!(w, [a, b] if a.appearance == b.appearance)) + && last.appearance.items.iter().any(|i| matches!(i.paint(), Paint::Gradient(_) | Paint::Pattern { .. })) + && rest.iter().all(|p| p.appearance.items.iter().all(|i| !matches!(i.paint(), Paint::Gradient(_) | Paint::Pattern { .. }))) + { + return false; + } paths.windows(2).any(|w| matches!(w, [a, b] if a.appearance != b.appearance)) } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 1fcf87e7a0..787c0d268c 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -1789,6 +1789,22 @@ fn compound_path_takes_its_last_paths_paint() { } } +#[test] +fn a_compound_path_whose_last_path_has_the_gradient_is_one_gradient_filled_compound_path() { + // GUARDS: a gradient instance wraps only the last path of a compound path (a sunburst's rays), the paths before it + // keep the default fill. Read as a drawn look whose paths paint apart, each ray but the last became a plain black + // path and only the last one took the gradient. + let defs = "%AI5_BeginGradient: (Lin)\n(Lin) 0 2 Bd\n[\n<00FF>\n0\n%_0 0 0 0 1 0 0 2 1 6 50 0 Bs\n%_0 0 0 0 0 0 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let instance = "Bb\n1 (Lin) 0 0 0 1 1 0 0 1 0 0 1 Bg\n10 0 10 10 100 50 Xm\nf\n0 BB\n"; + let rays: String = (0..3).map(|i| format!("0 g\n{}f\n", rect_path(f64::from(i) * 30.0, 0.0, f64::from(i) * 30.0 + 20.0, 20.0))).collect(); + let art_ = format!("0 Ae\n*u\n0 Ae\nu\n{rays}{}{instance}U\n9 () XW\n*U\n", rect_path(100.0, 0.0, 120.0, 20.0)); + let a = art(&read_ok(&format!("{defs}{}", layer(&art_))).doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let NodeKind::Compound { children, .. } = &a[0].kind else { panic!("{:#?}", a[0].kind) }; + assert_eq!(children.len(), 4, "every ray is a subpath of the compound path"); + assert!(matches!(fill(&a[0]), Paint::Gradient(_)), "{:?}", fill(&a[0])); +} + #[test] fn a_group_whose_state_has_no_transparency_takes_the_current_one() { // GUARDS: a group's own state block keeps the last `Xy`, as the PDF part draws it; a drawn look's group stays opaque. diff --git a/crates/eps/src/import/native/compare.rs b/crates/eps/src/import/native/compare.rs index 424ac4079a..a34414a0ac 100644 --- a/crates/eps/src/import/native/compare.rs +++ b/crates/eps/src/import/native/compare.rs @@ -1,5 +1,5 @@ use super::build::Frame; -use super::slots::OUTLINE_REACH; +use super::slots::{OUTLINE_REACH, drawn_box}; use super::{Arc, Document, Node, NodeKind, Rect}; /// `doc` with its layers that don't print hidden, when it has any. @@ -756,12 +756,14 @@ fn differing_pixels( } /// Where the type that shows in `nodes` is, in pixels of `region` drawn at `scale` (with a margin -/// for the strokes round it). The type in a live envelope isn't: the envelope draws it bent, away -/// from its text object's box, and is weighed as the art it draws, as its drawn art would be. +/// for the strokes round it): where it draws ([`drawn_box`]), so that type made from the text +/// document that differs from the page's counts as type whatever its alignment. The type in a +/// live envelope isn't: the envelope draws it bent, away from its text object's box, and is +/// weighed as the art it draws, as its drawn art would be. fn type_areas(nodes: &[Arc], region: Rect, scale: f64, out: &mut Vec) { for n in nodes.iter().filter(|n| n.visible) { if let NodeKind::Text(_) = n.kind - && let Some(b) = n.visual_bounds() + && let Some(b) = drawn_box(n) { let px = |r: Rect| Rect::new((r.x0 - region.x0) * scale, (r.y0 - region.y0) * scale, (r.x1 - region.x0) * scale, (r.y1 - region.y0) * scale); @@ -780,7 +782,7 @@ fn all_type_areas(nodes: &[Arc], region: Rect, scale: f64, out: &mut Vec, ) -> Vec { let [shown, hidden] = pages; - let mut content = made_content(infos, made); + // Every text object that shows has made type: each is matched with the page's type where it draws. + let mut content = made_content(infos, made, true); // The page's type where no made type draws, in the copies that looks draw, is theirs (past // `MAX_PAIRS` comparisons it isn't looked for). let looks = infos.iter().any(|i| i.shown && i.look.is_some()); @@ -315,15 +316,18 @@ fn object_words(o: &[Arc]) -> Vec { } /// Each slot's made type as its content, else nothing yet. Made type that shows has where it draws, -/// or where its story lies when it draws nothing. -fn made_content(infos: &[SlotInfo], made: Vec>) -> Vec { +/// or where its story lies when it draws nothing. `laid`: point type is laid out for its box +/// ([`drawn_box`]); without it the box is that of type without a layout, as it always was. +fn made_content(infos: &[SlotInfo], made: Vec>, laid: bool) -> Vec { infos .iter() .zip(made) .map(|(info, m)| match m { Some((node, region)) => { - let drawn = node.visual_bounds().filter(|b| !b.is_zero_area()).or(region); - Content::Made(node, drawn.filter(|_| info.shown), false) + // Type that doesn't show has no region: it isn't laid out for one. + let own = || if laid { drawn_box(&node) } else { node.visual_bounds() }; + let drawn = info.shown.then(|| own().filter(|b| !b.is_zero_area() && b.is_finite()).or(region)).flatten(); + Content::Made(node, drawn, false) } None => Content::Empty, }) @@ -391,8 +395,11 @@ pub(super) fn plan( // Where the made type that doesn't show lies, by slot. let hidden_at: Vec<(usize, Rect)> = infos.iter().zip(&made).enumerate().filter_map(|(k, (info, m))| Some((k, m.as_ref().filter(|_| !info.shown)?.1?))).collect(); - // Type the text document makes, shown or not: the page's pieces of it aren't needed. - let mut content = made_content(infos, made); + // Type the text document makes, shown or not: the page's pieces of it aren't needed. Its box + // stays that of type without a layout here: with text objects whose type isn't made stacked on + // made type that has their words (the copies of an outlined heading), the page's pieces in the + // box where the made type draws are theirs too, and the made type would take them all. + let mut content = made_content(infos, made, false); // Is `object` the type of a text object that doesn't show, as the page draws it: in its frame, // with its words? (A copied object's lines are where its original's are, so they don't say.) let hidden_type = |object: &[Arc]| { diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index ebd6deef88..5be707fac7 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -610,10 +610,64 @@ pub(super) fn extent(parts: &[Arc]) -> Option { parts.iter().filter_map(|n| n.visual_bounds()).reduce(|a, b| a.union(b)) } +/// Where a text object draws: its visual box, point type that has no layout laid out first, in +/// the fonts the import has ([`vectorcraft_text::FontDb::global`]), so the box depends on which +/// fonts are installed, as the opened document's does. Any point type without a layout is laid +/// out, not only type made from the file's text document, which is the type that has none during +/// the import (the page's own type is measured when it is read). Without a layout the box of point +/// type is an estimate that runs right from its anchor +/// ([`vectorcraft_doc::TextObject::estimate_bounds`]): beside where right-aligned type draws, over +/// one half of centered type, across vertical type, and as wide as an average font would set it, +/// which can be wider than the type is. The node keeps no layout: the document's type is measured +/// when it opens. Any other object's box is its visual box. +/// +/// `made_only` matches made type with the page's type by this box; `plan` doesn't match by it yet. +/// The page comparison's type areas use it for every file's layers, those `plan` fills included. +pub(super) fn drawn_box(node: &Node) -> Option { + if let NodeKind::Text(t) = &node.kind + && matches!(t.kind, vectorcraft_doc::TextKind::Point) + && t.cached_bounds.is_none() + { + let mut laid = node.clone(); + if let NodeKind::Text(t) = &mut laid.kind { + t.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).bounds); + } + return laid.visual_bounds(); + } + node.visual_bounds() +} + #[cfg(test)] mod tests { use super::*; + /// Made point type's box is where its alignment and orientation draw it: right-aligned type + /// before its anchor, centered type round it, vertical type down from it. Its node keeps no + /// layout. + #[test] + fn made_point_type_s_box_is_where_its_alignment_and_orientation_draw_it() { + use vectorcraft_doc::{CharStyle, Justify, TextObject}; + let anchor = 300.0; + let boxed = |justify: Justify, vertical: bool| { + let mut t = TextObject::point(Point::new(anchor, 200.0), "Wide heading", CharStyle { size: 40.0, ..CharStyle::default() }); + t.para.justify = justify; + for p in t.para_styles_mut() { + p.justify = justify; + } + t.vertical = vertical; + let node = Node::new(NodeId(1), NodeKind::Text(Box::new(t))); + let b = drawn_box(&node).unwrap(); + assert!(matches!(&node.kind, NodeKind::Text(t) if t.cached_bounds.is_none())); + b + }; + let (left, right, centered, down) = + (boxed(Justify::Left, false), boxed(Justify::Right, false), boxed(Justify::Center, false), boxed(Justify::Left, true)); + assert!(left.x0 > anchor - 20.0 && left.width() > 100.0, "{left:?}"); + assert!(right.x1 < anchor + 20.0 && (right.width() - left.width()).abs() < 1.0, "{right:?}"); + assert!((centered.center().x - anchor).abs() < 20.0 && (centered.width() - left.width()).abs() < 1.0, "{centered:?}"); + assert!(down.height() > 2.0 * down.width() && down.height() > 100.0, "{down:?}"); + } + /// Past the limits, the slots of type that looks draw go, in groups too, and other slots stay. #[test] fn look_type_slots_are_dropped_from_groups() { diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index f809141202..262ed32c94 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -5509,6 +5509,66 @@ fn a_small_label_of_the_page_in_no_text_object_is_noted() { assert!(note.is_some_and(|w| crate::is_loss(w)), "{:?}", r.warnings); } +/// Point type that isn't aligned left is matched with the page's type where it draws: right-aligned +/// type ends at its anchor and centered type lies round it, so the page's type there is theirs and +/// nothing is noted as left out. (The box of type that isn't laid out yet runs right from its +/// anchor, past the page's type.) +#[test] +fn right_aligned_and_centered_point_type_takes_the_pages_type_where_it_draws() { + // "Hi there" in 14 point Helvetica is about 49 points wide. The anchors are 90 and 50 across the + // art; the page draws the line so that it ends at the first and lies round the second. + for (align, anchor, at) in [(1, 8231.5, 41.0), (2, 8191.5, 25.5)] { + let doc = text_document(&[("Hi there\r", align, (anchor, 8180.0), (0.0, 0.0), 0.0)]); + let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); + let page = format!("0 1 0 0 setcmykcolor /Helvetica findfont 14 scalefont setfont {at} 61.5 moveto (Hi there) show"); + let r = import(&eps(&page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{align}: {:?}", r.warnings); + let texts: Vec = text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect(); + assert_eq!(texts, ["Hi there"], "{align}: {:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| crate::is_loss(w)), "{align}: {:?}", r.warnings); + } +} + +/// Centered point type at a heading's size, set tight, is matched with the page's type where it +/// draws, round its anchor. (The box of type that isn't laid out yet runs right from the anchor and +/// holds the right half of the line; with a leading under the type's size it ends at the baseline, +/// so it holds less than the half of the page's type the match needs. At 14 points the 6 points +/// round the box make up for it.) +#[test] +fn centered_point_type_at_a_heading_s_size_takes_the_pages_type_where_it_draws() { + // A 500 × 150 artboard, its centre (250, 75) the canvas centre 8191.5. "Hi there, hi" in 72 point + // Helvetica on a 58 point leading is about 348 points wide; its anchor is the artboard's middle, + // 86.5 points up. + let doc = text_document(&[("Hi there, hi\r", 2, (8191.5, 8180.0), (0.0, 0.0), 0.0)]).replacen("/1 14.0 /53", "/1 72.0 /4 false /5 58.0 /53", 1); + let art = native_with_text(&layer("Art", true, &text_object(0)), &doc).replace("0 0 100 100", "0 0 500 150").replacen( + "%AI3_TemplateBox: 50 50 50 50", + "%AI3_TemplateBox: 250 75 250 75", + 1, + ); + let page = "0 1 0 0 setcmykcolor /Helvetica findfont 72 scalefont setfont 76 86.5 moveto (Hi there, hi) show"; + let file = String::from_utf8(eps(page, &art)).unwrap().replacen("%%BoundingBox: 0 0 100 100", "%%BoundingBox: 0 0 500 150", 1); + let r = import(file.as_bytes()).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let texts: Vec = text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect(); + assert_eq!(texts, ["Hi there, hi"], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| crate::is_loss(w)), "{:?}", r.warnings); +} + +/// Right-aligned point type that the page draws in another colour differs from the page as type, +/// where it draws, before its anchor: the layers are read and the note says the type differs. +/// (Counted as art, away from the box of type that isn't laid out, it sent the file to its page.) +#[test] +fn right_aligned_point_type_that_differs_from_the_page_differs_as_type() { + let doc = text_document(&[("Hi there\r", 1, (8231.5, 8180.0), (0.0, 0.0), 0.0)]); + let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); + // The text document's type is magenta; the page draws it black, ending at the anchor. + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 41 61.5 moveto (Hi there) show"; + let r = import(&eps(page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.starts_with("the type on the layers differs from the file's own page")), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.starts_with("the art on the layers differs")), "{:?}", r.warnings); +} + /// A ligature the page shows by a glyph its font's encoding names `uniE028` (a private-use /// character, without the letters it stands for) is the letters of its text object: the page's type /// has one, and nothing is noted as left out. diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index 44a9f01369..c9e219cabf 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -347,9 +347,10 @@ fn temp_path(target: &Path) -> io::Result { /// mode bits mean other people when the group differs, and an ACL can narrow who reads the file. /// When the group or the ACL can't be kept, the replacement is readable by its owner alone rather /// than by people the old file didn't let in. (Unix; Windows files have none to keep beyond -/// read-only, which makes the save fail as writing in place would.) +/// read-only, which makes the save fail as writing in place would.) `tmp` is the file that is about +/// to replace `target`. #[cfg(unix)] -fn keep_permissions(target: &Path, tmp: &Path) -> io::Result<()> { +pub fn keep_permissions(target: &Path, tmp: &Path) -> io::Result<()> { use std::os::unix::fs::{MetadataExt, PermissionsExt}; // A new file: the default permissions. let Ok(m) = std::fs::metadata(target) else { return Ok(()) }; @@ -385,8 +386,9 @@ fn keep_acl(_: &Path, _: &Path) -> bool { true } +/// Windows files have no permissions to keep beyond read-only (see the Unix version). #[cfg(not(unix))] -fn keep_permissions(_: &Path, _: &Path) -> io::Result<()> { +pub fn keep_permissions(_: &Path, _: &Path) -> io::Result<()> { Ok(()) } diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 1de16f938d..654f0ac065 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -58,7 +58,7 @@ use vectorcraft_doc::{Document, ImageBlob}; #[cfg(all(unix, not(target_arch = "wasm32")))] pub use atomic::sync_parent; #[cfg(not(target_arch = "wasm32"))] -pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; +pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; use craft_gzip::Gz; pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode}; use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json}; diff --git a/crates/js/Cargo.toml b/crates/js/Cargo.toml index c12871583a..c6140164ec 100644 --- a/crates/js/Cargo.toml +++ b/crates/js/Cargo.toml @@ -11,6 +11,8 @@ workspace = true [dependencies] chrono = { workspace = true } +# The XMP packets of XMPMeta and XMPFile (xmp.rs). +craft-xml = { workspace = true } # Unicode 17.0 general categories for identifiers (chars.rs). 0.1.5 adds the Unicode-3.0 license, # which is not on the license allowlist, so the version is exact. unicode-properties = { version = "=0.1.4", default-features = false, features = ["general-category"] } diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 8fb61c7d60..c4327572f9 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -135,6 +135,29 @@ fn parse_text(i: &mut Interp, text: Value, platform: bool) -> JsResult { host(i, "parse", &[text, current, Value::Bool(platform)]) } +/// The platform path `x` names, as `File(x).fsName` gives it: for `XMPFile` +/// ([`crate::xmp_classes`]). +pub(crate) fn platform_path(i: &mut Interp, x: &Value) -> JsResult { + let p = parse(i, x)?; + i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs")) +} + +/// Calls the host function `name` with `args`, as `File` and `Folder` call theirs: for `XMPFile`. +pub(crate) fn call_host(i: &mut Interp, name: &str, args: &[Value]) -> JsResult { + host(i, name, args) +} + +/// The field `name` of a record a host function gave ([`field`]): for `XMPFile`. +pub(crate) fn record_field(i: &mut Interp, v: &Value, name: &str) -> JsResult { + field(i, v, name) +} + +/// The count of runs the realm has begun since `File` and `Folder` were added, or `None` without +/// them: an `XMPFile` is open only in the run that opened it. +pub(crate) fn run_count(i: &Interp) -> Option { + i.files.as_ref().map(|c| c.run) +} + fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult { let (_, path) = this_path(i, this, what)?; let p = parse_text(i, path, true)?; @@ -1094,6 +1117,7 @@ fn folder_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { pub(crate) fn reset_current(i: &mut Interp) -> JsResult<()> { let Some(c) = i.files.as_mut() else { return Ok(()) }; c.run += 1.0; + i.heap.reset_xmp_files(); let start = host(i, "current", &[])?; if let Some(c) = i.files.as_mut() { c.current = start; @@ -1101,6 +1125,31 @@ pub(crate) fn reset_current(i: &mut Interp) -> JsResult<()> { Ok(()) } +#[cfg(test)] +mod xmp_run_tests { + use super::*; + use crate::heap::PropMap; + + #[test] + fn a_failed_folder_reset_releases_native_xmp_buffers() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + let host = interp.heap.alloc_object(Object::new(Class::Ordinary, None)); + interp.files = Some(Classes { file_proto: host, folder_proto: host, host, current: Value::str("start"), run: 0.0 }); + let mut fields = PropMap::default(); + fields.insert(key("__vcXmpPacket"), Value::str("packet")); + fields.insert(key("__vcXmpPending"), Value::str("pending")); + fields.insert(key("__vcXmpPath"), Value::str("kept.xmp")); + let file = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), None)); + let result = interp.rooted(&[Value::Object(file)], reset_current); + assert!(result.is_err(), "the host has no current function"); + assert_eq!(run_count(&interp), Some(1.0)); + let Class::XmpFile(fields) = &interp.heap.object(file).unwrap().class else { panic!("native file") }; + assert!(matches!(fields.get(&key("__vcXmpPacket")), Some(Value::Null))); + assert!(matches!(fields.get(&key("__vcXmpPending")), Some(Value::Undefined))); + assert!(matches!(fields.get(&key("__vcXmpPath")), Some(Value::String(path)) if path.to_rust_string() == "kept.xmp")); + } +} + /// Adds `File` and `Folder` to the global object, their work done by the host functions in /// `items` ([`crate::Realm::define_file_classes`]). pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResult<()> { diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 1a58fa1d28..cab193aa88 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -268,6 +268,10 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// An `XMPMeta` object and its metadata ([`crate::xmp_classes`]). + Xmp(Box), + /// An object the `XMPFile` constructor made ([`crate::xmp_classes`]). + XmpFile(Box>), /// An object of a class a host defined ([`crate::host_classes`]). Host(crate::host_classes::HostObj), /// A `UnitValue` object and its measurement ([`crate::unit_value`]). @@ -339,7 +343,7 @@ impl Class { Class::XmlList(_) => "XMLList", Class::Namespace(_) => "Namespace", Class::QName { .. } => "QName", - Class::XmlFilter(_) | Class::PromiseRecord(_) => "Object", + Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile(_) | Class::PromiseRecord(_) => "Object", Class::Promise(_) => "Promise", Class::Math => "Math", Class::Json => "JSON", @@ -538,6 +542,16 @@ impl Heap { ids.filter_map(|(i, _)| u32::try_from(i).ok().map(ObjId)).collect() } + pub(crate) fn reset_xmp_files(&mut self) { + for cell in &mut self.cells { + if let Cell::Object(object) = cell + && let Class::XmpFile(fields) = &mut object.class + { + crate::xmp_classes::reset_file_state(fields); + } + } + } + /// Live cells, for tests. #[cfg(test)] pub(crate) fn live_cells(&self) -> usize { @@ -811,6 +825,14 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.input.iter().chain(&state.kept).map(|o| o.0)); extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } + Class::Xmp(meta) => extra = meta.heap_bytes(), + Class::XmpFile(fields) => { + for (name, value) in fields.iter() { + strings.add_key(name); + mark_value(value, work, strings); + } + extra = std::mem::size_of::>() + PROP_BYTES * fields.len(); + } Class::UnitValue(_) => extra = UNIT_VALUE_BYTES, Class::Promise(p) => { for v in p.values() { @@ -877,6 +899,28 @@ mod tests { assert_eq!(heap.bytes, OBJECT_BYTES + 2 * PROP_BYTES + string_bytes(1000) + string_bytes(5)); } + #[test] + fn xmp_file_buffers_are_traced_and_released_at_the_file_run_boundary() { + let mut heap = Heap::default(); + let pending = heap.alloc_object(Object::new(Class::Ordinary, None)); + let mut fields = PropMap::default(); + fields.insert(key("__vcXmpPacket"), Value::str(&"p".repeat(8192))); + fields.insert(key("__vcXmpPending"), Value::Object(pending)); + fields.insert(key("__vcXmpPath"), Value::str("kept.xmp")); + let file = heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), None)); + let roots = Roots { objects: vec![file], ..Roots::default() }; + heap.collect(&roots); + assert!(heap.object(pending).is_some(), "native values keep their objects reachable"); + let before = heap.bytes; + assert!(before >= string_bytes(8192), "native packet strings count toward the heap limit"); + heap.reset_xmp_files(); + heap.collect(&roots); + assert!(heap.object(pending).is_none(), "the prior run's pending value is released"); + assert!(before - heap.bytes >= string_bytes(8192), "the prior run's packet is released"); + let Class::XmpFile(fields) = &heap.object(file).unwrap().class else { panic!("native file") }; + assert!(matches!(fields.get(&key("__vcXmpPath")), Some(Value::String(path)) if path.to_rust_string() == "kept.xmp")); + } + #[test] fn prop_maps_keep_insertion_order_through_removals_and_growth() { let mut m = PropMap::default(); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 276895e782..81d8411530 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -106,6 +106,7 @@ pub enum Arg { pub(crate) enum ArgRead { /// Each as [`Data`]. Data, + DataWithin(DataLimits), /// Each as [`Data`], with the result given frozen, as [`HostItem::Value`] gives its value. Frozen, /// Each as the string `String(value)` gives. @@ -126,6 +127,12 @@ pub enum HostItem { /// A read-only copy of a value. Value(Data), Function(HostFunction), + /// A function whose explicit arguments use `limits`. The realm's other crossings keep their + /// configured limits. The result uses the realm's limits. + FunctionWithLimits { + limits: DataLimits, + function: HostFunction, + }, /// A function whose arguments arrive as strings, each the string `String(value)` gives. TextFunction(HostFunction), /// A function whose arguments arrive converted one by one as the list says. Arguments past the @@ -507,7 +514,10 @@ impl Interp { /// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first. fn read_args(&mut self, name: &Rc, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult> { let mut reading = Reading { - limits: self.data_limits, + limits: match how { + ArgRead::DataWithin(limits) => *limits, + _ => self.data_limits, + }, bytes: 0, entries: 0, ancestors: Vec::new(), @@ -529,14 +539,14 @@ impl Interp { } // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); - if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) { + if !matches!(how, ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Hosted) { self.temp_roots.extend(args.iter().cloned()); } let mut read = Ok(()); for (i, a) in args.iter().enumerate() { reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); let d = match how { - ArgRead::Data | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading), + ArgRead::Data | ArgRead::DataWithin(_) | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading), ArgRead::Text => self.read_text(a, &mut reading), ArgRead::Each(list) => match list.get(i) { Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined), @@ -666,6 +676,9 @@ impl Interp { }, HostItem::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE }, HostItem::Function(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Data)), flags: ENUMERABLE }, + HostItem::FunctionWithLimits { limits, function } => { + Prop::Data { value: Value::Object(self.host_function(function, &full, ArgRead::DataWithin(limits))), flags: ENUMERABLE } + } HostItem::TextFunction(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Text)), flags: ENUMERABLE }, HostItem::Converted(list, f) => { Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Each(list.into()))), flags: ENUMERABLE } @@ -720,3 +733,30 @@ fn read_site(data: &[Data]) -> CallSite { }; CallSite { source: at(0, crate::UNKNOWN_SOURCE), line: at(1, 0), column: at(2, 0) } } + +#[cfg(test)] +mod argument_limit_tests { + use super::*; + + #[test] + fn a_binding_argument_budget_does_not_change_other_crossings() { + let mut realm = crate::Realm::with_options(crate::Options::default(), crate::Limits::default()); + let function: HostFunction = Rc::new(|_| Ok(Data::Bool(true))); + realm + .define_host_object( + "h", + vec![ + ("normal".into(), HostItem::Function(function.clone())), + ("wide".into(), HostItem::FunctionWithLimits { limits: DataLimits { bytes: 64, ..DataLimits::default() }, function }), + ], + ) + .unwrap(); + realm.set_data_limits(DataLimits { bytes: 16, ..DataLimits::default() }); + assert_eq!(realm.run("h.wide('abcdefgh')").unwrap(), crate::JsValue::Bool(true)); + assert_eq!(realm.run("try { h.normal('abcdefgh'); false } catch (e) { e instanceof RangeError }").unwrap(), crate::JsValue::Bool(true)); + assert_eq!( + realm.run("try { h.wide('abcdefghijklmnopqrstuvwxyz'); false } catch (e) { e instanceof RangeError }").unwrap(), + crate::JsValue::Bool(true) + ); + } +} diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index f8e80a6e87..12618ef677 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -308,6 +308,9 @@ pub(crate) struct Interp { pub(crate) install_error: Option, /// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]). pub(crate) files: Option, + /// `ExternalObject` and the XMP classes it loads, once a host has added them + /// ([`crate::Realm::define_external_object`]). + pub(crate) xmp: Option, /// The classes a host added ([`crate::Realm::define_host_classes`]), in the order it added them. pub(crate) host_classes: Vec, /// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`]. @@ -629,6 +632,7 @@ impl Interp { held_bytes: 0, install_error: None, files: None, + xmp: None, host_classes: Vec::new(), write_hosted: false, host_objects: crate::host_classes::Made::default(), @@ -910,6 +914,7 @@ impl Interp { roots.objects.push(self.global); roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); + roots.objects.extend(self.xmp.iter().flat_map(crate::xmp_classes::Classes::objects)); roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects)); roots.values.extend(self.symbols.root_values()); roots.objects.extend(self.symbols.root_objects()); @@ -938,6 +943,7 @@ impl Interp { .saturating_add(self.held_bytes) .saturating_add(self.held.now.get()) .saturating_add(self.symbols.registry_bytes()) + .saturating_add(self.xmp.as_ref().map_or(0, crate::xmp_classes::Classes::bytes)) .saturating_add(queued); } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index a93dcd5483..7660bf6176 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -126,6 +126,8 @@ mod unit_value; mod value; mod xml; mod xml_builtins; +mod xmp; +mod xmp_classes; mod xpath; pub use ast::{ @@ -143,6 +145,7 @@ pub use realm::{ Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, Rejection, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE, }; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; +pub use xmp::{MAX_BYTES as XMP_MAX_BYTES, PacketSpan, find_packet as find_xmp_packet}; /// How a script is read. #[derive(Clone, Debug, PartialEq, Eq)] @@ -300,3 +303,5 @@ mod text_tests; mod unit_value_tests; #[cfg(test)] mod xml_tests; +#[cfg(test)] +mod xmp_tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index bd191b0463..1daf11a33d 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -617,6 +617,23 @@ impl Realm { } } + /// Adds the global `ExternalObject`. `new ExternalObject("lib:AdobeXMPScript")` defines the + /// globals `XMPMeta`, `XMPFile` and `XMPConst`; any other library name throws. `XMPFile` reads + /// and writes files through the host functions `xmpOpen` and `xmpWrite` of + /// [`Realm::define_file_classes`], which the host adds first; without `File` and `Folder`, + /// `XMPFile` throws. An `XMPFile` is open only in the run that opened it: each + /// [`Realm::reset_folder_current`] begins a new run for it, and [`Realm::run`] and + /// [`Realm::start`] do not. A successful close or a new file run releases its packet buffers. + /// Registered namespace storage counts toward the realm's heap limit. + /// After a successful installation, another call fails with an internal + /// error and preserves `ExternalObject` and registered namespaces. A failed installation can be retried. + pub fn define_external_object(&mut self) -> Result<(), RunError> { + match crate::xmp_classes::install(&mut self.interp) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Adds the host classes `classes` ([`crate::HostClass`]), each a global constructor whose /// prototype holds its members, and the global objects `instances`, each made from the /// [`crate::host_ref`] given. Prototypes and constructors are frozen; the instances cannot be diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs new file mode 100644 index 0000000000..a97418ccbd --- /dev/null +++ b/crates/js/src/xmp.rs @@ -0,0 +1,1436 @@ +//! XMP metadata for the scripts' `XMPMeta` and `XMPFile` ([`crate::xmp_classes`]): a packet read +//! into the list of its top-level properties and written back as RDF/XML, as the XMP Specification +//! Part 1 (ISO 16684-1, +//! ) +//! describes the serialization. +//! +//! A packet is read with `craft_xml`, which refuses a document type declaration and every entity +//! reference other than the predefined and numeric ones, and bounds the input, the nesting, the +//! nodes and the attributes. The `rdf:Description` elements under `rdf:RDF` give the properties: +//! a simple value (text, or a URI in `rdf:resource`), an array of simple items (`rdf:Bag`, +//! `rdf:Seq` or `rdf:Alt`, each item with an optional `xml:lang`), or any other value (a structure, +//! a value with qualifiers, an array of structures), which is kept as the XML it was written in and +//! written back with the namespace declarations it uses; a value with qualifiers in the `rdf:value` +//! form gives the text and the options of its `rdf:value`. The namespaces of the property, element and +//! attribute names under `rdf:Description` are added to the realm's [`Registry`] with the prefix the +//! packet gives them, or a new prefix when that one is taken; a namespace the packet declares and no +//! such name uses is not added. +//! +//! VectorCraft's own rules: a packet or a written packet holds at most [`MAX_BYTES`] bytes, +//! elements nest at most 64 deep, and each holds at most 1,024 attributes and has at most 1,024 +//! namespace declarations in scope, both as read and as written; a +//! child of `rdf:RDF` other than `rdf:Description` and text beside the descriptions or their +//! properties make the packet malformed, and a property given twice keeps its first value. +//! Explicit `rdf:about` values must agree, including empty values. Qualified names have valid prefix and local parts; +//! only spaces, tabs, carriage returns and line feeds count as indentation. +//! [`find_packet`] finds only a UTF-8 packet. A realm registers at most [`MAX_NAMESPACES`] namespaces holding at most +//! [`MAX_REGISTRY_BYTES`] bytes, each URI at most [`MAX_URI_BYTES`] bytes and each prefix at most +//! [`MAX_PREFIX_BYTES`] bytes. + +use std::collections::{HashMap, HashSet}; +use std::rc::Rc; + +use craft_xml::{Doctype, El, Limits, Names, Node, Options, UnknownEntity, XML_NS}; + +#[cfg(test)] +thread_local! { + pub(crate) static ACCOUNTING_ITEM_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + pub(crate) static ITEM_COPIES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The RDF namespace. +pub(crate) const RDF: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; +/// The namespace of the `x:xmpmeta` element around a packet's `rdf:RDF`. +const X: &str = "adobe:ns:meta/"; // brand-ok: the XMP namespace the files use +/// The Dublin Core namespace. +pub(crate) const DC: &str = "http://purl.org/dc/elements/1.1/"; +/// The XMP basic namespace. +pub(crate) const XMP: &str = "http://ns.adobe.com/xap/1.0/"; // brand-ok: the XMP namespace the files use +/// The XMP rights namespace. +pub(crate) const XMP_RIGHTS: &str = "http://ns.adobe.com/xap/1.0/rights/"; // brand-ok: the XMP namespace the files use +/// The PDF namespace. +pub(crate) const PDF: &str = "http://ns.adobe.com/pdf/1.3/"; // brand-ok: the XMP namespace the files use +/// The namespace of the image editor's properties. +pub(crate) const PHOTOSHOP: &str = "http://ns.adobe.com/photoshop/1.0/"; // brand-ok: the XMP namespace the files use +/// The XML namespace. +pub(crate) const XML: &str = XML_NS; +/// The namespace of the `xmlns` attributes, which no prefix may name. +const XMLNS: &str = "http://www.w3.org/2000/xmlns/"; + +/// The most bytes of a packet read or written. +pub const MAX_BYTES: usize = 8 << 20; +const MAX_DEPTH: usize = 64; +const MAX_NODES: usize = 1 << 20; +const MAX_ATTRS: usize = 1024; +/// The most namespaces a realm registers. +const MAX_NAMESPACES: usize = 4096; +/// The most bytes of a namespace URI a realm registers. +pub(crate) const MAX_URI_BYTES: usize = 1024; +/// The most bytes of a namespace prefix a realm registers, a `_n_` suffix included. +pub(crate) const MAX_PREFIX_BYTES: usize = 128; +/// The most bytes a realm's namespaces hold, counted by [`Registry::bytes`]. +pub(crate) const MAX_REGISTRY_BYTES: usize = 1 << 20; +/// The bytes counted for each namespace besides its URI and prefix. +const ENTRY_BYTES: usize = 96; +/// The `id` of a packet wrapper (XMP Specification Part 1, 7.3.2). +const WRAPPER_ID: &str = "W5M0MpCehiHzreSzNTczkc9d"; +/// The most bytes [`find_packet`] reads of a packet header, from its ``. +const MAX_HEADER: usize = 256; + +/// The property is a URI (`rdf:resource`). +pub(crate) const PROP_VALUE_IS_URI: u32 = 0x2; +/// The property has qualifiers. +const PROP_HAS_QUALIFIERS: u32 = 0x10; +/// The property has an `xml:lang` qualifier. +const PROP_HAS_LANG: u32 = 0x40; +/// The property is a structure. +pub(crate) const PROP_IS_STRUCT: u32 = 0x100; +/// The property is an array. +pub(crate) const PROP_IS_ARRAY: u32 = 0x200; +/// The array's order matters (`rdf:Seq`). +pub(crate) const ARRAY_IS_ORDERED: u32 = 0x400; +/// The array's items are alternatives (`rdf:Alt`). +pub(crate) const ARRAY_IS_ALTERNATIVE: u32 = 0x800; +/// The array's items are text in several languages. +pub(crate) const ARRAY_IS_ALTTEXT: u32 = 0x1000; + +/// Why XMP could not be read, written or changed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum XmpError { + /// The packet is not well-formed XML, or not XMP. + Malformed, + /// The packet, or the packet written, is longer than [`MAX_BYTES`], or a namespace URI is longer + /// than [`MAX_URI_BYTES`] or its prefix longer than [`MAX_PREFIX_BYTES`]. + TooLarge, + /// The realm already has [`MAX_NAMESPACES`] namespaces, or one more would take its namespaces + /// over [`MAX_REGISTRY_BYTES`]. + Namespaces, + /// A name that is not an XML name without a colon, or a prefix that names another namespace. + BadName, + /// Text with a character XML does not allow. + BadText, + /// An unsupported packet language, structure field, qualifier or selector form. + NotYet, + /// The metadata a packet gives is larger than the budget [`parse_within`] was given. + Heap, +} + +/// The kind of an array. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Form { + Bag, + Seq, + Alt, +} + +impl Form { + fn element(self) -> &'static str { + match self { + Form::Bag => "rdf:Bag", + Form::Seq => "rdf:Seq", + Form::Alt => "rdf:Alt", + } + } + + /// The array's options, as `XMPProperty.options` gives them. + fn options(self) -> u32 { + match self { + Form::Bag => PROP_IS_ARRAY, + Form::Seq => PROP_IS_ARRAY | ARRAY_IS_ORDERED, + Form::Alt => PROP_IS_ARRAY | ARRAY_IS_ORDERED | ARRAY_IS_ALTERNATIVE, + } + } + + /// The form the options of a new array give: `Alt` with [`ARRAY_IS_ALTERNATIVE`] or + /// [`ARRAY_IS_ALTTEXT`], `Seq` with [`ARRAY_IS_ORDERED`], else `Bag`. + pub(crate) fn from_options(options: u32) -> Form { + if options & (ARRAY_IS_ALTERNATIVE | ARRAY_IS_ALTTEXT) != 0 { + Form::Alt + } else if options & ARRAY_IS_ORDERED != 0 { + Form::Seq + } else { + Form::Bag + } + } +} + +/// An item of an array of simple values. +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct Item { + pub(crate) text: String, + pub(crate) lang: Option, +} + +impl Clone for Item { + fn clone(&self) -> Self { + #[cfg(test)] + ITEM_COPIES.with(|copies| copies.set(copies.get() + 1)); + Self { text: self.text.clone(), lang: self.lang.clone() } + } +} + +impl Item { + /// Does the item name a language? `xml:lang=""` names none. + pub(crate) fn has_lang(&self) -> bool { + self.lang.as_deref().is_some_and(|l| !l.is_empty()) + } + + /// The options `XMPProperty.options` gives for the item: an `xml:lang` qualifier, also an empty + /// one, is a qualifier and a language, as on a property. + pub(crate) fn options(&self) -> u32 { + if self.lang.is_some() { PROP_HAS_QUALIFIERS | PROP_HAS_LANG } else { 0 } + } +} + +/// A property's value. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Value { + Simple { + text: String, + uri: bool, + }, + Array { + form: Form, + items: Vec, + }, + /// A value kept as the XML element it was read as, with the namespace declarations it uses, its + /// options and its text when it has one. + Other { + xml: String, + /// Validation counts the expanded XML without retaining it. + expanded_bytes: usize, + options: u32, + text: Option, + /// The most namespace declarations `xml` puts in scope at one of its elements. + decls: usize, + }, +} + +impl Value { + /// The options `XMPProperty.options` gives. + pub(crate) fn options(&self) -> u32 { + match self { + Value::Simple { uri, .. } => { + if *uri { + PROP_VALUE_IS_URI + } else { + 0 + } + } + Value::Array { form, items } => { + let alt_text = *form == Form::Alt && !items.is_empty() && items.iter().all(Item::has_lang); + form.options() | if alt_text { ARRAY_IS_ALTTEXT } else { 0 } + } + Value::Other { options, .. } => *options, + } + } + + /// The text `XMPProperty.value` gives; `None` for an array or a structure. + pub(crate) fn text(&self) -> Option<&str> { + match self { + Value::Simple { text, .. } => Some(text), + Value::Array { .. } => None, + Value::Other { text, .. } => text.as_deref(), + } + } +} + +/// A top-level property. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Prop { + /// The namespace, which the properties a packet gives in the same namespace share. + pub(crate) ns: Rc, + pub(crate) name: String, + pub(crate) value: Value, +} + +impl Prop { + /// The estimated bytes the property holds. + pub(crate) fn heap_bytes(&self) -> usize { + let value = match &self.value { + Value::Simple { text, .. } => text.len(), + Value::Array { items, .. } => { + #[cfg(test)] + ACCOUNTING_ITEM_VISITS.with(|visits| visits.set(visits.get() + items.len())); + items.iter().map(|i| 48 + i.text.len() + i.lang.as_ref().map_or(0, String::len)).sum() + } + Value::Other { expanded_bytes, text, .. } => expanded_bytes + text.as_ref().map_or(0, String::len), + }; + 96 + self.ns.len() + self.name.len() + value + } +} + +/// The metadata of one `XMPMeta`: its `rdf:about` and its properties, in order. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct Meta { + pub(crate) about: String, + pub(crate) props: Vec, +} + +impl Meta { + /// The estimated bytes the metadata holds. + pub(crate) fn heap_bytes(&self) -> usize { + 32 + self.about.len() + self.props.iter().map(Prop::heap_bytes).sum::() + } + + /// The position of the property `name` in the namespace `ns`. + pub(crate) fn find(&self, ns: &str, name: &str) -> Option { + self.props.iter().position(|p| &*p.ns == ns && p.name == name) + } +} + +/// The namespaces a realm knows, each with its prefix (without the colon), in the order they were +/// registered. +#[derive(Clone, Debug)] +pub(crate) struct Registry { + /// Prefix by namespace, and namespace by prefix: each namespace has one prefix and each prefix + /// names one namespace. + prefixes: HashMap, + uris: HashMap, + /// The bytes the namespaces hold, as [`entry_bytes`] counts them. + bytes: usize, +} + +/// The bytes counted for the namespace `uri` with the prefix `prefix`: both strings are kept twice. +fn entry_bytes(uri: &str, prefix: &str) -> usize { + ENTRY_BYTES + 2 * (uri.len() + prefix.len()) +} + +impl Default for Registry { + fn default() -> Self { + let standard = + [("rdf", RDF), ("x", X), ("xml", XML), ("dc", DC), ("xmp", XMP), ("xmpRights", XMP_RIGHTS), ("pdf", PDF), ("photoshop", PHOTOSHOP)]; // brand-ok: the XMP namespace prefix the files use + Self { + prefixes: standard.iter().map(|(p, u)| ((*u).to_string(), (*p).to_string())).collect(), + uris: standard.iter().map(|(p, u)| ((*p).to_string(), (*u).to_string())).collect(), + bytes: standard.iter().map(|(p, u)| entry_bytes(u, p)).sum(), + } + } +} + +impl Registry { + /// The bytes the namespaces hold, at most [`MAX_REGISTRY_BYTES`]. + pub(crate) fn bytes(&self) -> usize { + self.bytes + } + + /// The prefix of the namespace `uri`. + pub(crate) fn prefix_of(&self, uri: &str) -> Option<&str> { + self.prefixes.get(uri).map(String::as_str) + } + + /// The namespace the prefix `prefix` names. + pub(crate) fn uri_of(&self, prefix: &str) -> Option<&str> { + self.uris.get(prefix).map(String::as_str) + } + + /// Registers the namespace `uri` with the prefix `suggested` (a trailing colon is left out), or + /// with `suggested_1_`, `suggested_2_` … when that one names another namespace. → the prefix + /// the namespace has, which is its earlier one when it was registered before. A URI over + /// [`MAX_URI_BYTES`] or a prefix over [`MAX_PREFIX_BYTES`] is [`XmpError::TooLarge`], and a + /// namespace past [`MAX_NAMESPACES`] or [`MAX_REGISTRY_BYTES`] is [`XmpError::Namespaces`]. + pub(crate) fn register(&mut self, uri: &str, suggested: &str) -> Result { + let (prefix, growth) = self.registration(uri, suggested)?; + if growth != 0 { + self.bytes += growth; + self.prefixes.insert(uri.to_string(), prefix.clone()); + self.uris.insert(prefix.clone(), uri.to_string()); + } + Ok(prefix) + } + + /// The prefix and retained bytes a registration would add, without changing the registry. + pub(crate) fn registration(&self, uri: &str, suggested: &str) -> Result<(String, usize), XmpError> { + if let Some(p) = self.prefix_of(uri) { + return Ok((p.to_string(), 0)); + } + let suggested = suggested.strip_suffix(':').unwrap_or(suggested); + if uri.len() > MAX_URI_BYTES || suggested.len() > MAX_PREFIX_BYTES { + return Err(XmpError::TooLarge); + } + // XML does not allow the prefix `xmlns` to be declared or a prefix to name its namespace. + if uri.is_empty() || !is_text(uri) || !is_ncname(suggested) || suggested == "xmlns" || uri == XMLNS { + return Err(XmpError::BadName); + } + if self.prefixes.len() >= MAX_NAMESPACES { + return Err(XmpError::Namespaces); + } + let mut prefix = suggested.to_string(); + let mut n = 1; + while self.uri_of(&prefix).is_some() { + prefix = format!("{suggested}_{n}_"); + n += 1; + } + if prefix.len() > MAX_PREFIX_BYTES { + return Err(XmpError::TooLarge); + } + let bytes = self.bytes.saturating_add(entry_bytes(uri, &prefix)); + if bytes > MAX_REGISTRY_BYTES { + return Err(XmpError::Namespaces); + } + let growth = entry_bytes(uri, &prefix); + Ok((prefix, growth)) + } +} + +/// Is `s` an XML name without a colon? +pub(crate) fn is_ncname(s: &str) -> bool { + craft_xml::is_name(s) && !s.contains(':') +} + +/// Does `s` hold only characters XML allows? +pub(crate) fn is_text(s: &str) -> bool { + s.chars().all(craft_xml::is_xml_char) +} + +/// Where a property path leads: the whole property, or one item of an array by its position from 1 +/// (-1 for the last). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Step { + Whole, + Item(i64), +} + +/// The property name and step of the path `path` in the namespace `ns`: `name`, `prefix:name`, +/// either with `[n]` or `[last()]` after it. A prefix must name `ns`. +pub(crate) fn parse_path(path: &str, ns: &str, registry: &Registry) -> Result<(String, Step), XmpError> { + if path.contains(['/', '?', '@']) { + return Err(XmpError::NotYet); + } + let (name, step) = match path.split_once('[') { + None => (path, Step::Whole), + Some((name, rest)) => { + let inner = rest.strip_suffix(']').ok_or(XmpError::BadName)?; + let step = match inner { + "last()" => Step::Item(-1), + n if !n.is_empty() && n.len() <= 9 && n.bytes().all(|b| b.is_ascii_digit()) => match n.parse::() { + Ok(i) if i >= 1 => Step::Item(i), + _ => return Err(XmpError::BadName), + }, + _ => return Err(XmpError::NotYet), + }; + (name, step) + } + }; + let local = match name.split_once(':') { + Some((prefix, local)) => { + if registry.uri_of(prefix) != Some(ns) { + return Err(XmpError::BadName); + } + local + } + None => name, + }; + if !is_ncname(local) { + return Err(XmpError::BadName); + } + Ok((local.to_string(), step)) +} + +/// The bindings of namespace prefixes in scope, innermost last; `""` is the default namespace. +type Scope = Vec<(String, String)>; + +fn push_decls(el: &El, scope: &mut Scope) { + for (prefix, uri) in el.ns_decls() { + scope.push((prefix.to_string(), uri.to_string())); + } +} + +/// Is `name` a namespace declaration? +fn is_decl(name: &str) -> bool { + name == "xmlns" || name.starts_with("xmlns:") +} + +fn valid_qualified_name(name: &str) -> bool { + name.split_once(':').map_or_else(|| is_ncname(name), |(prefix, local)| is_ncname(prefix) && is_ncname(local)) +} + +fn valid_packet_names(element: &El) -> bool { + valid_qualified_name(&element.name) + && element.attrs.iter().all(|(name, _)| valid_qualified_name(name)) + && element.elements().all(valid_packet_names) +} + +/// The namespace and local name of the qualified name `name`: an unprefixed element is in the +/// default namespace, an unprefixed attribute (`element` false) in none. `None` for a prefix +/// nothing declares. +fn resolve<'n>(name: &'n str, scope: &Scope, element: bool) -> Option<(String, &'n str)> { + if let Some((prefix, local)) = name.split_once(':') { + if !is_ncname(prefix) || !is_ncname(local) { + return None; + } + } else if !is_ncname(name) { + return None; + } + let (prefix, local) = match name.split_once(':') { + Some((p, l)) => (p, l), + None if element => ("", name), + None => return Some((String::new(), name)), + }; + if prefix == "xml" { + return Some((XML.to_string(), local)); + } + let uri = scope.iter().rev().find(|(p, _)| p == prefix).map(|(_, u)| u.clone()); + match uri { + Some(u) => Some((u, local)), + None if prefix.is_empty() => Some((String::new(), local)), + None => None, + } +} + +fn is_named(name: &str, scope: &Scope, element: bool, ns: &str, local: &str) -> bool { + resolve(name, scope, element).is_some_and(|(u, l)| u == ns && l == local) +} + +/// The text of `el`'s own text and CDATA children. +fn text_of(el: &El) -> String { + let mut s = String::new(); + for n in &el.children { + if let Node::Text(t) | Node::CData(t) = n { + s.push_str(t); + } + } + s +} + +/// The attributes of `el` that are not namespace declarations. +fn attrs(el: &El) -> Vec<(&str, &str)> { + el.attrs.iter().filter(|(k, _)| !is_decl(k)).map(|(k, v)| (k.as_str(), v.as_str())).collect() +} + +/// The `rdf:RDF` element at or below `el`, with `scope` holding the bindings in scope there. +fn find_rdf<'a>(el: &'a El, scope: &mut Scope, language: Option<&'a str>) -> Option<(&'a El, Option<&'a str>)> { + let mark = scope.len(); + push_decls(el, scope); + let language = inherited_language(el, scope, language); + if is_named(&el.name, scope, true, RDF, "RDF") { + return Some((el, language)); + } + for c in el.elements() { + if let Some(found) = find_rdf(c, scope, language) { + return Some(found); + } + } + scope.truncate(mark); + None +} + +fn inherited_language<'a>(el: &'a El, scope: &Scope, language: Option<&'a str>) -> Option<&'a str> { + attrs(el).into_iter().find(|(name, _)| is_named(name, scope, false, XML, "lang")).map(|(_, value)| value).or(language) +} + +/// Tests: reads the packet `text` with no budget ([`parse_within`]). +#[cfg(test)] +pub(crate) fn parse(text: &str, registry: &mut Registry) -> Result { + parse_within(text, registry, usize::MAX) +} + +/// Reads the packet `text`, registering the namespaces it uses in `registry`, and stops with +/// [`XmpError::Heap`] as soon as the properties read hold more than `budget` bytes, as +/// [`Meta::heap_bytes`] counts them. A packet that fails to read leaves `registry` unchanged. +pub(crate) fn parse_within(text: &str, registry: &mut Registry, budget: usize) -> Result { + let mut staged = registry.clone(); + let meta = parse_into(text, &mut staged, budget, true)?; + *registry = staged; + Ok(meta) +} + +/// Checks a packet within `budget` without retaining expanded XML fragments. +pub(crate) fn validate_within(text: &str, registry: &mut Registry, budget: usize) -> Result<(), XmpError> { + let mut staged = registry.clone(); + parse_into(text, &mut staged, budget, false)?; + *registry = staged; + Ok(()) +} + +/// The properties a packet has given so far. +struct Reading { + meta: Meta, + /// The names `meta` has. + seen: HashSet<(Rc, String)>, + /// The namespaces of the properties, each held once. + pool: HashSet>, + /// The bytes `meta` holds, and the most it may hold. + bytes: usize, + budget: usize, + retain_fragments: bool, +} + +impl Reading { + /// The shared copy of the namespace `ns`. + fn intern(&mut self, ns: String) -> Rc { + if let Some(shared) = self.pool.get(ns.as_str()) { + return Rc::clone(shared); + } + let shared: Rc = ns.into(); + self.pool.insert(Rc::clone(&shared)); + shared + } + + /// Adds `prop` unless a property of that name was read before. + fn add(&mut self, prop: Prop) -> Result<(), XmpError> { + if self.seen.insert((Rc::clone(&prop.ns), prop.name.clone())) { + self.bytes = self.bytes.saturating_add(prop.heap_bytes()); + if self.bytes > self.budget { + return Err(XmpError::Heap); + } + self.meta.props.push(prop); + } + Ok(()) + } +} + +/// Is `node` text that is not XML whitespace alone? +fn is_stray_text(node: &Node) -> bool { + matches!(node, Node::Text(t) | Node::CData(t) if !t.trim_matches([' ', '\t', '\r', '\n']).is_empty()) +} + +fn parse_into(text: &str, registry: &mut Registry, budget: usize, retain_fragments: bool) -> Result { + if text.len() > MAX_BYTES { + return Err(XmpError::TooLarge); + } + let text = text.strip_prefix('\u{FEFF}').unwrap_or(text); + let limits = Limits { max_input: MAX_BYTES, max_depth: MAX_DEPTH, max_nodes: MAX_NODES, max_attrs: MAX_ATTRS, ..Limits::DEFAULT }; + let opts = Options { + names: Names::AsWritten, + doctype: Doctype::Reject, + unknown_entity: UnknownEntity::Error, + drop_blank_text: false, + limits, + ..Options::default() + } + .strict(); + let root = opts.parse(text.as_bytes()).map_err(|e| if e.is_limit() { XmpError::TooLarge } else { XmpError::Malformed })?; + if !valid_packet_names(&root) { + return Err(XmpError::Malformed); + } + let mut scope = Scope::new(); + let (rdf, language) = find_rdf(&root, &mut scope, None).ok_or(XmpError::Malformed)?; + let mut explicit_subject = None; + // Text beside the descriptions or their properties is not RDF. + if rdf.children.iter().any(is_stray_text) { + return Err(XmpError::Malformed); + } + let mut reading = Reading { meta: Meta::default(), seen: HashSet::new(), pool: HashSet::new(), bytes: 32, budget, retain_fragments }; + for d in rdf.elements() { + let mark = scope.len(); + push_decls(d, &mut scope); + if !is_named(&d.name, &scope, true, RDF, "Description") || d.children.iter().any(is_stray_text) { + return Err(XmpError::Malformed); + } + if inherited_language(d, &scope, language).is_some_and(|language| !language.is_empty()) { + return Err(XmpError::NotYet); + } + for (k, v) in attrs(d) { + let Some((ns, local)) = resolve(k, &scope, false) else { return Err(XmpError::Malformed) }; + if ns == RDF { + if local == "about" { + if explicit_subject.is_some_and(|subject| subject != v) { + return Err(XmpError::Malformed); + } + explicit_subject = Some(v); + } + if local == "about" && reading.meta.about.is_empty() { + reading.meta.about = v.to_string(); + reading.bytes = reading.bytes.saturating_add(v.len()); + if reading.bytes > reading.budget { + return Err(XmpError::Heap); + } + } + continue; + } + if ns.is_empty() || ns == XML { + continue; + } + let prefix = k.split_once(':').map_or("ns", |(p, _)| p); + registry.register(&ns, prefix)?; + let ns = reading.intern(ns); + reading.add(Prop { ns, name: local.to_string(), value: Value::Simple { text: v.to_string(), uri: false } })?; + } + for p in d.elements() { + let prop = read_property(p, &mut scope, registry, &mut reading)?; + reading.add(prop)?; + } + scope.truncate(mark); + } + Ok(reading.meta) +} + +fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry, reading: &mut Reading) -> Result { + let mark = scope.len(); + push_decls(p, scope); + let (ns, local) = resolve(&p.name, scope, true).ok_or(XmpError::Malformed)?; + if ns.is_empty() || ns == RDF || ns == XML { + return Err(XmpError::Malformed); + } + let prefix = p.name.split_once(':').map_or("ns", |(p, _)| p); + registry.register(&ns, prefix)?; + let ns = reading.intern(ns); + let duplicate = reading.seen.contains(&(Rc::clone(&ns), local.to_string())); + let own = attrs(p); + let children: Vec<&El> = p.elements().collect(); + let value = if children.is_empty() && own.is_empty() { + Value::Simple { text: text_of(p), uri: false } + } else if let ([], [(k, v)]) = (children.as_slice(), own.as_slice()) + && is_named(k, scope, false, RDF, "resource") + && text_of(p).trim_matches([' ', '\t', '\r', '\n']).is_empty() + { + Value::Simple { text: (*v).to_string(), uri: true } + } else if let (Some(array), true) = (array_of(&children, scope), own.is_empty() && text_of(p).trim_matches([' ', '\t', '\r', '\n']).is_empty()) { + array + } else { + // A written packet puts a property 3 elements deep (`x:xmpmeta`, `rdf:RDF`, + // `rdf:Description`), which may be deeper than the packet read put it. + if PROPERTY_DEPTH + height(p) > MAX_DEPTH { + return Err(XmpError::TooLarge); + } + register_names(p, scope, registry)?; + register_nested(p, scope, registry)?; + let available = if duplicate { usize::MAX } else { reading.budget.saturating_sub(reading.bytes).saturating_sub(96 + ns.len() + local.len()) }; + other(p, &own, &children, scope, mark, (available, reading.retain_fragments && !duplicate))? + }; + scope.truncate(mark); + Ok(Prop { ns, name: local.to_string(), value }) +} + +/// Registers the namespaces of the name and the attributes of `el`, with `scope` holding the +/// bindings in scope there, other than RDF, XML and no namespace. A prefix nothing declares makes +/// the packet malformed. +fn register_names(el: &El, scope: &Scope, registry: &mut Registry) -> Result<(), XmpError> { + let names = std::iter::once((el.name.as_str(), true)).chain(attrs(el).into_iter().map(|(k, _)| (k, false))); + for (name, element) in names { + let (ns, _) = resolve(name, scope, element).ok_or(XmpError::Malformed)?; + if !ns.is_empty() && ns != RDF && ns != XML { + registry.register(&ns, name.split_once(':').map_or("ns", |(p, _)| p))?; + } + } + Ok(()) +} + +/// Registers the namespaces the elements inside `el` use, as [`register_names`] does. +fn register_nested(el: &El, scope: &mut Scope, registry: &mut Registry) -> Result<(), XmpError> { + for c in el.elements() { + let mark = scope.len(); + push_decls(c, scope); + let r = register_names(c, scope, registry).and_then(|()| register_nested(c, scope, registry)); + scope.truncate(mark); + r?; + } + Ok(()) +} + +/// The elements a written packet holds around a property. +const PROPERTY_DEPTH: usize = 3; + +/// The elements `el` nests, itself included. +fn height(el: &El) -> usize { + 1 + el.elements().map(height).max().unwrap_or(0) +} + +/// The array of simple items the only child of a property element holds, when it is one. +fn array_of(children: &[&El], scope: &mut Scope) -> Option { + let [container] = children else { return None }; + let mark = scope.len(); + push_decls(container, scope); + let form = [Form::Bag, Form::Seq, Form::Alt].into_iter().find(|f| is_named(&container.name, scope, true, RDF, &f.element()[4..])); + let mut items = Vec::new(); + let ok = form.is_some() && attrs(container).is_empty() && text_of(container).trim_matches([' ', '\t', '\r', '\n']).is_empty() && { + container.elements().all(|li| { + let inner = scope.len(); + push_decls(li, scope); + let mut lang = None; + let mut simple = is_named(&li.name, scope, true, RDF, "li") && li.elements().next().is_none(); + for (k, v) in attrs(li) { + if is_named(k, scope, false, XML, "lang") { + lang = Some(v.to_string()); + } else { + simple = false; + } + } + scope.truncate(inner); + if simple { + items.push(Item { text: text_of(li), lang }); + } + simple + }) + }; + scope.truncate(mark); + match (ok, form) { + (true, Some(form)) => Some(Value::Array { form, items }), + _ => None, + } +} + +/// A value kept as the XML it was read as, refused when the element written for it would hold more +/// than [`MAX_ATTRS`] attributes or declarations in scope, which a packet could then not read back. +fn other(p: &El, own: &[(&str, &str)], children: &[&El], scope: &mut Scope, mark: usize, (budget, keep): (usize, bool)) -> Result { + let (options, text) = match qualified_value(own, children, scope) { + Some(found) => found, + None => kept_form(p, own, children, scope), + }; + let mut xml = Fragment { text: String::new(), bytes: 0, budget: budget.saturating_sub(text.as_ref().map_or(0, String::len)), keep }; + let added = write_fragment(p, scope.get(..mark).unwrap_or(&[]), &mut xml)?; + let decls = added + nested_decls(p); + if p.attrs.len() + added > MAX_ATTRS || decls > MAX_ATTRS { + return Err(XmpError::TooLarge); + } + Ok(Value::Other { xml: xml.text, expanded_bytes: xml.bytes, options, text, decls }) +} + +/// The most namespace declarations `el` and the elements inside it put in scope at one element. +fn nested_decls(el: &El) -> usize { + el.ns_decls().count() + el.elements().map(nested_decls).max().unwrap_or(0) +} + +/// The array form of the container `el`, read with the prefixes it declares itself. +fn container_form(el: &El, scope: &mut Scope) -> Option
{ + let inner = scope.len(); + push_decls(el, scope); + let form = [Form::Bag, Form::Seq, Form::Alt].into_iter().find(|f| is_named(&el.name, scope, true, RDF, &f.element()[4..])); + scope.truncate(inner); + form +} + +/// The options and text of a kept value that is not in the `rdf:value` form. +fn kept_form(p: &El, own: &[(&str, &str)], children: &[&El], scope: &mut Scope) -> (u32, Option) { + let form = children.first().and_then(|c| container_form(c, scope)); + let resource = own.iter().find(|(k, _)| is_named(k, scope, false, RDF, "resource")).map(|(_, v)| (*v).to_string()); + let lang = own.iter().any(|(k, _)| is_named(k, scope, false, XML, "lang")); + // An empty property element whose attributes are fields is a structure. + let fields = own.iter().any(|(k, _)| resolve(k, scope, false).is_some_and(|(ns, _)| !ns.is_empty() && ns != RDF && ns != XML)); + match form { + Some(f) if children.len() == 1 => (f.options() | PROP_HAS_QUALIFIERS, None), + _ if !children.is_empty() || own.iter().any(|(k, _)| is_named(k, scope, false, RDF, "parseType")) => (PROP_IS_STRUCT, None), + _ if fields && resource.is_none() && !p.children.iter().any(is_stray_text) => (PROP_IS_STRUCT, None), + _ => { + let uri = if resource.is_some() { PROP_VALUE_IS_URI } else { 0 }; + (PROP_HAS_QUALIFIERS | uri | if lang { PROP_HAS_LANG } else { 0 }, Some(resource.unwrap_or_else(|| text_of(p)))) + } + } +} + +/// The options and text of a value with qualifiers in the `rdf:value` form (XMP Specification +/// Part 1, 7.9.2.5): `rdf:value` and the qualifiers are the fields of the property, written with +/// `rdf:parseType="Resource"`, in its one `rdf:Description`, or as the attributes of an empty +/// property element. `None` for a value in another form. +fn qualified_value(own: &[(&str, &str)], children: &[&El], scope: &mut Scope) -> Option<(u32, Option)> { + let lang = if own.iter().any(|(k, _)| is_named(k, scope, false, XML, "lang")) { PROP_HAS_LANG | PROP_HAS_QUALIFIERS } else { 0 }; + let resource_type = own.iter().any(|(k, v)| is_named(k, scope, false, RDF, "parseType") && *v == "Resource"); + let found = if children.is_empty() || resource_type { + value_field(children, own, scope) + } else if let [d] = children { + let mark = scope.len(); + push_decls(d, scope); + let found = if is_named(&d.name, scope, true, RDF, "Description") { + let fields: Vec<&El> = d.elements().collect(); + value_field(&fields, &attrs(d), scope) + } else { + None + }; + scope.truncate(mark); + found + } else { + None + }; + found.map(|(options, text)| (options | lang, text)) +} + +/// The options and text the `rdf:value` among the field elements `fields` and the attributes +/// `held` of one structure gives; the other fields and the attributes outside the RDF namespace +/// are its qualifiers. +fn value_field(fields: &[&El], held: &[(&str, &str)], scope: &mut Scope) -> Option<(u32, Option)> { + let is_rdf = |k: &str, scope: &Scope| resolve(k, scope, false).is_some_and(|(ns, _)| ns == RDF); + let lang_in = |list: &[(&str, &str)], scope: &Scope| list.iter().any(|(k, _)| is_named(k, scope, false, XML, "lang")); + let mut qualifiers = held.iter().any(|(k, _)| !is_rdf(k, scope)); + let mut lang = lang_in(held, scope); + if let Some((_, text)) = held.iter().find(|(k, _)| is_named(k, scope, false, RDF, "value")) { + qualifiers |= !fields.is_empty(); + return Some((option_bits(0, qualifiers, lang), Some((*text).to_string()))); + } + let at = fields.iter().position(|f| { + let mark = scope.len(); + push_decls(f, scope); + let found = is_named(&f.name, scope, true, RDF, "value"); + scope.truncate(mark); + found + })?; + let value = fields.get(at)?; + qualifiers |= fields.len() > 1; + let mark = scope.len(); + push_decls(value, scope); + let own = attrs(value); + lang |= lang_in(&own, scope); + let resource = own.iter().find(|(k, _)| is_named(k, scope, false, RDF, "resource")).map(|(_, v)| (*v).to_string()); + let inner: Vec<&El> = value.elements().collect(); + let found = match inner.as_slice() { + [] => match resource { + Some(uri) => (PROP_VALUE_IS_URI, Some(uri)), + None => (0, Some(text_of(value))), + }, + [c] => match container_form(c, scope) { + Some(f) => (f.options(), None), + None => (PROP_IS_STRUCT, None), + }, + _ => (PROP_IS_STRUCT, None), + }; + scope.truncate(mark); + Some((option_bits(found.0, qualifiers, lang), found.1)) +} + +/// `options` with [`PROP_HAS_QUALIFIERS`] when the value has `qualifiers`, and with +/// [`PROP_HAS_LANG`] as well when one of them is `xml:lang`. +fn option_bits(options: u32, qualifiers: bool, lang: bool) -> u32 { + let qualifiers = if qualifiers || lang { PROP_HAS_QUALIFIERS } else { 0 }; + options | qualifiers | if lang { PROP_HAS_LANG } else { 0 } +} + +#[cfg(test)] +std::thread_local! { + static FRAGMENT_BYTES_WRITTEN: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +struct Fragment { + text: String, + bytes: usize, + budget: usize, + keep: bool, +} + +impl Fragment { + fn push(&mut self, text: &str) -> Result<(), XmpError> { + if text.len() > self.budget.saturating_sub(self.bytes) { + return Err(XmpError::Heap); + } + self.bytes += text.len(); + if self.keep { + self.text.push_str(text); + #[cfg(test)] + FRAGMENT_BYTES_WRITTEN.with(|bytes| bytes.set(bytes.get() + text.len())); + } + Ok(()) + } + + fn escaped(&mut self, text: &str, attribute: bool) -> Result<(), XmpError> { + let mut escaped = String::new(); + for character in text.chars() { + let mut buffer = [0; 4]; + let character = character.encode_utf8(&mut buffer); + if attribute { + craft_xml::push_esc_attr(&mut escaped, character); + } else { + craft_xml::push_esc(&mut escaped, character); + } + self.push(&escaped)?; + escaped.clear(); + } + Ok(()) + } +} + +/// Writes `p` and its inherited namespace bindings within the remaining property budget. +fn write_fragment(p: &El, outer: &[(String, String)], out: &mut Fragment) -> Result { + let mut used: Vec = Vec::new(); + collect_prefixes(p, &mut used); + let own: Vec<&str> = p.ns_decls().map(|(prefix, _)| prefix).collect(); + out.push("<")?; + out.push(&p.name)?; + let mut added = 0; + for prefix in used.iter().filter(|u| !own.contains(&u.as_str())) { + if let Some((_, uri)) = outer.iter().rev().find(|(q, _)| q == prefix) { + added += 1; + if prefix.is_empty() { + out.push(" xmlns=\"")?; + } else { + out.push(" xmlns:")?; + out.push(prefix)?; + out.push("=\"")?; + } + out.escaped(uri, true)?; + out.push("\"")?; + } + } + write_rest(p, out)?; + Ok(added) +} + +/// The prefixes the names of `el` and the elements inside it use, `""` for an unprefixed element. +fn collect_prefixes(el: &El, used: &mut Vec) { + let mut add = |prefix: &str| { + if prefix != "xml" && !used.iter().any(|u| u == prefix) { + used.push(prefix.to_string()); + } + }; + add(el.name.split_once(':').map_or("", |(p, _)| p)); + for (k, _) in &el.attrs { + if let Some((p, _)) = k.split_once(':') + && p != "xmlns" + { + add(p); + } + } + for c in el.elements() { + collect_prefixes(c, used); + } +} + +/// Writes the attributes, the children and the end tag of `el`, whose name is already written. +fn write_rest(el: &El, out: &mut Fragment) -> Result<(), XmpError> { + for (k, v) in &el.attrs { + out.push(" ")?; + out.push(k)?; + out.push("=\"")?; + out.escaped(v, true)?; + out.push("\"")?; + } + if el.children.is_empty() { + return out.push("/>"); + } + out.push(">")?; + for n in &el.children { + match n { + Node::El(c) => { + out.push("<")?; + out.push(&c.name)?; + write_rest(c, out)?; + } + Node::Text(t) | Node::CData(t) => out.escaped(t, false)?, + Node::Pi { .. } | Node::Comment(_) => {} + } + } + out.push("") +} + +/// Text written while keeping to [`MAX_BYTES`]. +struct Out(String); + +impl Out { + fn push(&mut self, s: &str) -> Result<(), XmpError> { + if self.0.len().saturating_add(s.len()) > MAX_BYTES { + return Err(XmpError::TooLarge); + } + self.0.push_str(s); + Ok(()) + } + + fn text(&mut self, s: &str) -> Result<(), XmpError> { + self.push(&craft_xml::esc(s)) + } + + fn attr(&mut self, s: &str) -> Result<(), XmpError> { + self.push(&craft_xml::esc_attr(s)) + } +} + +/// `meta` as an XMP packet: the `x:xmpmeta` element inside a writable packet wrapper, or alone +/// without `wrapper`. +pub(crate) fn serialize(meta: &Meta, registry: &Registry, wrapper: bool) -> Result { + let mut namespaces: Vec<(&str, &str)> = Vec::new(); + let mut declared = HashSet::new(); + for p in &meta.props { + if matches!(p.value, Value::Other { .. }) || !declared.insert(&*p.ns) { + continue; + } + let prefix = registry.prefix_of(&p.ns).ok_or(XmpError::BadName)?; + namespaces.push((prefix, &*p.ns)); + } + // A read takes at most `MAX_ATTRS` declarations in scope at one element: those of `x:xmpmeta` + // and `rdf:RDF`, a declaration on `rdf:Description` for each namespace, and the declarations of a + // kept value. + let around = 2 + namespaces.len(); + let kept = meta.props.iter().map(|p| if let Value::Other { decls, .. } = p.value { decls } else { 0 }).max().unwrap_or(0); + if around + kept > MAX_ATTRS { + return Err(XmpError::TooLarge); + } + let prefix = |ns: &str| registry.prefix_of(ns).ok_or(XmpError::BadName); + let mut out = Out(String::new()); + if wrapper { + out.push(&format!("\n"))?; + } + out.push(&format!("\n \n \n")?; + for p in &meta.props { + match &p.value { + Value::Simple { text, uri: false } => { + let name = format!("{}:{}", prefix(&p.ns)?, p.name); + out.push(&format!(" <{name}>"))?; + out.text(text)?; + out.push(&format!("\n"))?; + } + Value::Simple { text, uri: true } => { + out.push(&format!(" <{}:{} rdf:resource=\"", prefix(&p.ns)?, p.name))?; + out.attr(text)?; + out.push("\"/>\n")?; + } + Value::Array { form, items } => { + let name = format!("{}:{}", prefix(&p.ns)?, p.name); + out.push(&format!(" <{name}>\n <{}>\n", form.element()))?; + for item in items { + out.push(" ")?; + out.text(&item.text)?; + out.push("\n")?; + } + out.push(&format!(" \n \n", form.element()))?; + } + Value::Other { xml, .. } => { + out.push(" ")?; + out.push(xml)?; + out.push("\n")?; + } + } + } + out.push(" \n \n")?; + if wrapper { + out.push("\n")?; + } + Ok(out.0) +} + +/// Where a packet lies in a file's bytes: from the start of its ``, and whether its wrapper marks it writable (`end="w"`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PacketSpan { + pub start: usize, + pub end: usize, + pub writeable: bool, +} + +/// The characters of whitespace padding just before the ` usize { + let options = Options { names: Names::AsWritten, doctype: Doctype::Reject, unknown_entity: UnknownEntity::Error, ..Options::default() }.strict(); + let mut events = options.events(packet.as_bytes()); + let (mut depth, mut rooted, mut begun) = (0usize, false, false); + loop { + let event = match events.next() { + Ok(Some(event)) => Ok(event), + Ok(None) => break, + Err(error) => Err(error), + }; + match event { + Ok(craft_xml::Event::Start { .. }) => depth += 1, + Ok(craft_xml::Event::End { .. }) => { + depth = depth.saturating_sub(1); + rooted |= depth == 0; + } + Ok(craft_xml::Event::Pi { target, data }) if depth == 0 && target == "xpacket" => { + if !rooted && data.starts_with("begin=") { + begun = [format!("id=\"{WRAPPER_ID}\""), format!("id='{WRAPPER_ID}'")].iter().any(|id| data.contains(id)); + } else if rooted + && begun + && matches!(data.trim_end_matches([' ', '\t', '\r', '\n']), "end=\"r\"" | "end=\"w\"" | "end='r'" | "end='w'") + { + let before = &packet[..events.span().start]; + return before.len() - before.trim_end_matches([' ', '\t', '\r', '\n']).len(); + } + } + Err(_) => return 0, + _ => {} + } + } + 0 +} + +/// The first UTF-8 packet in `bytes` that has both ends of its wrapper (XMP Specification Part 1, +/// 7.3), or `None`. A start is a ` Option { + const BEGIN: &[u8] = b""), (b"")]; + let len = bytes.len(); + let rest = |at: usize| bytes.get(at..).unwrap_or_default(); + let ids = [format!("id=\"{WRAPPER_ID}\""), format!("id='{WRAPPER_ID}'")]; + let is_start = |at: usize| { + rest(at).starts_with(BEGIN) && { + let head = bytes.get(at..len.min(at.saturating_add(MAX_HEADER))).unwrap_or_default(); + let head = head.windows(2).position(|w| w == b"?>").and_then(|close| head.get(..close)).unwrap_or_default(); + ids.iter().any(|id| head.windows(id.len()).any(|w| w == id.as_bytes())) + } + }; + // Every start, in order. + let starts: Vec = bytes.windows(BEGIN.len()).enumerate().filter(|(at, w)| *w == BEGIN && is_start(*at)).map(|(at, _)| at).collect(); + let start_after = |from: usize| starts.get(starts.partition_point(|&s| s < from)).copied(); + let mut ends = Later::new(END); + let mut closes = Later::new(b"?>"); + let mut section_ends = SECTIONS.map(|(_, close)| Later::new(close)); + let mut start = None; + let mut skipped_headers = Vec::new(); + let mut ignored_sections = std::collections::BTreeMap::new(); + let mut xml_trailer = None; + let mut pos = 0; + while let Some(at) = rest(pos).iter().position(|&b| b == b'<').map(|i| i + pos) { + pos = at + 1; + let here = rest(at); + if here.starts_with(b" close)) { + if start.is_some() + && let Some(close) = close + { + let first = starts.partition_point(|&begin| begin < at + 2); + let end = starts.partition_point(|&begin| begin < close); + skipped_headers.extend_from_slice(&starts[first..end]); + } + pos = close.map_or(len, |close| close + 2); + continue; + } + } + if starts.binary_search(&at).is_ok() { + if let Some(from) = start { + if xml_trailer.as_ref().is_none_or(|(checked, _)| *checked != from) { + xml_trailer = Some((from, packet_trailer(&bytes[from..]))); + } + if let Some((_, Ok((_, end, _)))) = xml_trailer + && at < from + end + { + pos = at + BEGIN.len(); + continue; + } + } + start = Some(at); + skipped_headers.clear(); + pos = at + BEGIN.len(); + continue; + } + let Some(from) = start else { + // Nothing before the next start matters. + pos = start_after(pos)?; + continue; + }; + if let Some(kind) = SECTIONS.iter().position(|(open, _)| here.starts_with(open)) { + let (open, close) = SECTIONS[kind]; + let inside = at + open.len(); + let end = section_ends[kind].find(bytes, inside); + // A trailer and then a start inside the section belong to packets of their own. + let hides_packet = end.is_some_and(|end| ends.find(bytes, inside).is_some_and(|e| e < end && start_after(e).is_some_and(|s| s < end))); + if let (Some(end), false) = (end, hides_packet) { + pos = end + close.len(); + ignored_sections.insert(at, pos); + } + continue; + } + if !here.starts_with(END) { + continue; + } + let after = at + END.len(); + let close = closes.find(bytes, after)?; + if let Some(next) = start_after(after).filter(|&next| next < close) { + start = Some(next); + skipped_headers.clear(); + pos = next + BEGIN.len(); + continue; + } + let trailer_value = std::str::from_utf8(&bytes[after..close]).ok().map(|value| value.trim_end_matches([' ', '\t', '\r', '\n'])); + if !matches!(trailer_value, Some("\"r\"" | "\"w\"" | "'r'" | "'w'")) { + pos = close + 2; + continue; + } + if xml_trailer.as_ref().is_none_or(|(checked, _)| *checked != from) { + xml_trailer = Some((from, packet_trailer(&bytes[from..]))); + } + if let Some((_, Err(Some(next)))) = xml_trailer { + start = Some(from + next); + skipped_headers.clear(); + pos = from + next + BEGIN.len(); + continue; + } + if let Some((_, Ok((trailer, _, _)))) = xml_trailer + && from + trailer > at + { + pos = from + trailer; + continue; + } + let span = PacketSpan { start: from, end: close + 2, writeable: bytes.get(after + 1) == Some(&b'w') }; + let packet = bytes.get(span.start..span.end)?; + if std::str::from_utf8(packet).is_ok() { + let mut selected = span.start; + if !skipped_headers.is_empty() { + while let Some(restart) = packet_xml_restart(&bytes[selected..span.end]) { + let threshold = selected.saturating_add(restart); + let index = skipped_headers.partition_point(|&header| header <= selected || header < threshold); + let Some(next) = skipped_headers.get(index).copied().filter(|&header| header < span.end) else { break }; + selected = next; + } + } + let trailer = if selected == from { xml_trailer.map_or(Err(None), |(_, trailer)| trailer) } else { packet_trailer(&bytes[selected..]) }; + if let Ok((_, end, writeable)) = trailer { + return Some(PacketSpan { start: selected, end: selected + end, writeable }); + } + if let Err(Some(next)) = trailer { + start = Some(selected + next); + skipped_headers.clear(); + pos = selected + next + BEGIN.len(); + continue; + } + return Some(PacketSpan { start: selected, ..span }); + } + let mut checked = span.start; + let mut last_invalid = span.start; + while let Err(error) = std::str::from_utf8(&bytes[checked..span.end]) { + checked += error.valid_up_to() + error.error_len().unwrap_or(1); + last_invalid = checked; + } + let next = starts[starts.partition_point(|&header| header < last_invalid)..] + .iter() + .copied() + .take_while(|&header| header < span.end) + .find(|&header| ignored_sections.range(..=header).next_back().is_none_or(|(_, &end)| header >= end)); + if let Some(next) = next { + start = Some(next); + skipped_headers.clear(); + pos = next + BEGIN.len(); + continue; + } + start = None; + pos = span.end; + } + None +} + +fn packet_trailer(packet: &[u8]) -> Result<(usize, usize, bool), Option> { + let options = Options { names: Names::AsWritten, doctype: Doctype::Reject, unknown_entity: UnknownEntity::Literal, ..Options::default() }; + let mut events = options.events(packet); + let mut depth = 0usize; + let ids = [format!("id=\"{WRAPPER_ID}\""), format!("id='{WRAPPER_ID}'")]; + while let Some(event) = events.next().map_err(|_| None)? { + let span = events.span(); + #[cfg(test)] + PACKET_XML_READ_BYTES.with(|bytes| bytes.set(bytes.get() + span.len())); + match event { + craft_xml::Event::Start { .. } => depth += 1, + craft_xml::Event::End { .. } => { + depth = depth.saturating_sub(1); + } + craft_xml::Event::Pi { target, data } if depth == 0 && target == "xpacket" => { + if span.start != 0 && span.len() <= MAX_HEADER && data.starts_with("begin=") && ids.iter().any(|id| data.contains(id)) { + return Err(Some(span.start)); + } + match data.trim_end_matches([' ', '\t', '\r', '\n']) { + "end=\"r\"" | "end='r'" => return Ok((span.start, span.end, false)), + "end=\"w\"" | "end='w'" => return Ok((span.start, span.end, true)), + _ => {} + } + } + _ => {} + } + } + Err(None) +} + +#[cfg(test)] +std::thread_local! { + pub(crate) static PACKET_XML_READ_BYTES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +fn packet_xml_restart(packet: &[u8]) -> Option { + let options = Options { names: Names::AsWritten, doctype: Doctype::Reject, unknown_entity: UnknownEntity::Error, ..Options::default() }.strict(); + let mut events = options.events(packet); + let mut open = Vec::new(); + let mut complete = None; + loop { + let event = match events.next() { + Ok(Some(event)) => Ok(event), + Ok(None) => break, + Err(error) => Err(error), + }; + let span = events.span(); + #[cfg(test)] + PACKET_XML_READ_BYTES.with(|bytes| bytes.set(bytes.get() + span.len())); + match event { + Ok(craft_xml::Event::Start { .. }) => open.push(span.start), + Ok(craft_xml::Event::End { .. }) => { + open.pop(); + if open.is_empty() { + complete = Some(span.end); + } + } + Err(_) => { + return Some(if span.start == packet.len() { + open.last().map_or(span.end, |start| start + 1) + } else if open.is_empty() { + complete.unwrap_or(span.end) + } else { + span.end + }); + } + _ => {} + } + } + None +} + +/// The next place of a marker at or after a given point. While the points do not go back, each +/// search starts past the last one, so the searches together read the bytes about once. +struct Later { + marker: &'static [u8], + /// The point of the last search, and what it found. + from: usize, + found: Option, +} + +impl Later { + fn new(marker: &'static [u8]) -> Later { + Later { marker, from: usize::MAX, found: None } + } + + fn find(&mut self, bytes: &[u8], from: usize) -> Option { + if self.from <= from && self.found.is_none_or(|f| f >= from) { + return self.found; + } + self.from = from; + self.found = bytes.get(from..).and_then(|r| r.windows(self.marker.len()).position(|w| w == self.marker)).map(|i| i + from); + self.found + } +} + +#[cfg(test)] +mod fragment_budget_tests { + use super::*; + + #[test] + fn expanded_namespace_fragments_stop_before_exceeding_the_heap_budget() { + let mut declarations = String::new(); + let mut fields = String::new(); + for index in 0..16 { + declarations.push_str(&format!(" xmlns:n{index}=\"urn:{index}:{}\"", "x".repeat(950))); + fields.push_str(&format!("value")); + } + let packet = format!( + "{fields}" + ); + let budget = 4096; + FRAGMENT_BYTES_WRITTEN.with(|bytes| bytes.set(0)); + assert_eq!(parse_within(&packet, &mut Registry::default(), budget), Err(XmpError::Heap)); + let written = FRAGMENT_BYTES_WRITTEN.with(std::cell::Cell::get); + assert!(written <= budget, "expanded fragment wrote {written} bytes with a {budget}-byte budget"); + let meta = parse_within(&packet, &mut Registry::default(), 64 * 1024).unwrap(); + assert!(meta.props[0].heap_bytes() > budget, "the valid control expands inherited namespace bindings"); + FRAGMENT_BYTES_WRITTEN.with(|bytes| bytes.set(0)); + validate_within(&packet, &mut Registry::default(), 64 * 1024).unwrap(); + assert_eq!(FRAGMENT_BYTES_WRITTEN.with(std::cell::Cell::get), 0, "validation must not retain fragment strings"); + let duplicate = packet.replacen("first, +//! and +//! describe them, +//! as built-ins ([`crate::Realm::define_external_object`]). The metadata itself is +//! [`crate::xmp`]. +//! +//! `new ExternalObject("lib:AdobeXMPScript")` defines the globals `XMPMeta`, `XMPFile` and +//! `XMPConst` and gives a handle whose `terminate()` releases it; the globals and the objects made +//! with them stay. Any other library name throws an `Error`, and no native code is loaded. +//! `ExternalObject.search(name)` is true for that name alone. +//! +//! `XMPMeta` holds its metadata in its object. Its namespace prefixes are the realm's: those a +//! packet declares are registered when it is read, and `XMPMeta.registerNamespace` adds others. +//! `getNamespacePrefix` and `registerNamespace` give a prefix with its colon. Property paths are a +//! name, `prefix:name`, and either with `[n]` (from 1) or `[last()]` for an array item. An array +//! property holds simple items; any other value a packet holds is kept as it was written and +//! `getProperty` gives its text, when it has one, and its options. +//! `insertArrayItem` inserts before the last existing item when its index is `ARRAY_LAST_ITEM`. +//! `insertArrayItem` and `setArrayItem` store `null` as an empty item value. +//! Metadata edits charge fuel for size accounting. +//! +//! `XMPFile` reads a file through the host functions `xmpOpen` and `xmpWrite` of `File` and +//! `Folder` ([`crate::Realm::define_file_classes`]), so it reads and writes only where they may. A +//! file named `.xmp` is read whole as a packet, and any other file, or any file with +//! `OPEN_USE_PACKET_SCANNING`, is scanned for its first packet ([`crate::xmp::find_packet`]). +//! `putXMP` keeps the packet and `closeFile` writes it. +//! +//! VectorCraft's own rules: only a `.xmp` file opened with `OPEN_FOR_UPDATE` takes `putXMP`; +//! `closeFile` always replaces the file through a temporary one when the folder may hold one, and +//! with `CLOSE_UPDATE_SAFELY` it writes no other way, throwing and keeping the packet instead; an +//! `XMPFile` is open only in the file run that opened it. Closing it successfully or beginning +//! another file run with `Realm::reset_folder_current` releases its packet buffers. A member the +//! reference lists that is not built yet, and a flag, format or option not handled yet, throws an +//! error that says so. + +use crate::builtins::arg; +use crate::heap::{Class, ENUMERABLE, HIDDEN, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, PropMap, key, string_bytes}; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::Value; +use crate::xmp::{self, Form, Item, Meta, Registry, Step, XmpError}; + +/// The one library `ExternalObject` loads. +const LIBRARY: &str = "lib:AdobeXMPScript"; // brand-ok: the library name scripts load + +const FILE_UNKNOWN: u32 = 0x2020_2020; +const FILE_TEXT: u32 = 0x7465_7874; +const FILE_XML: u32 = 0x584D_4C20; +const OPEN_FOR_READ: u32 = 0x1; +const OPEN_FOR_UPDATE: u32 = 0x2; +const OPEN_ONLY_XMP: u32 = 0x4; +const OPEN_USE_PACKET_SCANNING: u32 = 0x40; +const CLOSE_UPDATE_SAFELY: u32 = 0x1; +const SERIALIZE_OMIT_PACKET_WRAPPER: u32 = 0x10; + +const LIBRARY_SLOT: &str = "__vcLibrary"; +const PATH: &str = "__vcXmpPath"; +const FORMAT: &str = "__vcXmpFormat"; +const FLAGS: &str = "__vcXmpFlags"; +const RUN: &str = "__vcXmpRun"; +const OPEN: &str = "__vcXmpOpen"; +const PACKET: &str = "__vcXmpPacket"; +const OFFSET: &str = "__vcXmpOffset"; +const LENGTH: &str = "__vcXmpLength"; +const WRITEABLE: &str = "__vcXmpWriteable"; +const SIDECAR: &str = "__vcXmpSidecar"; +const CHAR_FORM: &str = "__vcXmpCharForm"; +const PENDING: &str = "__vcXmpPending"; + +/// The objects of `ExternalObject` and the XMP classes, kept by the realm, and its namespaces. +#[derive(Debug)] +pub(crate) struct Classes { + ids: Ids, + registry: Registry, +} + +#[derive(Clone, Copy, Debug)] +struct Ids { + external_proto: ObjId, + meta: ObjId, + meta_proto: ObjId, + file: ObjId, + file_proto: ObjId, + constants: ObjId, + property_proto: ObjId, +} + +impl Classes { + pub(crate) fn bytes(&self) -> usize { + self.registry.bytes() + } + + /// The objects a collection keeps. + pub(crate) fn objects(&self) -> [ObjId; 7] { + let i = self.ids; + [i.external_proto, i.meta, i.meta_proto, i.file, i.file_proto, i.constants, i.property_proto] + } +} + +fn ids(i: &Interp) -> JsResult { + i.xmp.as_ref().map(|c| c.ids).ok_or_else(|| Abrupt::Internal("ExternalObject is not installed".into())) +} + +fn registry(i: &mut Interp) -> JsResult<&mut Registry> { + i.xmp.as_mut().map(|c| &mut c.registry).ok_or_else(|| Abrupt::Internal("ExternalObject is not installed".into())) +} + +// ---- errors ---- + +fn not_yet(i: &mut Interp, what: &str) -> Abrupt { + i.throw(ErrorType::Error, &format!("{what} is not available yet")) +} + +fn not_handled(i: &mut Interp, what: &str, value: &str) -> Abrupt { + let value = shown(value); + i.throw(ErrorType::Range, &format!("{what}: the value {value} is not available yet")) +} + +fn wrong_object(i: &mut Interp, what: &str, class: &str) -> Abrupt { + i.type_error(&format!("{what}: the object is not an {class} object")) +} + +/// The first 200 characters of `s`, the most of a script's text an error message holds. +fn shown(s: &str) -> String { + s.chars().take(200).collect() +} + +/// The exception for `e`, which `what` met with the name or path `name`. +fn xmp_error(i: &mut Interp, what: &str, e: XmpError, name: &str) -> Abrupt { + let name = shown(name); + match e { + XmpError::Malformed => i.throw(ErrorType::Error, &format!("{what}: the XMP packet is not well-formed XMP")), + XmpError::TooLarge | XmpError::Namespaces => i.throw(ErrorType::Range, &format!("{what}: the XMP data is too large")), + XmpError::BadName => i.throw(ErrorType::Error, &format!("{what}: {name} is not a valid property name")), + XmpError::BadText => i.throw(ErrorType::Error, &format!("{what}: the text holds a character XML does not allow")), + XmpError::NotYet => not_handled(i, what, &name), + XmpError::Heap => Abrupt::Limit(crate::LimitKind::Heap), + } +} + +fn not_array(i: &mut Interp, what: &str, name: &str) -> Abrupt { + let name = shown(name); + i.throw(ErrorType::Error, &format!("{what}: {name} is not an array")) +} + +fn not_simple(i: &mut Interp, what: &str, name: &str) -> Abrupt { + let name = shown(name); + i.throw(ErrorType::Error, &format!("{what}: {name} is not a simple property")) +} + +fn not_alt_text(i: &mut Interp, what: &str, name: &str) -> Abrupt { + let name = shown(name); + i.throw(ErrorType::Error, &format!("{what}: {name} is not a language alternative array")) +} + +fn out_of_range(i: &mut Interp, what: &str, index: i64) -> Abrupt { + i.throw(ErrorType::Range, &format!("{what}: the array index {index} is out of range")) +} + +fn unregistered(i: &mut Interp, what: &str, uri: &str) -> Abrupt { + let uri = shown(uri); + i.throw(ErrorType::Error, &format!("{what}: the namespace {uri} is not registered")) +} + +// ---- small helpers ---- + +fn text(i: &mut Interp, v: &Value) -> JsResult { + Ok(i.to_str(v)?.to_rust_string()) +} + +/// A string argument's value as plain text, refused when it holds a character XML does not allow. +fn xml_text(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let s = text(i, v)?; + if !xmp::is_text(&s) { + return Err(xmp_error(i, what, XmpError::BadText, "")); + } + Ok(s) +} + +/// A flags argument: `undefined` and `null` are 0, any other value a whole number from 0 to +/// 2^32 - 1, refused with a `RangeError` otherwise. +fn flags(i: &mut Interp, v: &Value, what: &str) -> JsResult { + if matches!(v, Value::Undefined | Value::Null) { + return Ok(0); + } + let n = i.to_number(v)?; + if n.fract() != 0.0 || !(0.0..=f64::from(u32::MAX)).contains(&n) { + let shown = crate::number::to_string(n); + return Err(not_handled(i, what, &shown)); + } + Ok(n as u32) +} + +/// Refuses the bits of `value` outside `allowed`, naming the first. +fn only(i: &mut Interp, value: u32, allowed: u32, what: &str) -> JsResult<()> { + let extra = value & !allowed; + if extra != 0 { + let bit = 1u32 << extra.trailing_zeros(); + return Err(not_handled(i, what, &format!("0x{bit:X}"))); + } + Ok(()) +} + +/// Takes fuel for reading or writing `bytes` bytes of XMP. +fn spend(i: &mut Interp, bytes: usize) -> JsResult<()> { + crate::regexp_vm::use_fuel_n(i, 1 + bytes as u64 / 256) +} + +fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { + if let Some(Class::XmpFile(fields)) = i.heap.object(o).map(|object| &object.class) { + return Ok(fields.get(&key(name)).cloned().unwrap_or(Value::Undefined)); + } + Ok(match i.get_own_property(o, &key(name))? { + Some(Prop::Data { value, .. }) => value, + _ => Value::Undefined, + }) +} + +fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { + set_slot_with_charge(i, o, name, value, true) +} + +fn set_slot_with_charge(i: &mut Interp, o: ObjId, name: &str, value: Value, charged: bool) -> JsResult<()> { + if let Some(Class::XmpFile(fields)) = i.heap.object(o).map(|object| &object.class) { + let name = key(name); + let added = if fields.contains(&name) { 0 } else { PROP_BYTES + string_bytes(name.len()) }; + let strings = if charged { + 0 + } else if let Value::String(s) = &value { + string_bytes(s.len()) + } else { + 0 + }; + return i.rooted(&[Value::Object(o), value.clone()], |i| { + i.reserve_heap(added + strings)?; + if let Some(Class::XmpFile(fields)) = i.heap.object_mut(o).map(|object| &mut object.class) { + fields.insert(name, value); + i.heap.bytes = i.heap.bytes.saturating_add(added); + } + Ok(()) + }); + } + if let Value::String(s) = &value { + i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?; + } + i.define(o, key(name), Prop::Data { value, flags: 0 }) +} + +pub(crate) fn reset_file_state(fields: &mut PropMap) { + if let Some(packet) = fields.get_mut(&key(PACKET)) { + *packet = Value::Null; + } + if let Some(pending) = fields.get_mut(&key(PENDING)) { + *pending = Value::Undefined; + } +} + +/// A string value, charged to the heap. +fn string(i: &mut Interp, s: &str) -> JsResult { + let bytes = string_bytes(s.encode_utf16().count()); + i.reserve_heap(bytes)?; + i.heap.bytes = i.heap.bytes.saturating_add(bytes); + Ok(Value::str(s)) +} + +/// A new ordinary object with the prototype `proto` and the read-only data properties `fields`. +fn record(i: &mut Interp, proto: Option, fields: Vec<(&'static str, Value)>) -> JsResult { + i.rooted(&fields.iter().map(|(_, v)| v.clone()).collect::>(), |i| { + let keys: usize = fields.iter().map(|(name, _)| string_bytes(name.encode_utf16().count())).sum(); + i.reserve_heap(OBJECT_BYTES + PROP_BYTES * fields.len() + keys)?; + let o = i.heap.alloc_object(Object::new(Class::Ordinary, proto.or(Some(i.intrinsics.object_proto)))); + for (name, value) in &fields { + i.define(o, key(name), Prop::Data { value: value.clone(), flags: ENUMERABLE })?; + } + Ok(Value::Object(o)) + }) +} + +// ---- ExternalObject ---- + +fn external_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let name = text(i, &arg(args, 0))?; + if name != LIBRARY { + let name = shown(&name); + let what = "ExternalObject"; + return Err(i.throw(ErrorType::Error, &format!("{what}: the library {name} is not available"))); + } + let ids = ids(i)?; + let global = i.global; + i.reserve_heap(OBJECT_BYTES + PROP_BYTES)?; + let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(ids.external_proto))); + i.rooted(&[Value::Object(o)], |i| { + let library = string(i, LIBRARY)?; + data(i, o, LIBRARY_SLOT, library, 0)?; + let members = [("XMPMeta", ids.meta), ("XMPFile", ids.file), ("XMPConst", ids.constants)]; + let mut added = 0; + for (name, _) in members { + if i.get_own_property(global, &key(name))?.is_none() { + added += PROP_BYTES + string_bytes(name.len()); + } + } + i.reserve_heap(added)?; + for (name, value) in members { + crate::builtins::data(i, global, name, Value::Object(value), HIDDEN)?; + } + Ok(()) + })?; + Ok(Value::Object(o)) +} + +fn external_search(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + Ok(Value::Bool(text(i, &arg(args, 0))? == LIBRARY)) +} + +fn external_terminate(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let handle = this.as_object().filter(|&o| matches!(slot(i, o, LIBRARY_SLOT), Ok(Value::String(_)))); + let Some(o) = handle else { return Err(wrong_object(i, "ExternalObject.terminate", "ExternalObject")) }; + set_slot(i, o, LIBRARY_SLOT, Value::Bool(false))?; + Ok(Value::Undefined) +} + +// ---- XMPMeta ---- + +fn is_meta(i: &Interp, v: &Value) -> Option { + v.as_object().filter(|&o| matches!(i.heap.object(o).map(|ob| &ob.class), Some(Class::Xmp(_)))) +} + +fn this_meta(i: &mut Interp, this: &Value, what: &str) -> JsResult { + match is_meta(i, this) { + Some(o) => Ok(o), + None => Err(wrong_object(i, what, "XMPMeta")), + } +} + +fn meta_of(i: &Interp, o: ObjId) -> JsResult<&Meta> { + match i.heap.object(o).map(|ob| &ob.class) { + Some(Class::Xmp(m)) => Ok(m), + _ => Err(Abrupt::Internal("an XMPMeta lost its metadata".into())), + } +} + +/// Changes the metadata of `o` with `f`, given `grow`, the most bytes the change adds, and charges +/// the heap for what it added or frees what it took out. +fn change(i: &mut Interp, o: ObjId, grow: usize, f: impl FnOnce(&mut Meta, &Registry) -> T) -> JsResult { + let accounting = meta_of(i, o)?.heap_bytes().saturating_mul(3).saturating_add(grow); + spend(i, accounting)?; + change_counted(i, o, grow, None, f) +} + +fn change_counted(i: &mut Interp, o: ObjId, grow: usize, delta: Option<(usize, usize)>, f: impl FnOnce(&mut Meta, &Registry) -> T) -> JsResult { + i.reserve_heap(grow)?; + let Some(c) = i.xmp.as_ref() else { return Err(Abrupt::Internal("ExternalObject is not installed".into())) }; + let Some(Class::Xmp(m)) = i.heap.object_mut(o).map(|ob| &mut ob.class) else { + return Err(Abrupt::Internal("an XMPMeta lost its metadata".into())); + }; + let before = delta.map_or_else(|| m.heap_bytes(), |(removed, _)| removed); + let r = f(m, &c.registry); + let after = delta.map_or_else(|| m.heap_bytes(), |(_, added)| added); + i.heap.bytes = if after >= before { i.heap.bytes.saturating_add(after - before) } else { i.heap.bytes.saturating_sub(before - after) }; + Ok(r) +} + +/// A new `XMPMeta` holding `meta`. +fn new_meta(i: &mut Interp, meta: Meta) -> JsResult { + let ids = ids(i)?; + let bytes = meta.heap_bytes(); + i.reserve_heap(OBJECT_BYTES.saturating_add(bytes))?; + let o = i.heap.alloc_object(Object::new(Class::Xmp(Box::new(meta)), Some(ids.meta_proto))); + i.heap.bytes = i.heap.bytes.saturating_add(bytes); + Ok(Value::Object(o)) +} + +/// The metadata of the packet `text`, read for `what`. +fn parse_packet(i: &mut Interp, what: &str, text: &str) -> JsResult { + let mut staged = registry(i)?.clone(); + let copied = staged.bytes(); + spend(i, text.len().saturating_add(2 * copied))?; + i.collect_garbage(); + let budget = i.limits.heap_bytes.saturating_sub(i.heap.bytes).saturating_sub(OBJECT_BYTES); + let meta = xmp::parse_within(text, &mut staged, budget).map_err(|e| xmp_error(i, what, e, ""))?; + let growth = staged.bytes().saturating_sub(copied); + i.reserve_heap(OBJECT_BYTES.saturating_add(meta.heap_bytes()).saturating_add(growth))?; + *registry(i)? = staged; + i.heap.bytes = i.heap.bytes.saturating_add(growth); + Ok(meta) +} + +fn meta_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let meta = match arg(args, 0) { + Value::Undefined => Meta::default(), + Value::Object(o) if matches!(i.heap.object(o).map(|ob| &ob.class), Some(Class::Array { .. })) => { + return Err(not_yet(i, "new XMPMeta(buffer)")); + } + v => { + let packet = text(i, &v)?; + parse_packet(i, "XMPMeta", &packet)? + } + }; + new_meta(i, meta) +} + +/// The namespace argument `v`, refused when it is not registered. +fn namespace(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let uri = text(i, v)?; + if registry(i)?.prefix_of(&uri).is_none() { + return Err(unregistered(i, what, &uri)); + } + Ok(uri) +} + +/// The namespace and path arguments at `at`, each converted once. +struct Target { + ns: String, + /// The property name and its step. + name: String, + step: Step, + /// The path as given. + path: String, +} + +/// The namespace and path arguments at `at`. +fn target(i: &mut Interp, args: &[Value], at: usize, what: &str) -> JsResult { + let ns = namespace(i, &arg(args, at), what)?; + let path = text(i, &arg(args, at + 1))?; + // A packet holds no property in the RDF or XML namespace. + if ns == xmp::RDF || ns == xmp::XML { + return Err(xmp_error(i, what, XmpError::BadName, &path)); + } + let r = xmp::parse_path(&path, &ns, registry(i)?); + match r { + Ok((name, step)) => Ok(Target { ns, name, step, path }), + Err(e) => Err(xmp_error(i, what, e, &path)), + } +} + +/// The index an item position names in an array of `len` items: -1 is the last. +fn position(index: i64, len: usize) -> Option { + let i = if index == -1 { len } else { usize::try_from(index).ok()? }; + (1..=len).contains(&i).then(|| i - 1) +} + +/// An item position argument: a whole number from 1, or -1 for the last. +fn item_index(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let n = i.to_number(v)?; + if n.fract() != 0.0 || !(n == -1.0 || (1.0..=1e15).contains(&n)) { + return Err(out_of_range(i, what, if n.is_finite() { n as i64 } else { 0 })); + } + Ok(n as i64) +} + +/// An `XMPProperty` for `path` in `ns`. +fn property(i: &mut Interp, ns: &str, path: &str, value: Option<&str>, options: u32, locale: &str) -> JsResult { + let proto = ids(i)?.property_proto; + let ns = string(i, ns)?; + let path = i.rooted(std::slice::from_ref(&ns), |i| string(i, path))?; + let value = match value { + Some(v) => i.rooted(&[ns.clone(), path.clone()], |i| string(i, v))?, + None => Value::Undefined, + }; + let locale = i.rooted(&[ns.clone(), path.clone(), value.clone()], |i| string(i, locale))?; + let fields = vec![("namespace", ns), ("path", path), ("value", value), ("options", Value::Number(f64::from(options))), ("locale", locale)]; + record(i, Some(proto), fields) +} + +fn property_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let v = match this.as_object() { + Some(o) => slot(i, o, "value")?, + None => Value::Undefined, + }; + if matches!(v, Value::Undefined) { Ok(Value::str("")) } else { Ok(Value::String(i.to_str(&v)?)) } +} + +fn get_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.getProperty"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, step, path } = target(i, args, 0, what)?; + if !matches!(arg(args, 2), Value::Undefined) { + let v = text(i, &arg(args, 2))?; + return Err(not_handled(i, what, &v)); + } + let found = { + let m = meta_of(i, o)?; + match m.find(&ns, &name).map(|at| &m.props[at].value) { + None => Ok(None), + Some(value) => match step { + Step::Whole => Ok(Some((value.text().map(str::to_string), value.options(), String::new()))), + Step::Item(index) => match value { + xmp::Value::Array { items, .. } => Ok(position(index, items.len()) + .and_then(|p| items.get(p)) + .map(|item| (Some(item.text.clone()), item.options(), item.lang.clone().unwrap_or_default()))), + _ => Err(()), + }, + }, + } + }; + let found = found.map_err(|()| not_array(i, what, &name))?; + let Some((text, options, locale)) = found else { return Ok(Value::Undefined) }; + property(i, &ns, &path, text.as_deref(), options, &locale) +} + +fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.setProperty"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, step, .. } = target(i, args, 0, what)?; + let options = flags(i, &arg(args, 3), what)?; + only(i, options, xmp::PROP_IS_ARRAY | xmp::ARRAY_IS_ORDERED | xmp::ARRAY_IS_ALTERNATIVE, what)?; + if !matches!(arg(args, 4), Value::Undefined) { + let v = text(i, &arg(args, 4))?; + return Err(not_handled(i, what, &v)); + } + let value = arg(args, 2); + if let Step::Item(index) = step { + // An array item is a simple value, which takes no options. + only(i, options, 0, what)?; + let v = xml_text(i, &value, what)?; + return set_item(i, o, &ns, &name, index, v, false, what); + } + if options != 0 { + // An array is made empty; one that exists is left as it is. + if !matches!(value, Value::Undefined | Value::Null) { + let v = text(i, &value)?; + return Err(not_handled(i, what, &v)); + } + let kind = { + let m = meta_of(i, o)?; + m.find(&ns, &name).map(|at| matches!(m.props[at].value, xmp::Value::Array { .. })) + }; + return match kind { + Some(true) => Ok(Value::Undefined), + Some(false) => Err(not_array(i, what, &name)), + None => { + let prop = xmp::Prop { ns: ns.into(), name, value: xmp::Value::Array { form: Form::from_options(options), items: Vec::new() } }; + change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop)).map(|()| Value::Undefined) + } + }; + } + let v = xml_text(i, &value, what)?; + let simple = { + let m = meta_of(i, o)?; + m.find(&ns, &name).map(|at| (at, matches!(m.props[at].value, xmp::Value::Simple { .. }))) + }; + let new = xmp::Value::Simple { text: v, uri: false }; + match simple { + Some((_, false)) => Err(not_simple(i, what, &name)), + Some((at, true)) => { + let grow = 96 + new.text().map_or(0, str::len); + change(i, o, grow, |m, _| { + if let Some(p) = m.props.get_mut(at) { + p.value = new; + } + }) + } + None => { + let prop = xmp::Prop { ns: ns.into(), name, value: new }; + change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop)) + } + } + .map(|()| Value::Undefined) +} + +fn delete_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.deleteProperty"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, step, .. } = target(i, args, 0, what)?; + match step { + Step::Whole => { + let at = meta_of(i, o)?.find(&ns, &name); + if let Some(at) = at { + change(i, o, 0, |m, _| m.props.remove(at))?; + } + Ok(Value::Undefined) + } + Step::Item(index) => delete_item(i, o, &ns, &name, index, what, true), + } +} + +fn does_property_exist(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.doesPropertyExist"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, step, .. } = target(i, args, 0, what)?; + let m = meta_of(i, o)?; + let exists = match (m.find(&ns, &name).map(|at| &m.props[at].value), step) { + (None, _) => false, + (Some(_), Step::Whole) => true, + (Some(xmp::Value::Array { items, .. }), Step::Item(index)) => position(index, items.len()).is_some(), + (Some(_), Step::Item(_)) => false, + }; + Ok(Value::Bool(exists)) +} + +/// The items of the array `name` in `ns` of `o`, `None` when it has no such property, refused when +/// the property is not an array. +fn array_items(i: &mut Interp, o: ObjId, ns: &str, name: &str, what: &str) -> JsResult> { + let found = { + let m = meta_of(i, o)?; + m.find(ns, name).map(|at| match &m.props[at].value { + xmp::Value::Array { form, items } => Some((at, *form, items.len())), + _ => None, + }) + }; + match found { + None => Ok(None), + Some(Some(a)) => Ok(Some(a)), + Some(None) => Err(not_array(i, what, name)), + } +} + +/// The namespace and array name arguments: a whole property. +fn array_target(i: &mut Interp, args: &[Value], what: &str) -> JsResult { + let t = target(i, args, 0, what)?; + if t.step != Step::Whole { + return Err(not_handled(i, what, &t.path)); + } + Ok(t) +} + +fn count_array_items(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.countArrayItems"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + let n = array_items(i, o, &ns, &name, what)?.map_or(0, |(_, _, len)| len); + Ok(Value::Number(n as f64)) +} + +fn get_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.getArrayItem"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, path, .. } = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + let Some((at, _, len)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; + let Some(p) = position(index, len) else { return Ok(Value::Undefined) }; + let item = match &meta_of(i, o)?.props[at].value { + xmp::Value::Array { items, .. } => items.get(p).cloned(), + _ => None, + }; + let Some(item) = item else { return Ok(Value::Undefined) }; + let path = format!("{path}[{}]", p + 1); + property(i, &ns, &path, Some(&item.text), item.options(), item.lang.as_deref().unwrap_or("")) +} + +fn does_array_item_exist(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.doesArrayItemExist"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + let len = array_items(i, o, &ns, &name, what)?.map_or(0, |(_, _, len)| len); + Ok(Value::Bool(position(index, len).is_some())) +} + +/// The item options argument: 0 alone, for a simple item. +fn item_options(i: &mut Interp, v: &Value, what: &str) -> JsResult<()> { + let options = flags(i, v, what)?; + only(i, options, 0, what) +} + +/// Adds `value` to the array `name` in `ns` of `o` at the position `index` (from 1; one past the +/// last appends), making the array in `form` when it has none. +#[allow(clippy::too_many_arguments)] +fn insert_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: Option, value: String, form: Option, what: &str) -> JsResult { + let found = array_items(i, o, ns, name, what)?; + let len = found.map_or(0, |(_, _, len)| len); + let p = match index { + None => len, + Some(-1) => match len.checked_sub(1) { + Some(p) => p, + None => return Err(out_of_range(i, what, -1)), + }, + Some(n) => match usize::try_from(n) { + Ok(n) if (1..=len + 1).contains(&n) => n - 1, + _ => return Err(out_of_range(i, what, n)), + }, + }; + let grow = 48 + value.len(); + spend(i, len.saturating_sub(p).saturating_mul(std::mem::size_of::()))?; + match found { + Some((at, _, _)) => change_counted(i, o, grow, Some((0, grow)), |m, _| { + if let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|pr| &mut pr.value) { + items.insert(p.min(items.len()), Item { text: value, lang: None }); + } + })?, + None => { + let Some(form) = form else { return Err(not_array(i, what, name)) }; + let prop = + xmp::Prop { ns: ns.into(), name: name.to_string(), value: xmp::Value::Array { form, items: vec![Item { text: value, lang: None }] } }; + change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop))?; + } + } + Ok(Value::Undefined) +} + +/// Replaces the item at `index` of the array `name` in `ns` of `o` with `value`, or appends it at +/// one past the last when `append` allows. +#[allow(clippy::too_many_arguments)] +fn set_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: i64, value: String, append: bool, what: &str) -> JsResult { + let Some((at, _, len)) = array_items(i, o, ns, name, what)? else { return Err(not_array(i, what, name)) }; + let p = match position(index, len) { + Some(p) => p, + None if append && usize::try_from(index).is_ok_and(|n| n == len + 1) => { + return insert_item(i, o, ns, name, Some(index), value, None, what); + } + None => return Err(out_of_range(i, what, index)), + }; + let grow = 48 + value.len(); + change(i, o, grow, |m, _| { + if let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|pr| &mut pr.value) + && let Some(item) = items.get_mut(p) + { + item.text = value; + } + })?; + Ok(Value::Undefined) +} + +/// Deletes the item at `index` of the array `name` in `ns` of `o`; a missing item or array is left +/// as it is when `quiet`. +fn delete_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: i64, what: &str, quiet: bool) -> JsResult { + let found = array_items(i, o, ns, name, what)?; + let target = found.and_then(|(at, _, len)| position(index, len).map(|p| (at, p))); + match target { + Some((at, p)) => { + change(i, o, 0, |m, _| { + if let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|pr| &mut pr.value) + && p < items.len() + { + items.remove(p); + } + })?; + Ok(Value::Undefined) + } + None if quiet => Ok(Value::Undefined), + None => Err(out_of_range(i, what, index)), + } +} + +fn append_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.appendArrayItem"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + // Full calls keep their argument positions. Short calls can omit `itemOptions`. + let third = arg(args, 2); + let positional = args.len() >= 5 + || matches!(&third, Value::Number(_) | Value::Undefined) + || (matches!(&third, Value::Null) && matches!(arg(args, 3), Value::String(_))); + let (value, array_options) = if positional { + item_options(i, &third, what)?; + (arg(args, 3), arg(args, 4)) + } else { + (third, arg(args, 3)) + }; + let array_options = flags(i, &array_options, what)?; + only(i, array_options, xmp::PROP_IS_ARRAY | xmp::ARRAY_IS_ORDERED | xmp::ARRAY_IS_ALTERNATIVE, what)?; + let value = if matches!(value, Value::Null | Value::Undefined) { String::new() } else { xml_text(i, &value, what)? }; + let form = (array_options != 0).then(|| Form::from_options(array_options)); + insert_item(i, o, &ns, &name, None, value, form, what) +} + +fn insert_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.insertArrayItem"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + let value = arg(args, 3); + let value = if matches!(value, Value::Null | Value::Undefined) { String::new() } else { xml_text(i, &value, what)? }; + item_options(i, &arg(args, 4), what)?; + insert_item(i, o, &ns, &name, Some(index), value, None, what) +} + +fn set_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.setArrayItem"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + let value = arg(args, 3); + let value = if matches!(value, Value::Null | Value::Undefined) { String::new() } else { xml_text(i, &value, what)? }; + item_options(i, &arg(args, 4), what)?; + set_item(i, o, &ns, &name, index, value, true, what) +} + +fn delete_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.deleteArrayItem"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + delete_item(i, o, &ns, &name, index, what, false) +} + +/// Does language tag `lang` match `want`, ignoring case? +fn same_lang(lang: Option<&str>, want: &str) -> bool { + lang.is_some_and(|l| l.eq_ignore_ascii_case(want)) +} + +/// Is language tag `lang` the language `generic`, or one of its variants (`generic-…`), ignoring +/// case? Never for an empty `generic`. +fn generic_lang(lang: Option<&str>, generic: &str) -> bool { + !generic.is_empty() + && lang.is_some_and(|l| { + l.eq_ignore_ascii_case(generic) + || l.len() > generic.len() + && l.get(..generic.len()).is_some_and(|p| p.eq_ignore_ascii_case(generic)) + && l.as_bytes().get(generic.len()) == Some(&b'-') + }) +} + +/// The item of `items` for `specific`, else one whose language starts with `generic`, else the +/// `x-default` item, else the first. +fn pick_lang<'a>(items: &'a [Item], generic: &str, specific: &str) -> Option<&'a Item> { + items + .iter() + .find(|i| same_lang(i.lang.as_deref(), specific)) + .or_else(|| items.iter().find(|i| generic_lang(i.lang.as_deref(), generic))) + .or_else(|| items.iter().find(|i| same_lang(i.lang.as_deref(), "x-default"))) + .or_else(|| items.first()) +} + +/// A language argument: `null` and `undefined` are empty. +fn lang(i: &mut Interp, v: &Value, what: &str) -> JsResult { + if matches!(v, Value::Null | Value::Undefined) { Ok(String::new()) } else { xml_text(i, v, what) } +} + +/// Is the property at `at` of `o` a language alternative: an `rdf:Alt` whose items, if it has any, +/// all have a language? An item with `xml:lang=""` has none. +fn is_alt_text(i: &Interp, o: ObjId, at: usize) -> JsResult { + Ok(match meta_of(i, o)?.props.get(at).map(|p| &p.value) { + Some(xmp::Value::Array { form: Form::Alt, items }) => items.iter().all(Item::has_lang), + _ => false, + }) +} + +fn get_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.getLocalizedText"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + let generic = lang(i, &arg(args, 2), what)?; + let specific = lang(i, &arg(args, 3), what)?; + let Some((at, _, len)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; + spend(i, len.saturating_mul(std::mem::size_of::()).saturating_mul(6))?; + let language_bytes = match &meta_of(i, o)?.props[at].value { + xmp::Value::Array { items, .. } => items.iter().fold(0usize, |bytes, item| bytes.saturating_add(item.lang.as_ref().map_or(0, String::len))), + _ => 0, + }; + spend(i, language_bytes.saturating_mul(3))?; + if !is_alt_text(i, o, at)? { + return Err(not_alt_text(i, what, &name)); + } + let found = match &meta_of(i, o)?.props[at].value { + xmp::Value::Array { items, .. } => pick_lang(items, &generic, &specific).cloned(), + _ => None, + }; + match found { + Some(item) => property(i, "", "", Some(&item.text), item.options(), item.lang.as_deref().unwrap_or("")), + None => Ok(Value::Undefined), + } +} + +fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.setLocalizedText"; + let o = this_meta(i, &this, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; + let generic = lang(i, &arg(args, 2), what)?; + let specific = lang(i, &arg(args, 3), what)?; + if specific.is_empty() || specific.contains(char::is_whitespace) { + return Err(not_handled(i, what, &specific)); + } + let value = xml_text(i, &arg(args, 4), what)?; + let found = array_items(i, o, &ns, &name, what)?; + // A new array is added in the same change that sets its item, so a refused change adds nothing. + let (at, new) = match found { + Some((at, _, _)) if !is_alt_text(i, o, at)? => return Err(not_alt_text(i, what, &name)), + Some((at, _, _)) => (Some(at), None), + None => (None, Some(xmp::Prop { ns: ns.into(), name, value: xmp::Value::Array { form: Form::Alt, items: Vec::new() } })), + }; + // An item and the `x-default` item change, or every item with the text of the `x-default` one. + let changed = match at.and_then(|at| meta_of(i, o).ok()?.props.get(at)).map(|p| &p.value) { + Some(xmp::Value::Array { items, .. }) if specific.eq_ignore_ascii_case("x-default") => { + let old = items.iter().find(|i| same_lang(i.lang.as_deref(), "x-default")).map(|i| &i.text); + items.iter().filter(|i| Some(&i.text) == old).count().max(2) + } + _ => 2, + }; + let grow = changed.saturating_mul(64 + value.len() + specific.len()).saturating_add(new.as_ref().map_or(0, xmp::Prop::heap_bytes)); + change(i, o, grow, |m, _| { + let at = match new { + Some(prop) => { + m.props.push(prop); + m.props.len() - 1 + } + None => at.unwrap_or(usize::MAX), + }; + let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|p| &mut p.value) else { return }; + set_lang(items, &generic, &specific, value); + })?; + Ok(Value::Undefined) +} + +/// Sets the item of `items` in `specific` to `value`, or, when there is none, the one item in the +/// language `generic` or a variant of it. VectorCraft's own rule: the `x-default` item is first; it +/// is added with the value when there is none, and follows a change to an item that had the same +/// text; a change to the `x-default` item also changes the items that had its text. +fn set_lang(items: &mut Vec, generic: &str, specific: &str, value: String) { + // An `x-default` item a packet gave later moves to the front; the others keep their order. + if let Some(d) = items.iter().position(|i| same_lang(i.lang.as_deref(), "x-default")) + && d > 0 + { + let item = items.remove(d); + items.insert(0, item); + } + let default = items.iter().position(|i| same_lang(i.lang.as_deref(), "x-default")); + if specific.eq_ignore_ascii_case("x-default") { + match default.and_then(|d| items.get(d)).map(|i| i.text.clone()) { + Some(old) => { + for item in items.iter_mut().filter(|i| i.text == old) { + item.text.clone_from(&value); + } + } + None => items.insert(0, Item { text: value, lang: Some("x-default".into()) }), + } + return; + } + let old = items.iter().position(|i| same_lang(i.lang.as_deref(), specific)).or_else(|| { + let mut generic_items = + items.iter().enumerate().filter(|(_, i)| !same_lang(i.lang.as_deref(), "x-default") && generic_lang(i.lang.as_deref(), generic)); + match (generic_items.next(), generic_items.next()) { + (Some((at, _)), None) => Some(at), + _ => None, + } + }); + let follows = match (old, default) { + (Some(o), Some(d)) => items.get(o).map(|i| &i.text) == items.get(d).map(|i| &i.text), + (None, Some(_)) => false, + (_, None) => true, + }; + match old { + Some(o) => { + if let Some(item) = items.get_mut(o) { + item.text.clone_from(&value); + } + } + None => items.push(Item { text: value.clone(), lang: Some(specific.to_string()) }), + } + match default { + Some(d) if follows => { + if let Some(item) = items.get_mut(d) { + item.text = value; + } + } + None => items.insert(0, Item { text: value, lang: Some("x-default".into()) }), + Some(_) => {} + } +} + +/// The packet `o` serializes to with the serialize options argument `v`. +fn serialized(i: &mut Interp, o: ObjId, v: &Value, what: &str) -> JsResult { + let options = flags(i, v, what)?; + only(i, options, SERIALIZE_OMIT_PACKET_WRAPPER, what)?; + let work = { + let Some(classes) = i.xmp.as_ref() else { return Err(Abrupt::Internal("ExternalObject is not installed".into())) }; + let meta = meta_of(i, o)?; + let prefixes = meta + .props + .iter() + .filter(|property| !matches!(property.value, xmp::Value::Other { .. })) + .fold(0usize, |bytes, property| bytes.saturating_add(classes.registry.prefix_of(&property.ns).map_or(0, str::len))); + meta.heap_bytes().saturating_mul(6).saturating_add(prefixes.saturating_mul(3)) + }; + spend(i, work)?; + let r = { + let Some(c) = i.xmp.as_ref() else { return Err(Abrupt::Internal("ExternalObject is not installed".into())) }; + xmp::serialize(meta_of(i, o)?, &c.registry, options & SERIALIZE_OMIT_PACKET_WRAPPER == 0) + }; + let s = r.map_err(|e| xmp_error(i, what, e, ""))?; + Ok(s) +} + +fn serialize(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.serialize"; + let o = this_meta(i, &this, what)?; + // Padding, indent, newline and base indent are not handled yet. + for (n, a) in args.iter().enumerate().skip(1) { + if !matches!(a, Value::Undefined) { + let name = ["", "padding", "indent", "newline", "baseIndent"].get(n).copied().unwrap_or("argument"); + return Err(not_yet(i, &format!("XMPMeta.serialize {name}"))); + } + } + let s = serialized(i, o, &arg(args, 0), what)?; + string(i, &s) +} + +fn register_namespace(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.registerNamespace"; + let uri = text(i, &arg(args, 0))?; + let prefix = text(i, &arg(args, 1))?; + let (proposed, growth) = registry(i)?.registration(&uri, &prefix).map_err(|e| xmp_error(i, what, e, &prefix))?; + i.reserve_heap(growth.saturating_add(string_bytes(proposed.len() + 1)))?; + let r = registry(i)?.register(&uri, &prefix); + match r { + Ok(p) => { + i.heap.bytes = i.heap.bytes.saturating_add(growth); + string(i, &format!("{p}:")) + } + Err(e) => Err(xmp_error(i, what, e, &prefix)), + } +} + +fn get_namespace_prefix(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let uri = text(i, &arg(args, 0))?; + let found = registry(i)?.prefix_of(&uri).map(|p| format!("{p}:")); + match found { + Some(p) => string(i, &p), + None => Ok(Value::Undefined), + } +} + +fn get_namespace_uri(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let prefix = text(i, &arg(args, 0))?; + let prefix = prefix.strip_suffix(':').unwrap_or(&prefix).to_string(); + let found = registry(i)?.uri_of(&prefix).map(str::to_string); + match found { + Some(u) => string(i, &u), + None => Ok(Value::Undefined), + } +} + +/// Defines functions that throw that they are not available yet. +macro_rules! not_yet_fns { + ($($f:ident => $name:literal,)*) => { + $(fn $f(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Err(not_yet(i, $name)) + })* + }; +} + +not_yet_fns! { + meta_iterator => "XMPMeta.iterator", + meta_serialize_to_array => "XMPMeta.serializeToArray", + meta_dump_object => "XMPMeta.dumpObject", + meta_sort => "XMPMeta.sort", + meta_get_struct_field => "XMPMeta.getStructField", + meta_set_struct_field => "XMPMeta.setStructField", + meta_delete_struct_field => "XMPMeta.deleteStructField", + meta_does_struct_field_exist => "XMPMeta.doesStructFieldExist", + meta_get_qualifier => "XMPMeta.getQualifier", + meta_set_qualifier => "XMPMeta.setQualifier", + meta_delete_qualifier => "XMPMeta.deleteQualifier", + meta_does_qualifier_exist => "XMPMeta.doesQualifierExist", + meta_dump_namespaces => "XMPMeta.dumpNamespaces", + meta_register_alias => "XMPMeta.registerAlias", + meta_resolve_alias => "XMPMeta.resolveAlias", + meta_dump_aliases => "XMPMeta.dumpAliases", + meta_delete_alias => "XMPMeta.deleteAlias", + meta_delete_namespace => "XMPMeta.deleteNamespace", + file_get_format_info => "XMPFile.getFormatInfo", +} + +// ---- XMPFile ---- + +/// The `XMPFile` `this`, refused when the `XMPFile` constructor did not make it. +fn this_file(i: &mut Interp, this: &Value, what: &str) -> JsResult { + if let Some(o) = this.as_object() + && matches!(i.heap.object(o).map(|ob| &ob.class), Some(Class::XmpFile(_))) + && matches!(slot(i, o, PATH)?, Value::String(_)) + { + return Ok(o); + } + Err(wrong_object(i, what, "XMPFile")) +} + +/// The `XMPFile` `this` while it is open in this run, refused when it is closed. +fn open_file(i: &mut Interp, this: &Value, what: &str) -> JsResult { + let o = this_file(i, this, what)?; + let this_run = matches!(slot(i, o, RUN)?, Value::Number(n) if Some(n) == crate::file_classes::run_count(i)); + if !this_run || !slot(i, o, OPEN)?.truthy() { + return Err(i.throw(ErrorType::Error, &format!("{what}: the file is closed"))); + } + Ok(o) +} + +fn file_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPFile"; + if i.files.is_none() { + return Err(not_yet(i, "XMPFile without File and Folder")); + } + let format = match arg(args, 1) { + Value::Undefined | Value::Null => FILE_UNKNOWN, + v => flags(i, &v, what)?, + }; + if ![FILE_UNKNOWN, FILE_TEXT, FILE_XML].contains(&format) { + return Err(not_handled(i, what, &format!("0x{format:08X}"))); + } + let open_flags = flags(i, &arg(args, 2), what)?; + // `OPEN_ONLY_XMP` asks for the XMP alone, which is all an `XMPFile` reads. + only(i, open_flags, OPEN_FOR_READ | OPEN_FOR_UPDATE | OPEN_ONLY_XMP | OPEN_USE_PACKET_SCANNING, what)?; + let update = open_flags & OPEN_FOR_UPDATE != 0; + let scan = open_flags & OPEN_USE_PACKET_SCANNING != 0; + let path = crate::file_classes::platform_path(i, &arg(args, 0))?; + let r = i.rooted(std::slice::from_ref(&path), |i| { + crate::file_classes::call_host(i, "xmpOpen", &[path.clone(), Value::Bool(update), Value::Bool(scan)]) + })?; + let keep = [path.clone(), r.clone()]; + i.rooted(&keep, |i| { + let error = crate::file_classes::record_field(i, &r, "error")?; + if let Value::String(_) = error { + let m = text(i, &error)?; + return Err(i.throw(ErrorType::Error, &m)); + } + let field = |i: &mut Interp, name: &str| crate::file_classes::record_field(i, &r, name); + let sidecar = field(i, "sidecar")?.truthy(); + let reported = if format == FILE_UNKNOWN && sidecar { FILE_XML } else { format }; + let file_proto = ids(i)?.file_proto; + let state_bytes = std::mem::size_of::>(); + i.reserve_heap(OBJECT_BYTES + state_bytes + 12 * PROP_BYTES)?; + let o = i.heap.alloc_object(Object::new(Class::XmpFile(Box::default()), Some(file_proto))); + i.heap.bytes = i.heap.bytes.saturating_add(state_bytes); + i.rooted(&[Value::Object(o)], |i| { + let packet = field(i, "packet")?; + let fields = [ + (PATH, path.clone()), + (FORMAT, Value::Number(f64::from(reported))), + (FLAGS, Value::Number(f64::from(open_flags))), + (RUN, crate::file_classes::run_count(i).map_or(Value::Undefined, Value::Number)), + (OPEN, Value::Bool(true)), + (PACKET, if matches!(packet, Value::String(_)) { packet } else { Value::Null }), + (OFFSET, field(i, "offset")?), + (LENGTH, field(i, "length")?), + (WRITEABLE, Value::Bool(field(i, "writeable")?.truthy())), + (SIDECAR, Value::Bool(sidecar)), + (CHAR_FORM, field(i, "charForm")?), + (PENDING, Value::Undefined), + ]; + for (name, value) in fields { + set_slot(i, o, name, value)?; + } + Ok(Value::Object(o)) + }) + }) +} + +fn get_xmp(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let what = "XMPFile.getXMP"; + let o = open_file(i, &this, what)?; + let pending = slot(i, o, PENDING)?; + let packet = if matches!(pending, Value::String(_)) { pending } else { slot(i, o, PACKET)? }; + if !matches!(packet, Value::String(_)) { + return Ok(Value::Null); + } + let text = text(i, &packet)?; + let meta = if text.trim_matches([' ', '\t', '\r', '\n']).is_empty() { Meta::default() } else { parse_packet(i, what, &text)? }; + new_meta(i, meta) +} + +fn get_packet_info(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let what = "XMPFile.getPacketInfo"; + let o = open_file(i, &this, what)?; + let packet = slot(i, o, PACKET)?; + if !matches!(packet, Value::String(_)) { + return Ok(Value::Null); + } + let char_form = slot(i, o, CHAR_FORM)?; + // The padding is counted in bytes: two for each character of a UTF-16 packet. + let unit = if matches!(char_form, Value::Number(n) if n == 2.0 || n == 3.0) { 2 } else { 1 }; + let packet_text = text(i, &packet)?; + spend(i, packet_text.len())?; + let pad = crate::xmp::pad_size(&packet_text) * unit; + let fields = vec![ + ("charForm", char_form), + ("length", slot(i, o, LENGTH)?), + ("offset", slot(i, o, OFFSET)?), + ("packet", packet), + ("padSize", Value::Number(pad as f64)), + ("writeable", slot(i, o, WRITEABLE)?), + ]; + record(i, None, fields) +} + +fn get_file_info(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let what = "XMPFile.getFileInfo"; + let o = open_file(i, &this, what)?; + let fields = vec![ + ("filePath", slot(i, o, PATH)?), + ("format", slot(i, o, FORMAT)?), + ("handlerFlags", Value::Number(0.0)), + ("openFlags", slot(i, o, FLAGS)?), + ]; + record(i, None, fields) +} + +/// Can `o` take a packet: opened for update, and a `.xmp` file? +fn can_update(i: &Interp, o: ObjId) -> JsResult { + let open_flags = match slot(i, o, FLAGS)? { + Value::Number(n) => n as u32, + _ => 0, + }; + Ok(open_flags & OPEN_FOR_UPDATE != 0 && slot(i, o, SIDECAR)?.truthy()) +} + +/// The packet the argument `v` of `putXMP` or `canPutXMP` gives: an `XMPMeta` serialized with its +/// wrapper, or a string, which must be a packet that can be read. +fn packet_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { + if let Some(m) = is_meta(i, v) { + return serialized(i, m, &Value::Undefined, what); + } + if let Value::Object(o) = v + && matches!(i.heap.object(*o).map(|ob| &ob.class), Some(Class::Array { .. })) + { + return Err(not_yet(i, &format!("{what}(buffer)"))); + } + let s = text(i, v)?; + if s.len() > xmp::MAX_BYTES { + return Err(xmp_error(i, what, XmpError::TooLarge, "")); + } + // A packet is checked by reading it into a copy of the realm's namespaces, so checking it + // registers nothing. + let mut scratch = registry(i)?.clone(); + spend(i, s.len().saturating_add(2 * scratch.bytes()))?; + xmp::validate_within(&s, &mut scratch, i.limits.heap_bytes).map_err(|e| xmp_error(i, what, e, ""))?; + Ok(s) +} + +fn can_put_xmp(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPFile.canPutXMP"; + let o = open_file(i, &this, what)?; + if !can_update(i, o)? { + return Ok(Value::Bool(false)); + } + let packet = packet_arg(i, &arg(args, 0), what); + match packet { + // Converting the argument runs script code, which may have closed the file. + Ok(_) => { + let o = open_file(i, &this, what)?; + Ok(Value::Bool(can_update(i, o)?)) + } + Err(Abrupt::Throw(_)) => Ok(Value::Bool(false)), + Err(e) => Err(e), + } +} + +fn put_xmp(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPFile.putXMP"; + let o = open_file(i, &this, what)?; + if !can_update(i, o)? { + return Err(i.throw(ErrorType::Error, &format!("{what}: the file cannot be updated"))); + } + let packet = packet_arg(i, &arg(args, 0), what)?; + // Converting the argument runs script code, which may have closed the file. + let o = open_file(i, &this, what)?; + if !can_update(i, o)? { + return Err(i.throw(ErrorType::Error, &format!("{what}: the file cannot be updated"))); + } + let v = string(i, &packet)?; + i.rooted(std::slice::from_ref(&v), |i| set_slot_with_charge(i, o, PENDING, v.clone(), true))?; + Ok(Value::Undefined) +} + +fn close_file(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPFile.closeFile"; + let o = this_file(i, &this, what)?; + let close_flags = flags(i, &arg(args, 0), what)?; + only(i, close_flags, CLOSE_UPDATE_SAFELY, what)?; + let this_run = matches!(slot(i, o, RUN)?, Value::Number(n) if Some(n) == crate::file_classes::run_count(i)); + let pending = slot(i, o, PENDING)?; + if this_run && slot(i, o, OPEN)?.truthy() && matches!(pending, Value::String(_)) { + let path = slot(i, o, PATH)?; + let safely = Value::Bool(close_flags & CLOSE_UPDATE_SAFELY != 0); + let r = + i.rooted(&[path.clone(), pending.clone()], |i| crate::file_classes::call_host(i, "xmpWrite", &[path.clone(), pending.clone(), safely]))?; + let error = i.rooted(std::slice::from_ref(&r), |i| crate::file_classes::record_field(i, &r, "error"))?; + if let Value::String(_) = error { + // The file stays open with its packet, so a later `closeFile` tries again. + let m = text(i, &error)?; + return Err(i.throw(ErrorType::Error, &m)); + } + } + set_slot(i, o, PENDING, Value::Undefined)?; + set_slot(i, o, PACKET, Value::Null)?; + set_slot(i, o, OPEN, Value::Bool(false))?; + Ok(Value::Undefined) +} + +// ---- install ---- + +fn native(i: &mut Interp, name: &'static str, f: crate::heap::NativeFn, length: u32, kind: NativeKind, constructor: bool) -> JsResult { + i.reserve_heap(OBJECT_BYTES + PROP_BYTES + string_bytes("length".len()))?; + crate::builtins::native(i, name, f, length, kind, constructor) +} + +fn data(i: &mut Interp, on: ObjId, name: &str, value: Value, flags: u8) -> JsResult<()> { + let added = if i.get_own_property(on, &key(name))?.is_some() { 0 } else { PROP_BYTES + string_bytes(name.encode_utf16().count()) }; + i.rooted(&[Value::Object(on), value.clone()], |i| { + i.reserve_heap(added)?; + crate::builtins::data(i, on, name, value, flags) + }) +} + +fn method(i: &mut Interp, on: ObjId, name: &'static str, f: crate::heap::NativeFn, length: u32) -> JsResult<()> { + i.rooted(&[Value::Object(on)], |i| { + let method = native(i, name, f, length, NativeKind::Plain, false)?; + data(i, on, name, Value::Object(method), HIDDEN) + }) +} + +/// A data property of `XMPConst`: read-only, enumerable. +fn constant(i: &mut Interp, on: ObjId, name: &str, value: Value) -> JsResult<()> { + data(i, on, name, value, ENUMERABLE) +} + +fn constants(i: &mut Interp) -> JsResult { + i.reserve_heap(OBJECT_BYTES)?; + let o = i.new_object(); + i.rooted(&[Value::Object(o)], |i| { + let namespaces = [ + ("NS_DC", xmp::DC), + ("NS_RDF", xmp::RDF), + ("NS_XML", xmp::XML), + ("NS_XMP", xmp::XMP), + ("NS_XMP_RIGHTS", xmp::XMP_RIGHTS), + ("NS_PDF", xmp::PDF), + ("NS_PHOTOSHOP", xmp::PHOTOSHOP), // brand-ok: the constant's name in the reference + ]; + for (name, uri) in namespaces { + let value = string(i, uri)?; + constant(i, o, name, value)?; + } + let numbers: [(&str, f64); 14] = [ + ("FILE_UNKNOWN", f64::from(FILE_UNKNOWN)), + ("FILE_TEXT", f64::from(FILE_TEXT)), + ("FILE_XML", f64::from(FILE_XML)), + ("OPEN_FOR_READ", f64::from(OPEN_FOR_READ)), + ("OPEN_FOR_UPDATE", f64::from(OPEN_FOR_UPDATE)), + ("OPEN_ONLY_XMP", f64::from(OPEN_ONLY_XMP)), + ("OPEN_USE_PACKET_SCANNING", f64::from(OPEN_USE_PACKET_SCANNING)), + ("CLOSE_UPDATE_SAFELY", f64::from(CLOSE_UPDATE_SAFELY)), + ("SERIALIZE_OMIT_PACKET_WRAPPER", f64::from(SERIALIZE_OMIT_PACKET_WRAPPER)), + ("PROP_IS_ARRAY", f64::from(xmp::PROP_IS_ARRAY)), + ("PROP_IS_STRUCT", f64::from(xmp::PROP_IS_STRUCT)), + ("ARRAY_IS_ORDERED", f64::from(xmp::ARRAY_IS_ORDERED)), + ("ARRAY_IS_ALTERNATIVE", f64::from(xmp::ARRAY_IS_ALTERNATIVE)), + ("ARRAY_LAST_ITEM", -1.0), + ]; + for (name, n) in numbers { + constant(i, o, name, Value::Number(n))?; + } + i.object_mut(o)?.extensible = false; + Ok(o) + }) +} + +fn meta_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { + method(i, proto, "getProperty", get_property, 2)?; + method(i, proto, "setProperty", set_property, 3)?; + method(i, proto, "deleteProperty", delete_property, 2)?; + method(i, proto, "doesPropertyExist", does_property_exist, 2)?; + method(i, proto, "countArrayItems", count_array_items, 2)?; + method(i, proto, "getArrayItem", get_array_item, 3)?; + method(i, proto, "appendArrayItem", append_array_item, 3)?; + method(i, proto, "insertArrayItem", insert_array_item, 4)?; + method(i, proto, "setArrayItem", set_array_item, 4)?; + method(i, proto, "deleteArrayItem", delete_array_item, 3)?; + method(i, proto, "doesArrayItemExist", does_array_item_exist, 3)?; + method(i, proto, "getLocalizedText", get_localized_text, 4)?; + method(i, proto, "setLocalizedText", set_localized_text, 5)?; + method(i, proto, "serialize", serialize, 0)?; + method(i, proto, "iterator", meta_iterator, 0)?; + method(i, proto, "serializeToArray", meta_serialize_to_array, 0)?; + method(i, proto, "dumpObject", meta_dump_object, 0)?; + method(i, proto, "sort", meta_sort, 0)?; + method(i, proto, "getStructField", meta_get_struct_field, 4)?; + method(i, proto, "setStructField", meta_set_struct_field, 5)?; + method(i, proto, "deleteStructField", meta_delete_struct_field, 4)?; + method(i, proto, "doesStructFieldExist", meta_does_struct_field_exist, 4)?; + method(i, proto, "getQualifier", meta_get_qualifier, 4)?; + method(i, proto, "setQualifier", meta_set_qualifier, 5)?; + method(i, proto, "deleteQualifier", meta_delete_qualifier, 4)?; + method(i, proto, "doesQualifierExist", meta_does_qualifier_exist, 4)?; + method(i, ctor, "registerNamespace", register_namespace, 2)?; + method(i, ctor, "getNamespacePrefix", get_namespace_prefix, 1)?; + method(i, ctor, "getNamespaceURI", get_namespace_uri, 1)?; + method(i, ctor, "dumpNamespaces", meta_dump_namespaces, 0)?; + method(i, ctor, "registerAlias", meta_register_alias, 5)?; + method(i, ctor, "resolveAlias", meta_resolve_alias, 2)?; + method(i, ctor, "dumpAliases", meta_dump_aliases, 0)?; + method(i, ctor, "deleteAlias", meta_delete_alias, 2)?; + method(i, ctor, "deleteNamespace", meta_delete_namespace, 1) +} + +fn file_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { + method(i, proto, "getXMP", get_xmp, 0)?; + method(i, proto, "putXMP", put_xmp, 1)?; + method(i, proto, "canPutXMP", can_put_xmp, 1)?; + method(i, proto, "getPacketInfo", get_packet_info, 0)?; + method(i, proto, "getFileInfo", get_file_info, 0)?; + method(i, proto, "closeFile", close_file, 1)?; + method(i, ctor, "getFormatInfo", file_get_format_info, 1) +} + +/// Links the constructor `ctor` and its prototype `proto`, without making it a global. +fn link(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { + data(i, ctor, "prototype", Value::Object(proto), 0)?; + data(i, proto, "constructor", Value::Object(ctor), HIDDEN) +} + +/// Adds the global `ExternalObject`, which defines `XMPMeta`, `XMPFile` and `XMPConst` when a +/// script loads the XMP library ([`crate::Realm::define_external_object`]). A call after a +/// successful installation is refused and preserves registered namespaces. A failed installation can be retried. +pub(crate) fn install(i: &mut Interp) -> JsResult<()> { + if i.xmp.is_some() { + return Err(Abrupt::Internal("ExternalObject is already added".into())); + } + let object_proto = i.intrinsics.object_proto; + i.reserve_heap(4 * OBJECT_BYTES)?; + let external_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let meta_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let file_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let property_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + let keep = [external_proto, meta_proto, file_proto, property_proto].map(Value::Object); + let installed = i.rooted(&keep, |i| { + let meta = native(i, "XMPMeta", meta_ctor, 1, NativeKind::Plain, true)?; + i.rooted(&[Value::Object(meta)], |i| { + let file = native(i, "XMPFile", file_ctor, 3, NativeKind::Plain, true)?; + i.rooted(&[Value::Object(file)], |i| { + let constants = constants(i)?; + let registry = Registry::default(); + i.rooted(&[Value::Object(constants)], |i| i.reserve_heap(registry.bytes()))?; + i.heap.bytes = i.heap.bytes.saturating_add(registry.bytes()); + i.xmp = Some(Classes { ids: Ids { external_proto, meta, meta_proto, file, file_proto, constants, property_proto }, registry }); + link(i, meta, meta_proto)?; + link(i, file, file_proto)?; + meta_members(i, meta, meta_proto)?; + file_members(i, file, file_proto)?; + method(i, property_proto, "toString", property_to_string, 0)?; + let external = native(i, "ExternalObject", external_ctor, 1, NativeKind::Plain, true)?; + i.rooted(&[Value::Object(external)], |i| { + method(i, external, "search", external_search, 1)?; + method(i, external_proto, "terminate", external_terminate, 0)?; + link(i, external, external_proto)?; + data(i, i.global, "ExternalObject", Value::Object(external), HIDDEN) + }) + }) + }) + }); + if installed.is_err() { + i.xmp = None; + } + installed +} + +#[cfg(test)] +mod namespace_heap_tests { + use super::*; + + #[test] + fn non_xml_whitespace_sidecars_are_not_empty_metadata() { + for text in ["\u{a0}", "\u{2003}", "\u{85}", " \t\r\n"] { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + crate::file_classes::install( + &mut interp, + vec![("current".into(), crate::HostItem::Function(std::rc::Rc::new(|_| Ok(crate::Data::String(String::new())))))], + ) + .unwrap(); + install(&mut interp).unwrap(); + let mut fields = PropMap::default(); + fields.insert(key(PATH), Value::str("packet.xmp")); + fields.insert(key(OPEN), Value::Bool(true)); + fields.insert(key(RUN), Value::Number(crate::file_classes::run_count(&interp).unwrap())); + fields.insert(key(PACKET), Value::str(text)); + let object = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), Some(ids(&interp).unwrap().file_proto))); + let value = Value::Object(object); + interp + .rooted(std::slice::from_ref(&value), |interp| { + let result = get_xmp(interp, value.clone(), &[], false); + if text == " \t\r\n" { + assert!(result.is_ok()); + } else { + assert!(matches!(result, Err(Abrupt::Throw(_))), "{text:?}: {result:?}"); + } + Ok(()) + }) + .unwrap(); + } + } + + #[test] + fn localized_text_lookup_charges_for_language_scans() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let value = new_meta( + &mut interp, + Meta { + props: vec![xmp::Prop { + ns: xmp::DC.into(), + name: "items".into(), + value: xmp::Value::Array { form: Form::Alt, items: vec![Item { text: "text".into(), lang: Some("en-US".into()) }; 10_000] }, + }], + ..Meta::default() + }, + ) + .unwrap(); + interp + .rooted(std::slice::from_ref(&value), |interp| { + let args = [Value::str(xmp::DC), Value::str("items"), Value::str("fr"), Value::str("fr-FR")]; + interp.fuel = 1_000; + let result = get_localized_text(interp, value.clone(), &args, false); + assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))), "{result:?}"); + interp.fuel = 1_000_000; + assert!(get_localized_text(interp, value.clone(), &args, false).is_ok()); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn inserting_array_items_charges_for_shifted_items() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let meta = Meta { + props: vec![xmp::Prop { + ns: xmp::DC.into(), + name: "items".into(), + value: xmp::Value::Array { form: Form::Bag, items: vec![Item { text: "text".into(), lang: None }; 1000] }, + }], + ..Meta::default() + }; + let value = new_meta(&mut interp, meta).unwrap(); + let object = value.as_object().unwrap(); + interp + .rooted(&[value], |interp| { + interp.fuel = 100; + let result = insert_item(interp, object, xmp::DC, "items", Some(1), "insert".into(), None, "insert"); + assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))), "{result:?}"); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn result_records_reserve_their_retained_property_keys() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + interp.collect_garbage(); + let name = "a_property_name_with_retained_key_storage"; + interp.limits.heap_bytes = interp.heap.bytes + OBJECT_BYTES + PROP_BYTES + string_bytes(name.len()) - 1; + let result = record(&mut interp, None, vec![(name, Value::Number(1.0))]); + assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Heap))), "{result:?}"); + } + + #[test] + fn replacing_array_items_charges_metadata_accounting_work() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let meta = Meta { + props: vec![xmp::Prop { + ns: xmp::DC.into(), + name: "items".into(), + value: xmp::Value::Array { form: Form::Bag, items: vec![Item { text: "text".into(), lang: None }; 1000] }, + }], + ..Meta::default() + }; + let value = new_meta(&mut interp, meta).unwrap(); + interp + .rooted(std::slice::from_ref(&value), |interp| { + interp.fuel = 100; + let result = + set_array_item(interp, value.clone(), &[Value::str(xmp::DC), Value::str("items"), Value::Number(1.0), Value::str("edit")], false); + assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))), "{result:?}"); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn unrelated_namespaces_do_not_spend_serialization_fuel() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + for index in 0..400 { + registry(&mut interp).unwrap().register(&format!("urn:unused:{index}:{}", "x".repeat(990)), &format!("unused_{index}")).unwrap(); + } + let value = new_meta(&mut interp, Meta::default()).unwrap(); + let object = value.as_object().unwrap(); + interp + .rooted(&[value], |interp| { + interp.fuel = 10_000; + assert!(serialized(interp, object, &Value::Undefined, "serialize").is_ok()); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn repeated_library_handles_fit_their_retained_size() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + external_ctor(&mut interp, Value::Undefined, &[Value::str(LIBRARY)], true).unwrap(); + for room in 0..2048 { + interp.collect_garbage(); + let baseline = interp.heap.bytes; + interp.limits.heap_bytes = baseline + room; + if let Ok(value) = external_ctor(&mut interp, Value::Undefined, &[Value::str(LIBRARY)], true) { + interp + .rooted(&[value], |interp| { + interp.collect_garbage(); + assert_eq!(room, interp.heap.bytes - baseline, "extra heap reservation for a retained handle"); + Ok(()) + }) + .unwrap(); + return; + } + } + panic!("no library handle fit"); + } + + #[test] + fn a_failed_external_constructor_publishes_no_partial_globals() { + let mut failures = 0; + let mut successes = 0; + for room in (0..4096).step_by(16) { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes + room; + let result = external_ctor(&mut interp, Value::Undefined, &[Value::str(LIBRARY)], true); + if result.is_err() { + failures += 1; + for name in ["XMPMeta", "XMPFile", "XMPConst"] { + assert!(interp.get_own_property(interp.global, &key(name)).unwrap().is_none(), "partial global {name}, room={room}"); + } + } else if let Ok(value) = result { + successes += 1; + interp + .rooted(&[value], |interp| { + interp.collect_garbage(); + assert!( + interp.heap.bytes <= interp.limits.heap_bytes, + "constructor retained {} bytes with limit {}", + interp.heap.bytes, + interp.limits.heap_bytes + ); + Ok(()) + }) + .unwrap(); + } + } + assert!(failures > 0 && successes > 0); + } + + #[test] + fn packet_info_charges_fuel_for_scanning_the_packet() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + crate::file_classes::install( + &mut interp, + vec![("current".into(), crate::HostItem::Function(std::rc::Rc::new(|_| Ok(crate::Data::String(String::new())))))], + ) + .unwrap(); + install(&mut interp).unwrap(); + let mut fields = PropMap::default(); + fields.insert(key(PATH), Value::str("packet.xmp")); + fields.insert(key(OPEN), Value::Bool(true)); + fields.insert(key(RUN), Value::Number(crate::file_classes::run_count(&interp).unwrap())); + fields.insert(key(PACKET), Value::str(&" ".repeat(4096))); + let object = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), Some(ids(&interp).unwrap().file_proto))); + let this = Value::Object(object); + interp + .rooted(std::slice::from_ref(&this), |interp| { + interp.fuel = 1000; + get_packet_info(interp, this.clone(), &[], false)?; + assert!(interp.fuel <= 983, "packet scan used only {} fuel", 1000 - interp.fuel); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn staging_a_packet_charges_its_string_only_once() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + crate::file_classes::install( + &mut interp, + vec![("current".into(), crate::HostItem::Function(std::rc::Rc::new(|_| Ok(crate::Data::String(String::new())))))], + ) + .unwrap(); + install(&mut interp).unwrap(); + let mut fields = PropMap::default(); + for (name, value) in [ + (PATH, Value::str("packet.xmp")), + (RUN, Value::Number(crate::file_classes::run_count(&interp).unwrap())), + (OPEN, Value::Bool(true)), + (FLAGS, Value::Number(f64::from(OPEN_FOR_UPDATE))), + (SIDECAR, Value::Bool(true)), + (PENDING, Value::Undefined), + ] { + fields.insert(key(name), value); + } + let object = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::new(fields)), Some(ids(&interp).unwrap().file_proto))); + let this = Value::Object(object); + interp + .rooted(std::slice::from_ref(&this), |interp| { + let packet = format!( + "{}", + xmp::RDF, + "x".repeat(4096) + ); + let argument = string(interp, &packet)?; + interp.rooted(std::slice::from_ref(&argument), |interp| { + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes + string_bytes(packet.encode_utf16().count()) + 512; + let result = put_xmp(interp, this.clone(), std::slice::from_ref(&argument), false); + assert!(result.is_ok(), "a single pending packet charge fits: {result:?}"); + Ok(()) + }) + }) + .unwrap(); + } + + #[test] + fn storing_an_open_packet_reuses_its_charged_string() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let packet = string(&mut interp, &"x".repeat(4096)).unwrap(); + interp + .rooted(std::slice::from_ref(&packet), |interp| { + let object = interp.heap.alloc_object(Object::new(Class::XmpFile(Box::default()), Some(ids(interp)?.file_proto))); + interp.rooted(&[Value::Object(object)], |interp| { + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes + 512; + set_slot(interp, object, PACKET, packet.clone()) + }) + }) + .unwrap(); + } + + #[test] + fn a_failed_serialization_charges_its_escaping_work() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let meta = Meta { + props: vec![xmp::Prop { + ns: xmp::DC.into(), + name: "value".into(), + value: xmp::Value::Simple { text: "&".repeat(xmp::MAX_BYTES / 4), uri: false }, + }], + ..Meta::default() + }; + let value = new_meta(&mut interp, meta).unwrap(); + let object = value.as_object().unwrap(); + interp + .rooted(&[value], |interp| { + interp.fuel = 100_000; + let result = serialized(interp, object, &Value::Undefined, "serialize"); + assert!(matches!(result, Err(Abrupt::Throw(_))), "{result:?}"); + assert!(interp.fuel < 100_000, "failed escaping left its work unpaid"); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn indexed_property_reads_copy_only_the_selected_item() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let meta = Meta { + props: vec![xmp::Prop { + ns: xmp::DC.into(), + name: "items".into(), + value: xmp::Value::Array { form: Form::Bag, items: vec![Item { text: "text".into(), lang: None }; 1000] }, + }], + ..Meta::default() + }; + let value = new_meta(&mut interp, meta).unwrap(); + interp + .rooted(std::slice::from_ref(&value), |interp| { + xmp::ITEM_COPIES.with(|copies| copies.set(0)); + for index in 1..=1000 { + get_property(interp, value.clone(), &[Value::str(xmp::DC), Value::str(&format!("items[{index}]"))], false).unwrap(); + } + let copies = xmp::ITEM_COPIES.with(|copies| copies.get()); + assert!(copies <= 1000, "copied {copies} items for 1000 indexed reads"); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn appending_array_items_has_linear_accounting_work() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + let value = new_meta(&mut interp, Meta::default()).unwrap(); + let object = value.as_object().unwrap(); + interp + .rooted(&[value], |interp| { + xmp::ACCOUNTING_ITEM_VISITS.with(|visits| visits.set(0)); + for _ in 0..1000 { + insert_item(interp, object, xmp::DC, "items", None, "text".into(), Some(Form::Bag), "append").unwrap(); + } + let visits = xmp::ACCOUNTING_ITEM_VISITS.with(|visits| visits.get()); + assert!(visits <= 2000, "accounting visited {visits} items for 1000 appends"); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn parsed_namespaces_fit_with_the_metadata_before_registration() { + let mut interp = Interp::new(crate::Options::default(), crate::Limits::default()); + install(&mut interp).unwrap(); + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes + (24 << 10); + let mut declarations = String::new(); + let mut properties = String::new(); + let mut first_uri = String::new(); + for index in 0..16 { + let uri = format!("urn:{index}:{}", "x".repeat(950)); + if index == 0 { + first_uri.clone_from(&uri); + } + declarations.push_str(&format!(" xmlns:n{index}=\"{uri}\"")); + properties.push_str(&format!("text")); + } + let packet = format!( + "{properties}" + ); + let result = parse_packet(&mut interp, "XMPMeta", &packet).and_then(|meta| new_meta(&mut interp, meta)); + assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Heap))), "{result:?}"); + assert!(registry(&mut interp).unwrap().prefix_of(&first_uri).is_none(), "a failed allocation leaves the namespaces unchanged"); + } +} diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs new file mode 100644 index 0000000000..5aee375abd --- /dev/null +++ b/crates/js/src/xmp_tests.rs @@ -0,0 +1,1135 @@ +use proptest::prelude::*; + +use crate::xmp::{self, Form, Registry, XmpError}; +use crate::{JsValue, LimitKind, Limits, Realm, RunErrorKind}; + +fn realm() -> Realm { + let mut r = Realm::with_options(crate::Options::default(), Limits::default()); + if let Err(e) = r.define_external_object() { + panic!("{e:?}"); + } + r +} + +fn run(src: &str) -> JsValue { + match realm().run(&format!("new ExternalObject('lib:AdobeXMPScript');\n{src}")) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +fn truth(src: &str) { + assert_eq!(run(src), JsValue::Bool(true), "{src}"); +} + +/// The name and message of what `src` throws. +fn thrown(src: &str) -> String { + string(&format!("try {{ {src}; 'no error' }} catch (e) {{ e.name + ': ' + e.message }}")) +} + +const PACKET: &str = r#" + + + + HelloBonjour + onetwo + image/svg+xml + 1 + + + +"#; + +#[test] +fn inherited_description_language_is_not_silently_discarded() { + let packet = r#"Hello"#; + assert!(matches!(xmp::parse(packet, &mut Registry::default()), Err(XmpError::NotYet))); + let outer = packet.replace("xml:lang=\"en\"", "").replace("", ""); + let mut registry = Registry::default(); + let meta = xmp::parse(&explicit, &mut registry).unwrap(); + assert!(xmp::serialize(&meta, ®istry, false).unwrap().contains("xml:lang=\"en\"")); +} + +#[test] +fn localized_text_returns_the_selected_property_and_language() { + let specific = with_packet( + "var value = m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'fr-FR'); [typeof value, value.value, value.locale, value.options, value.namespace, value.path, String(value)].join('|')", + ); + assert_eq!(string(&specific), "object|Bonjour|fr-FR|80|||Bonjour"); + let fallback = with_packet("var value = m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'de-DE'); [value.value, value.locale].join('|')"); + assert_eq!(string(&fallback), "Hello|x-default"); + truth(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'missing', null, 'fr-FR') === undefined")); + truth(&with_packet( + "m.appendArrayItem(XMPConst.NS_DC, 'emptyAlt', 0, 'value', XMPConst.PROP_IS_ARRAY | XMPConst.ARRAY_IS_ORDERED | XMPConst.ARRAY_IS_ALTERNATIVE); + m.deleteArrayItem(XMPConst.NS_DC, 'emptyAlt', 1); m.doesPropertyExist(XMPConst.NS_DC, 'emptyAlt') && m.getLocalizedText(XMPConst.NS_DC, 'emptyAlt', null, 'fr-FR') === undefined", + )); +} + +#[test] +fn rdf_qualified_names_validate_both_parts() { + let packet = PACKET.replace("ex:a>", "ex:a:b>"); + assert!(matches!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed))); + assert!(xmp::parse(PACKET, &mut Registry::default()).is_ok()); +} + +#[test] +fn rdf_non_xml_whitespace_is_not_indentation() { + let packet = PACKET.replace("", "\u{a0}"); + assert!(matches!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed))); + assert!(xmp::parse(&PACKET.replace("", " \t\r\n"), &mut Registry::default()).is_ok()); +} + +#[test] +fn rdf_descriptions_reject_conflicting_nonempty_subjects() { + let packet = PACKET + .replace("rdf:about=\"\"", "rdf:about=\"urn:a\"") + .replace("", ""); + assert!(matches!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed))); + assert!(xmp::parse(&packet.replace("urn:b", "urn:a"), &mut Registry::default()).is_ok()); +} + +#[test] +fn explicit_empty_and_named_rdf_subjects_cannot_be_merged() { + for (first, second) in [("", "urn:a"), ("urn:a", "")] { + let packet = PACKET + .replace("rdf:about=\"\"", &format!("rdf:about=\"{first}\"")) + .replace("", &format!("")); + assert!(matches!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed))); + } +} + +#[test] +fn packet_padding_requires_an_actual_wrapper_trailer() { + let packet = r#""#; + assert_eq!(xmp::pad_size(packet), 0); + assert!(xmp::pad_size(PACKET) > 0); + let prefixed = format!("\n\n{PACKET}"); + assert_eq!(xmp::pad_size(&prefixed), xmp::pad_size(PACKET)); + assert_eq!(xmp::pad_size(&format!("{PACKET}")), xmp::pad_size(PACKET)); + assert_eq!(xmp::pad_size(&format!("{PACKET}")), xmp::pad_size(PACKET)); + let comment = ""; + assert_eq!(xmp::pad_size(&PACKET.replace("", &format!("{comment}"))), xmp::pad_size(PACKET)); +} + +#[test] +fn packet_padding_ignores_invalid_trailer_values() { + for value in ["note", "", "ww", "W"] { + let packet = PACKET.replace("", &format!(" \n ")); + assert_eq!(xmp::pad_size(&packet), 6, "{value:?}"); + } +} + +#[test] +fn packet_scans_ignore_trailers_inside_the_xml_root() { + let packet = PACKET.replace("", ""); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (0, packet.len())); + let packet = PACKET.replace("", ""); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (0, packet.len())); +} + +#[test] +fn malformed_wrapped_xml_is_not_reported_as_absent() { + let packet = PACKET.replace("image/svg+xml", "&undefined;"); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (0, packet.len())); + assert!(xmp::parse(&packet[span.start..span.end], &mut Registry::default()).is_err()); +} + +#[test] +fn wrapper_lookahead_stops_before_unrelated_later_packets() { + let header = ""; + let incomplete = format!("{header}"); + let packet = format!("{}{PACKET}", incomplete.repeat(1000)); + xmp::PACKET_XML_READ_BYTES.with(|bytes| bytes.set(0)); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (0, incomplete.len())); + let read = xmp::PACKET_XML_READ_BYTES.with(|bytes| bytes.get()); + assert!(read <= incomplete.len() * 4, "lookahead read {read} bytes for {} byte candidate", incomplete.len()); +} + +#[test] +fn an_inner_trailer_does_not_pair_an_orphan_with_the_next_packet() { + let orphan = PACKET.replace("", "").replace("", ""); + let packet = format!("{orphan}{PACKET}"); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (orphan.len(), packet.len())); +} + +#[test] +fn packet_headers_inside_application_instructions_are_text() { + let packet = PACKET.replace("", ""); + assert_eq!(xmp::find_packet(packet.as_bytes()).map(|span| (span.start, span.end)), Some((0, packet.len()))); + assert!(xmp::parse(&packet, &mut Registry::default()).is_ok()); +} + +#[test] +fn packet_headers_inside_the_xml_root_are_instructions() { + let header = ""; + let packet = PACKET.replace("", &format!("{header}")); + let span = xmp::find_packet(packet.as_bytes()).unwrap(); + assert_eq!((span.start, span.end), (0, packet.len())); + assert!(xmp::parse(&packet, &mut Registry::default()).is_ok()); +} + +#[test] +fn binary_prefix_with_an_unclosed_instruction_does_not_hide_a_packet() { + let packet = format!("binary\0\xff"), ("")] { + let mut packet = b"\xff".to_vec(); + packet.extend_from_slice(open.as_bytes()); + packet.extend_from_slice(PACKET.as_bytes()); + packet.extend_from_slice(close.as_bytes()); + packet.extend_from_slice(b""); + let offset = packet.len(); + packet.extend_from_slice(PACKET.as_bytes()); + let span = xmp::find_packet(&packet).unwrap(); + assert_eq!((span.start, span.end), (offset, packet.len()), "{open}"); + } +} + +#[test] +fn an_abandoned_xml_root_does_not_hide_the_next_packet() { + let header = ""; + for root in ["", "", ""] { + let prefix = format!("{header}{root}{}", "") + .replace("", ""); + assert!(matches!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed))); +} + +#[test] +fn non_xml_whitespace_before_an_array_is_preserved() { + let packet = PACKET.replace("image/svg+xml", "\u{a0}value"); + let mut registry = Registry::default(); + let meta = xmp::parse(&packet, &mut registry).unwrap(); + assert!(xmp::serialize(&meta, ®istry, true).unwrap().contains('\u{a0}')); +} + +fn with_packet(src: &str) -> String { + format!("var m = new XMPMeta({:?});\n{src}", PACKET) +} + +#[test] +fn only_the_xmp_library_loads() { + let r = realm().run("typeof XMPMeta + ' ' + ExternalObject.search('lib:AdobeXMPScript') + ' ' + ExternalObject.search('lib:other')"); + assert_eq!(r.ok(), Some(JsValue::String("undefined true false".into()))); + let r = realm().run("try { new ExternalObject('lib:other') ; 'loaded' } catch (e) { e.name + ': ' + e.message + ' ' + typeof XMPMeta }"); + assert_eq!(r.ok(), Some(JsValue::String("Error: ExternalObject: the library lib:other is not available undefined".into()))); + truth("typeof XMPMeta == 'function' && typeof XMPFile == 'function' && XMPConst.ARRAY_LAST_ITEM == -1"); + truth("var h = new ExternalObject('lib:AdobeXMPScript'); h.terminate(); typeof XMPMeta == 'function'"); +} + +#[test] +fn a_packet_reads_into_properties() { + assert_eq!(string(&with_packet("m.getProperty(XMPConst.NS_DC, 'format').value")), "image/svg+xml"); + assert_eq!(string(&with_packet("String(m.getProperty(XMPConst.NS_XMP, 'xmp:CreatorTool'))")), "Tool & Co"); + assert_eq!(string(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'fr-FR').value")), "Bonjour"); + assert_eq!(string(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'de-DE').value")), "Hello"); + assert_eq!(string(&with_packet("m.getArrayItem(XMPConst.NS_DC, 'subject', XMPConst.ARRAY_LAST_ITEM).value")), "two"); + assert_eq!(run(&with_packet("m.countArrayItems(XMPConst.NS_DC, 'subject')")), JsValue::Number(2.0)); + assert_eq!(run(&with_packet("m.getProperty(XMPConst.NS_DC, 'title').options")), JsValue::Number(f64::from(0x200 | 0x400 | 0x800 | 0x1000))); + assert_eq!(run(&with_packet("m.getProperty('http://example.com/ns/', 'thing').options")), JsValue::Number(256.0)); + assert_eq!(run(&with_packet("m.getProperty(XMPConst.NS_DC, 'creator')")), JsValue::Undefined); + assert_eq!(string("XMPMeta.getNamespacePrefix('http://example.com/ns/') + ''"), "undefined"); + assert_eq!(string(&with_packet("XMPMeta.getNamespacePrefix('http://example.com/ns/')")), "ex:"); +} + +/// An array item with an `xml:lang` qualifier has the qualifier and language options, read by path +/// or by index; an item without one has none. +#[test] +fn array_items_report_their_language_qualifier() { + let qualified = f64::from(0x10 | 0x40); + assert_eq!(run(&with_packet("m.getProperty(XMPConst.NS_DC, 'title[2]').options")), JsValue::Number(qualified)); + assert_eq!(run(&with_packet("m.getArrayItem(XMPConst.NS_DC, 'title', 1).options")), JsValue::Number(qualified)); + assert_eq!(run(&with_packet("m.getProperty(XMPConst.NS_DC, 'subject[1]').options")), JsValue::Number(0.0)); + assert_eq!(run(&with_packet("m.getArrayItem(XMPConst.NS_DC, 'subject', 2).options")), JsValue::Number(0.0)); +} + +#[test] +fn properties_arrays_and_namespaces_round_trip() { + let src = "var ns = 'http://example.com/rt/'; + var p = XMPMeta.registerNamespace(ns, 'rt'); + var m = new XMPMeta(); + m.setProperty(ns, 'name', 'a & \"c\"'); + m.appendArrayItem(ns, 'list', 0, 'x', XMPConst.ARRAY_IS_ORDERED); + m.appendArrayItem(ns, 'list', 'y'); + m.insertArrayItem(ns, 'list', 1, 'w'); + m.setArrayItem(ns, 'list', 3, 'z'); + m.setLocalizedText(ns, 'label', null, 'en-US', 'Hi'); + m.setLocalizedText(ns, 'label', null, 'de-DE', 'Hallo'); + var n = new XMPMeta(m.serialize()); + var o = new XMPMeta(n.serialize(XMPConst.SERIALIZE_OMIT_PACKET_WRAPPER)); + [p, o.getProperty(ns, 'rt:name').value, o.getProperty(ns, 'list').options, o.countArrayItems(ns, 'list'), + o.getArrayItem(ns, 'list', 1).value, o.getArrayItem(ns, 'list', 2).value, o.getArrayItem(ns, 'list', 3).value, + o.getLocalizedText(ns, 'label', null, 'x-default'), o.getLocalizedText(ns, 'label', 'de', 'de-AT'), + m.serialize() == n.serialize(), n.serialize().indexOf(' & \"c\"|1536|3|w|x|z|Hi|Hallo|true|true|-1"); + let src = with_packet( + "var n = new XMPMeta(m.serialize()); n.serialize() == m.serialize() && n.getProperty('http://example.com/ns/', 'thing').options == 256 && n.getProperty(XMPConst.NS_XMP, 'CreatorTool').value == 'Tool & Co'", + ); + truth(&src); + truth(&with_packet( + "m.deleteProperty(XMPConst.NS_DC, 'format'); !m.doesPropertyExist(XMPConst.NS_DC, 'format') && m.doesPropertyExist(XMPConst.NS_DC, 'subject')", + )); + truth(&with_packet("m.deleteArrayItem(XMPConst.NS_DC, 'subject', 1); m.getArrayItem(XMPConst.NS_DC, 'subject', 1).value == 'two'")); + assert_eq!(string("XMPMeta.registerNamespace('http://example.com/a/', 'dc')"), "dc_1_:"); + assert_eq!(string("XMPMeta.getNamespaceURI('dc:')"), "http://purl.org/dc/elements/1.1/"); +} + +#[test] +fn append_array_item_preserves_explicit_optional_slots() { + assert_eq!( + string( + "var out = []; var ns = XMPConst.NS_DC; + function append(option, full) { var m = new XMPMeta(); try { + if (full) m.appendArrayItem(ns, 'items', option, 'value', XMPConst.PROP_IS_ARRAY); + else { m.appendArrayItem(ns, 'items', 'first', XMPConst.PROP_IS_ARRAY); + m.appendArrayItem(ns, 'items', option, 'value'); m.deleteArrayItem(ns, 'items', 1); } + out.push(m.getArrayItem(ns, 'items', 1).value); + } catch (e) { out.push('error'); } } + append(undefined, true); append(null, true); append(undefined, false); append(null, false); + var m = new XMPMeta(); m.appendArrayItem(ns, 'empty', null, XMPConst.PROP_IS_ARRAY); + m.appendArrayItem(ns, 'short', 'short', XMPConst.PROP_IS_ARRAY); + out.push(m.getArrayItem(ns, 'empty', 1).value, m.getArrayItem(ns, 'short', 1).value); out.join('|')" + ), + "value|value|value|value||short" + ); +} + +#[test] +fn array_last_insertion_precedes_the_last_existing_item() { + assert_eq!( + string(&with_packet( + "m.insertArrayItem(XMPConst.NS_DC, 'subject', XMPConst.ARRAY_LAST_ITEM, 'middle'); [1,2,3].map(function(n) { return m.getArrayItem(XMPConst.NS_DC, 'subject', n).value; }).join('|')" + )), + "one|middle|two" + ); + assert!(thrown(&with_packet("m.deleteArrayItem(XMPConst.NS_DC, 'subject', 2); m.deleteArrayItem(XMPConst.NS_DC, 'subject', 1); m.insertArrayItem(XMPConst.NS_DC, 'subject', XMPConst.ARRAY_LAST_ITEM, 'x')")).starts_with("RangeError:")); +} + +#[test] +fn null_array_values_are_empty_items() { + truth(&with_packet( + "m.insertArrayItem(XMPConst.NS_DC, 'subject', 1, null); m.setArrayItem(XMPConst.NS_DC, 'subject', 2, null); m.getArrayItem(XMPConst.NS_DC, 'subject', 1).value === '' && m.getArrayItem(XMPConst.NS_DC, 'subject', 2).value === ''", + )); +} + +/// The prefix `xmlns` and the namespace of `xmlns` attributes are refused, so no packet declares +/// them. +#[test] +fn the_xmlns_prefix_and_namespace_are_refused() { + assert_eq!( + thrown("XMPMeta.registerNamespace('http://example.com/x/', 'xmlns')"), + "Error: XMPMeta.registerNamespace: xmlns is not a valid property name" + ); + assert_eq!( + thrown("XMPMeta.registerNamespace('http://www.w3.org/2000/xmlns/', 'ok')"), + "Error: XMPMeta.registerNamespace: ok is not a valid property name" + ); + truth("XMPMeta.getNamespaceURI('xmlns') === undefined && XMPMeta.getNamespacePrefix('http://www.w3.org/2000/xmlns/') === undefined"); +} + +#[test] +fn bad_arguments_and_unbuilt_members_throw() { + assert_eq!(thrown("new XMPMeta().getProperty('http://none/', 'a')"), "Error: XMPMeta.getProperty: the namespace http://none/ is not registered"); + assert_eq!(thrown("new XMPMeta().setProperty(XMPConst.NS_DC, '1a', 'x')"), "Error: XMPMeta.setProperty: 1a is not a valid property name"); + assert_eq!( + thrown("new XMPMeta().setProperty(XMPConst.NS_DC, 'a', 'x\\u0001')"), + "Error: XMPMeta.setProperty: the text holds a character XML does not allow" + ); + assert_eq!(thrown(&with_packet("m.setProperty(XMPConst.NS_DC, 'subject', 'x')")), "Error: XMPMeta.setProperty: subject is not a simple property"); + assert_eq!(thrown(&with_packet("m.getArrayItem(XMPConst.NS_DC, 'format', 1)")), "Error: XMPMeta.getArrayItem: format is not an array"); + assert_eq!( + thrown(&with_packet("m.insertArrayItem(XMPConst.NS_DC, 'subject', 9, 'x')")), + "RangeError: XMPMeta.insertArrayItem: the array index 9 is out of range" + ); + assert_eq!( + thrown(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'subject', null, 'en')")), + "Error: XMPMeta.getLocalizedText: subject is not a language alternative array" + ); + assert_eq!( + thrown(&with_packet("m.setProperty(XMPConst.NS_DC, 'subject[1]', 'x', XMPConst.PROP_IS_ARRAY)")), + "RangeError: XMPMeta.setProperty: the value 0x200 is not available yet" + ); + // An `rdf:Alt` with an item that has no language is not a language alternative. + let untagged = "var m = new XMPMeta(\"\ + ab\");"; + assert_eq!( + thrown(&format!("{untagged} m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'en')")), + "Error: XMPMeta.getLocalizedText: title is not a language alternative array" + ); + assert_eq!( + thrown(&format!("{untagged} m.setLocalizedText(XMPConst.NS_DC, 'title', null, 'en', 'c')")), + "Error: XMPMeta.setLocalizedText: title is not a language alternative array" + ); + assert_eq!( + thrown("new XMPMeta().getStructField(XMPConst.NS_DC, 'a', XMPConst.NS_DC, 'b')"), + "Error: XMPMeta.getStructField is not available yet" + ); + assert_eq!(thrown("new XMPMeta().getProperty(XMPConst.NS_DC, 'a/b')"), "RangeError: XMPMeta.getProperty: the value a/b is not available yet"); + assert_eq!( + thrown("XMPMeta.prototype.getProperty.call({}, XMPConst.NS_DC, 'a')"), + "TypeError: XMPMeta.getProperty: the object is not an XMPMeta object" + ); + assert_eq!( + thrown("new XMPFile('a.xmp', XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ)"), + "Error: XMPFile without File and Folder is not available yet" + ); +} + +#[test] +fn malformed_and_huge_packets_are_refused() { + let malformed = [ + "", + "", + "]>", + "&e;", + "", + "1", + ]; + for p in malformed { + assert_eq!(thrown(&format!("new XMPMeta({p:?})")), "Error: XMPMeta: the XMP packet is not well-formed XMP", "{p}"); + } + let deep = format!( + "{}{}", + "".repeat(200), + "".repeat(200) + ); + assert_eq!(xmp::parse(&deep, &mut Registry::default()), Err(XmpError::TooLarge)); + let huge = "x".repeat(xmp::MAX_BYTES + 1); + assert_eq!(xmp::parse(&huge, &mut Registry::default()), Err(XmpError::TooLarge)); + let r = realm().run("new ExternalObject('lib:AdobeXMPScript'); var s = 'xxxxxxxx'; while (s.length < 9000000) s += s; try { new XMPMeta(s); 'read' } catch (e) { e.name + ': ' + e.message }"); + assert_eq!(r.ok(), Some(JsValue::String("RangeError: XMPMeta: the XMP data is too large".into()))); +} + +#[test] +fn packets_are_found_in_file_bytes() { + let header = ""; + let bytes = format!("binary\0\u{1}{PACKET}trailer"); + let span = xmp::find_packet(bytes.as_bytes()).map(|s| (s.start, s.end, s.writeable)); + assert_eq!(span, Some((8, 8 + PACKET.len(), true))); + assert_eq!(xmp::find_packet(b" no end"), None); + assert_eq!(xmp::find_packet(format!("{header} no end").as_bytes()), None); + let read_only = PACKET.replace("end=\"w\"", "end=\"r\""); + assert_eq!(xmp::find_packet(read_only.as_bytes()).map(|s| s.writeable), Some(false)); + let stray = format!("{header} junk {header}{PACKET}"); + let span = xmp::find_packet(stray.as_bytes()).map(|s| (s.start, s.end)); + assert_eq!(span, Some((stray.len() - PACKET.len(), stray.len())), "a start with no end of its own is skipped"); + let open_end = format!("{header} junk image/svg+xml", "]]>"); + let bytes = format!("binary\0{inner}"); + assert_eq!(xmp::find_packet(bytes.as_bytes()).map(|s| (s.start, s.end)), Some((7, bytes.len()))); +} + +/// An array whose container declares the RDF prefix itself is read as an array, also when its +/// items are not simple. +#[test] +fn a_container_declaring_its_own_prefix_is_an_array() { + let packet = PACKET.replace( + "", + "1", + ); + let o = string(&format!("String(new XMPMeta({packet:?}).getProperty(XMPConst.NS_DC, 'creator').options)")); + let o: u32 = o.parse().unwrap(); + assert_eq!((o & xmp::PROP_IS_ARRAY, o & xmp::ARRAY_IS_ORDERED, o & xmp::PROP_IS_STRUCT), (xmp::PROP_IS_ARRAY, xmp::ARRAY_IS_ORDERED, 0)); +} + +#[test] +fn many_properties_and_namespaces_each_read_once() { + let mut body = String::new(); + for n in 0..3000 { + body.push_str(&format!("v{n}", n % 500, n % 500, n % 500, n % 500)); + } + body.push_str("second"); + let packet = format!("{body}"); + let mut registry = Registry::default(); + let meta = xmp::parse(&packet, &mut registry).unwrap(); + assert_eq!(meta.props.len(), 3000); + let first = meta.find("http://n/0/", "p0").and_then(|at| meta.props.get(at)).and_then(|p| p.value.text()); + assert_eq!(first, Some("v0"), "a property given twice keeps its first value"); + assert_eq!(registry.prefix_of("http://n/499/"), Some("n499")); + let again = xmp::parse(&xmp::serialize(&meta, ®istry, false).unwrap(), &mut registry).unwrap(); + assert_eq!(again, meta); +} + +#[test] +fn blank_values_and_failed_packets_keep_their_state() { + let rdf = "\ + \n "; + let src = format!( + "new ExternalObject('lib:AdobeXMPScript'); var m = new XMPMeta({rdf:?}); var n = new XMPMeta(m.serialize());\n\ + [n.getProperty('http://a/', 'p').value, n.getArrayItem('http://a/', 'q', 1).value].join('|')" + ); + assert_eq!(string(&src), " | \n "); + let bad = "\ + x"; + let src = format!( + "new ExternalObject('lib:AdobeXMPScript'); try {{ new XMPMeta({bad:?}); }} catch (e) {{}}\n\ + String(XMPMeta.getNamespacePrefix('http://b/'))" + ); + assert_eq!(string(&src), "undefined", "a packet that fails to read registers no namespace"); +} + +/// A namespace URI or prefix over its limit is refused, and so is a namespace that would take the +/// realm's namespaces over their byte budget; a refused namespace leaves the registry as it was. +#[test] +fn namespace_lengths_and_the_registry_budget_are_bounded() { + let mut registry = Registry::default(); + let uri = |n: usize, fill: usize| format!("http://n/{n}/{}", "u".repeat(fill)); + let at_limit = uri(0, xmp::MAX_URI_BYTES - uri(0, 0).len()); + assert_eq!(at_limit.len(), xmp::MAX_URI_BYTES); + assert_eq!(registry.register(&at_limit, "a"), Ok("a".to_string())); + let over = format!("{at_limit}u"); + assert_eq!(registry.register(&over, "b"), Err(XmpError::TooLarge)); + assert_eq!(registry.register("http://p/", &"p".repeat(xmp::MAX_PREFIX_BYTES)), Ok("p".repeat(xmp::MAX_PREFIX_BYTES))); + assert_eq!(registry.register("http://q/", &"q".repeat(xmp::MAX_PREFIX_BYTES + 1)), Err(XmpError::TooLarge)); + assert_eq!(registry.register("http://p2/", &"p".repeat(xmp::MAX_PREFIX_BYTES)), Err(XmpError::TooLarge), "the `_1_` suffix counts"); + assert_eq!(registry.prefix_of(&over), None); + let mut n = 1; + let refused = loop { + let before = registry.bytes(); + match registry.register(&uri(n, 900), &format!("p{n}")) { + Ok(_) => n += 1, + Err(e) => break (e, before), + } + assert!(n < 4096, "the byte budget ends registration before the namespace count does"); + }; + assert_eq!(refused.0, XmpError::Namespaces); + assert_eq!(registry.bytes(), refused.1, "a refused namespace adds no bytes"); + assert!(registry.bytes() <= xmp::MAX_REGISTRY_BYTES); + assert_eq!(registry.prefix_of(&uri(n, 900)), None); + assert_eq!(registry.register(&at_limit, "z"), Ok("a".to_string()), "a namespace registered before keeps its prefix"); +} + +#[test] +fn long_namespaces_from_scripts_and_packets_are_refused() { + assert_eq!( + thrown("XMPMeta.registerNamespace('http://n/' + new Array(2000).join('u'), 'a')"), + "RangeError: XMPMeta.registerNamespace: the XMP data is too large" + ); + assert_eq!( + thrown("XMPMeta.registerNamespace('http://n/', new Array(200).join('a'))"), + "RangeError: XMPMeta.registerNamespace: the XMP data is too large" + ); + let long = format!("http://n/{}", "u".repeat(xmp::MAX_URI_BYTES)); + let packet = format!( + "v" + ); + let mut registry = Registry::default(); + assert_eq!(xmp::parse(&packet, &mut registry), Err(XmpError::TooLarge)); + assert_eq!(registry.prefix_of(&long), None); + assert_eq!(thrown(&format!("new XMPMeta({packet:?})")), "RangeError: XMPMeta: the XMP data is too large"); +} + +/// An error message holds at most the first 200 characters of a name, path, value or namespace +/// the script gave. +#[test] +fn error_messages_hold_a_bounded_part_of_the_script_text() { + let cases = [ + ("new XMPMeta().getProperty('http://none/' + s, 'a')", "Error: XMPMeta.getProperty: the namespace http://none/"), + ("new XMPMeta().setProperty(XMPConst.NS_DC, '1' + s, 'x')", "Error: XMPMeta.setProperty: 1"), + ("new XMPMeta().getProperty(XMPConst.NS_DC, 'a/' + s)", "RangeError: XMPMeta.getProperty: the value a/"), + ("new XMPMeta().getProperty(XMPConst.NS_DC, 'a', s)", "RangeError: XMPMeta.getProperty: the value "), + ]; + for (src, start) in cases { + let message = thrown(&format!("var s = new Array(100000).join('x'); {src}")); + assert!(message.starts_with(start), "{message}"); + assert!(message.len() < start.len() + 260, "{src}: {} characters", message.len()); + } +} + +/// With no item in the specific language, `setLocalizedText` changes the one item in the generic +/// language, and adds the specific language when there are several. +#[test] +fn localized_text_updates_a_single_generic_language_item() { + let src = "var ns = 'http://example.com/lt/'; XMPMeta.registerNamespace(ns, 'lt'); var m = new XMPMeta(); + m.setLocalizedText(ns, 'label', null, 'en-GB', 'Colour'); + m.setLocalizedText(ns, 'label', 'en', 'en-US', 'Color'); + var one = [m.countArrayItems(ns, 'label'), m.getLocalizedText(ns, 'label', null, 'en-GB'), m.getLocalizedText(ns, 'label', null, 'x-default')]; + m.setLocalizedText(ns, 'label', null, 'en-AU', 'Colour'); + m.setLocalizedText(ns, 'label', 'en', 'en-CA', 'Couleur'); + one.concat([m.countArrayItems(ns, 'label'), m.getLocalizedText(ns, 'label', null, 'en-CA'), m.getLocalizedText(ns, 'label', null, 'en-GB')]).join('|')"; + assert_eq!(string(src), "2|Color|Color|4|Couleur|Color"); +} + +/// A `setLocalizedText` that stops at the heap limit adds no array. The heap limits tried run from +/// one that holds the text to one that also holds the change. +#[test] +fn localized_text_past_the_heap_limit_adds_no_array() { + let mut stopped = 0; + let mut created = false; + let mut seen = vec![]; + for step in 0..128 { + let mut r = Realm::with_options(crate::Options::default(), Limits { heap_bytes: (256 << 10) + step * (16 << 10), ..Limits::default() }); + if let Err(e) = r.define_external_object() { + panic!("{e:?}"); + } + let text = "new ExternalObject('lib:AdobeXMPScript'); var m = new XMPMeta(); var s = 'x'; for (var k = 0; k < 18; k++) s += s;"; + if let Err(e) = r.run(text) { + seen.push(format!("{step} text {e:?}")); + continue; + } + let set = r.run("m.setLocalizedText(XMPConst.NS_DC, 'title', null, s, s);"); + let exists = r.run("m.doesPropertyExist(XMPConst.NS_DC, 'title')"); + match (set, exists) { + (Ok(_), Ok(v)) => { + assert_eq!(v, JsValue::Bool(true), "heap step {step}: the change adds the array"); + created = true; + break; + } + (Err(e), Ok(v)) => { + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "heap step {step}: {e:?}"); + assert_eq!(v, JsValue::Bool(false), "heap step {step}"); + stopped += 1; + } + (_, Err(e)) => panic!("{e:?}"), + } + } + assert!(stopped > 0, "no heap limit stopped the change: {seen:?}"); + assert!(created, "no heap limit let the change through: {seen:?}"); +} + +/// Setting the `x-default` item also changes the items that had its text, and leaves the others. +#[test] +fn localized_text_for_x_default_changes_the_items_that_matched_it() { + let src = "var ns = 'http://example.com/lt/'; XMPMeta.registerNamespace(ns, 'lt'); var m = new XMPMeta(); + m.setLocalizedText(ns, 'label', null, 'en-US', 'old'); + m.setLocalizedText(ns, 'label', null, 'fr-FR', 'vieux'); + m.setLocalizedText(ns, 'label', null, 'x-default', 'new'); + ['x-default', 'en-US', 'fr-FR'].map(function (l) { return m.getLocalizedText(ns, 'label', null, l); }).join('|')"; + assert_eq!(string(src), "new|new|vieux"); +} + +/// A packet read from `rdf:RDF` alone reads back from what it serializes to, which adds the +/// `x:xmpmeta` element around it, also with values nested near the depth limit. +#[test] +fn deeply_nested_values_read_back_after_serializing() { + let mut read = 0; + for height in 55..=66 { + let nest = format!("{}x{}", "".repeat(height - 1), "".repeat(height - 1)); + let packet = format!( + "{nest}" + ); + let mut registry = Registry::default(); + let Ok(meta) = xmp::parse(&packet, &mut registry) else { continue }; + read += 1; + let out = xmp::serialize(&meta, ®istry, true); + let again = out.as_ref().ok().map(|out| xmp::parse(out, &mut registry)); + assert_eq!(again, Some(Ok(meta)), "a value {height} elements high"); + } + assert!(read > 0, "some of the packets are read"); +} + +/// Namespaces declared only inside a structure or on a qualifier are registered when the packet +/// is read. +#[test] +fn namespaces_inside_kept_values_are_registered() { + let packet = PACKET.replace( + "", + "s1", + ); + let src = + format!("var m = new XMPMeta({packet:?}); [XMPMeta.getNamespacePrefix('http://inner/'), XMPMeta.getNamespacePrefix('http://q/')].join('|')"); + assert_eq!(string(&src), "in:|q:"); + for value in ["1", "x"] { + let packet = format!( + "{value}" + ); + assert_eq!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed), "an undeclared prefix in {value}"); + } +} + +/// Text beside an array's container keeps the property as it was written. +#[test] +fn text_beside_an_array_is_kept() { + let packet = "\ + beforexafter"; + let mut registry = Registry::default(); + let meta = xmp::parse(packet, &mut registry).unwrap(); + let out = xmp::serialize(&meta, ®istry, false).unwrap(); + assert!(out.contains("before") && out.contains("after"), "{out}"); + assert_eq!(xmp::parse(&out, &mut registry), Ok(meta)); +} + +/// No property is set in the RDF or XML namespace, which a packet cannot hold. +#[test] +fn rdf_and_xml_namespaces_hold_no_properties() { + for ns in ["http://www.w3.org/1999/02/22-rdf-syntax-ns#", "http://www.w3.org/XML/1998/namespace"] { + for name in ["foo", "li"] { + assert_eq!( + thrown(&format!("new XMPMeta().setProperty({ns:?}, {name:?}, 'x')")), + format!("Error: XMPMeta.setProperty: {name} is not a valid property name"), + "{ns}" + ); + } + assert_eq!( + thrown(&format!("new XMPMeta().appendArrayItem({ns:?}, 'foo', 'x', XMPConst.PROP_IS_ARRAY)")), + "Error: XMPMeta.appendArrayItem: foo is not a valid property name" + ); + } +} + +/// A second `define_external_object` is refused and keeps the namespaces the realm registered. +#[test] +fn a_second_external_object_is_refused() { + let mut r = realm(); + let kept = r.run("new ExternalObject('lib:AdobeXMPScript'); XMPMeta.registerNamespace('http://kept/', 'kept')"); + assert_eq!(kept.ok(), Some(JsValue::String("kept:".into()))); + let again = r.define_external_object(); + assert_eq!(again.map_err(|e| e.kind), Err(RunErrorKind::Internal)); + let prefix = r.run("new ExternalObject('lib:AdobeXMPScript'); XMPMeta.getNamespacePrefix('http://kept/')"); + assert_eq!(prefix.ok(), Some(JsValue::String("kept:".into()))); +} + +#[test] +fn an_external_object_install_can_retry_after_a_heap_limit() { + let mut failures = 0; + let mut successes = 0; + for kib in 0..=128 { + let mut realm = Realm::with_options(crate::Options { es2015: true, ..crate::Options::default() }, Limits::default()); + assert_eq!(realm.run("0").ok(), Some(JsValue::Number(0.0))); + let baseline = realm.interp().settled_heap_bytes(); + realm.set_limits(Limits { heap_bytes: baseline + (kib << 10), ..Limits::default() }); + match realm.define_external_object() { + Ok(()) => successes += 1, + Err(error) => { + assert_eq!(error.kind, RunErrorKind::Limit(LimitKind::Heap), "additional heap {kib} KiB: {error:?}"); + failures += 1; + realm.set_limits(Limits::default()); + assert!(realm.define_external_object().is_ok(), "installation could not retry after additional heap {kib} KiB"); + let result = realm.run("new ExternalObject('lib:AdobeXMPScript'); typeof XMPMeta === 'function' && typeof XMPFile === 'function'"); + assert_eq!(result.as_ref().ok(), Some(&JsValue::Bool(true)), "additional heap {kib} KiB: {result:?}"); + } + } + } + assert!(failures > 0 && successes > 0, "failures {failures}, successes {successes}"); +} + +#[test] +fn es5_external_install_reserves_every_published_member() { + let mut successes = 0; + let mut failures = 0; + for kib in 0..=128 { + let mut realm = Realm::with_options(crate::Options { es2015: false, ..crate::Options::default() }, Limits::default()); + realm.run("0").unwrap(); + let baseline = realm.interp().settled_heap_bytes(); + let limit = baseline + (kib << 10); + realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() }); + match realm.define_external_object() { + Ok(()) => { + successes += 1; + let retained = realm.interp().settled_heap_bytes(); + assert!(retained <= limit, "installation retained {retained} bytes with a {limit}-byte limit"); + } + Err(error) => { + failures += 1; + assert_eq!(error.kind, RunErrorKind::Limit(LimitKind::Heap)); + realm.set_limits(Limits::default()); + realm.define_external_object().unwrap(); + } + } + } + assert!(successes > 0 && failures > 0); +} + +#[test] +fn retained_xmp_namespaces_count_toward_the_heap_limit() { + let mut realm = realm(); + realm.run("new ExternalObject('lib:AdobeXMPScript'); 0").unwrap(); + realm.interp().collect_for_room(); + let before = realm.interp().settled_heap_bytes(); + let suffix = "x".repeat(950); + let script = format!("for (var n = 0; n < 16; n++) XMPMeta.registerNamespace('urn:' + n + ':' + {suffix:?}, 'large' + n); 0"); + realm.run(&script).unwrap(); + realm.interp().collect_for_room(); + let after = realm.interp().settled_heap_bytes(); + assert!(after >= before + 16 * suffix.len(), "retained namespace bytes must remain charged after GC: {before} -> {after}"); +} + +#[test] +fn registering_xmp_namespaces_stops_before_exceeding_the_heap_limit() { + let mut realm = realm(); + realm.run("new ExternalObject('lib:AdobeXMPScript'); 0").unwrap(); + realm.interp().collect_for_room(); + let baseline = realm.interp().settled_heap_bytes(); + realm.set_limits(Limits { heap_bytes: baseline + (32 << 10), ..Limits::default() }); + let suffix = "x".repeat(950); + let script = format!("for (var n = 0; n < 64; n++) XMPMeta.registerNamespace('urn:' + n + ':' + {suffix:?}, 'large' + n); 0"); + let result = realm.run(&script); + assert!(matches!(result, Err(ref error) if error.kind == RunErrorKind::Limit(LimitKind::Heap)), "{result:?}"); + realm.set_limits(Limits::default()); + let unchanged = realm.run(&format!("XMPMeta.getNamespacePrefix('urn:' + n + ':' + {suffix:?}) === undefined")); + assert_eq!(unchanged.ok(), Some(JsValue::Bool(true)), "the failed registration leaves no namespace entry"); +} + +/// A path argument is converted to text once, so one whose text changes on each conversion names +/// one property. +#[test] +fn paths_are_converted_once() { + let src = "function p(a, b) { var k = 0; return { toString: function () { return k++ ? b : a; } }; } + [m.getProperty(XMPConst.NS_DC, p('format', 'title')).path, m.getArrayItem(XMPConst.NS_DC, p('subject', 'title'), 1).path].join('|')"; + assert_eq!(string(&with_packet(src)), "format|subject[1]"); +} + +/// A change to a language alternative moves an `x-default` item a packet gave later to the front, +/// and keeps the order of the others. +#[test] +fn localized_text_moves_x_default_first() { + let packet = PACKET.replace( + "HelloBonjour", + "HelloHelloSalut", + ); + let src = format!( + "var m = new XMPMeta({packet:?}); m.setLocalizedText(XMPConst.NS_DC, 'title', null, 'en', 'Hi'); + [1, 2, 3].map(function (n) {{ var p = m.getArrayItem(XMPConst.NS_DC, 'title', n); return p.locale + '=' + p.value; }}).join('|')" + ); + assert_eq!(string(&src), "x-default=Hi|en=Hi|fr=Salut"); +} + +/// An item with `xml:lang=""` names no language, so its `rdf:Alt` is not a language alternative +/// and has no `ARRAY_IS_ALTTEXT` (0x1000) option, and the empty attribute is written back. +#[test] +fn an_empty_language_is_no_language() { + let packet = PACKET.replace("Bonjour", "Bonjour"); + assert!(packet.contains("xml:lang=\"\"")); + let src = format!( + "var m = new XMPMeta({packet:?}); var out = []; + try {{ m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'x-default'); out.push('read'); }} catch (e) {{ out.push(e.message); }} + try {{ m.setLocalizedText(XMPConst.NS_DC, 'title', null, 'x-default', 'Hi'); out.push('set'); }} catch (e) {{ out.push(e.message); }} + out.push((m.getProperty(XMPConst.NS_DC, 'title').options & 0x1000) != 0); + out.push(m.serialize().indexOf('xml:lang=\"\"') >= 0); + out.join('|')" + ); + assert_eq!( + string(&src), + "XMPMeta.getLocalizedText: title is not a language alternative array|XMPMeta.setLocalizedText: title is not a language alternative array|false|true" + ); +} + +/// Text beside the descriptions or their properties makes a packet malformed; whitespace there and +/// text inside a property do not. +#[test] +fn text_beside_descriptions_is_malformed() { + let rdf = |body: &str| format!("{body}"); + for body in [ + "strayx", + "x", + "strayx", + ] { + assert_eq!(xmp::parse(&rdf(body), &mut Registry::default()), Err(XmpError::Malformed), "{body}"); + } + let fine = rdf("\n \n x \n \n"); + let meta = xmp::parse(&fine, &mut Registry::default()).unwrap(); + assert_eq!(meta.props.first().and_then(|p| p.value.text()), Some(" x ")); +} + +/// The properties of one namespace share its URI, and a read stops at its budget. +#[test] +fn many_properties_under_one_long_namespace_share_it() { + let uri = format!("http://long/{}/", "u".repeat(1000)); + let body: String = (0..2000).map(|n| format!("v")).collect(); + let packet = format!( + "{body}" + ); + let meta = xmp::parse(&packet, &mut Registry::default()).unwrap(); + assert_eq!(meta.props.len(), 2000); + assert!(meta.props.windows(2).all(|w| std::rc::Rc::ptr_eq(&w[0].ns, &w[1].ns)), "one copy of the URI"); + let bytes = meta.heap_bytes(); + assert_eq!(xmp::parse_within(&packet, &mut Registry::default(), bytes / 2), Err(XmpError::Heap)); + assert_eq!(xmp::parse_within(&packet, &mut Registry::default(), bytes), Ok(meta)); + // The `rdf:about` value counts toward the budget too, in a packet with no properties. + let about = + format!("", "a".repeat(4096)); + let meta = xmp::parse(&about, &mut Registry::default()).unwrap(); + assert!(meta.props.is_empty()); + assert_eq!(xmp::parse_within(&about, &mut Registry::default(), meta.heap_bytes() - 1), Err(XmpError::Heap)); + assert_eq!(xmp::parse_within(&about, &mut Registry::default(), meta.heap_bytes()), Ok(meta)); + let r = realm().run(&format!( + "new ExternalObject('lib:AdobeXMPScript'); var s = {packet:?}; var m = new XMPMeta(s); m.getProperty('{uri}', 'p0').value + ':' + m.getProperty('{uri}', 'p1999').value" + )); + assert_eq!(r.ok(), Some(JsValue::String("v:v".into()))); +} + +/// A value with qualifiers in the `rdf:value` form gives the text and options of its `rdf:value`, +/// and an empty property element with fields as attributes is a structure; both write back as +/// they were read. +#[test] +fn rdf_value_forms_give_their_text() { + let packet = PACKET.replace( + "", + "srcv\ + rv\ + \ + \ + 1\ + plain", + ); + let shown = "['source', 'rights', 'relation', 'coverage', 'type', 'language'].map(function (n) { + var p = m.getProperty(XMPConst.NS_DC, n); return p.value + ':' + p.options; }).join('|')"; + let want = "src:16|r:80|rel:16|undefined:256|http://t/:18|plain:0"; + assert_eq!(string(&format!("var m = new XMPMeta({packet:?}); {shown}")), want); + assert_eq!(string(&format!("var m = new XMPMeta(new XMPMeta({packet:?}).serialize()); {shown}")), want); +} + +/// A packet is not written with more attributes on one element than a read takes, and a packet +/// whose `rdf:RDF` lies deep reads back from what it writes. +#[test] +fn written_packets_keep_to_the_read_limits() { + let mut registry = Registry::default(); + let mut meta = xmp::Meta::default(); + for n in 0..1023 { + let uri = format!("http://n/{n}/"); + registry.register(&uri, "n").unwrap(); + meta.props.push(xmp::Prop { ns: uri.into(), name: "p".into(), value: xmp::Value::Simple { text: "v".into(), uri: false } }); + } + assert_eq!(xmp::serialize(&meta, ®istry, false), Err(XmpError::TooLarge), "1,025 declarations in scope"); + meta.props.pop(); + let out = xmp::serialize(&meta, ®istry, false).unwrap(); + assert_eq!(xmp::parse(&out, &mut registry), Ok(meta)); + let decls: String = (0..600).map(|n| format!(" xmlns:b{n}='http://b/{n}/'")).collect(); + let fields: String = (0..600).map(|n| format!(" b{n}:k='v'")).collect(); + let kept = format!( + "x" + ); + assert_eq!(xmp::parse(&kept, &mut Registry::default()), Err(XmpError::TooLarge), "a kept value that takes 600 declarations"); + let simple: String = (0..600).map(|n| format!("v")).collect(); + let inner: String = (0..500).map(|n| format!(" xmlns:c{n}='http://c/{n}/'")).collect(); + let spread = format!( + "{simple}\ + 1" + ); + let mut registry = Registry::default(); + let meta = xmp::parse(&spread, &mut registry).unwrap(); + assert_eq!(xmp::serialize(&meta, ®istry, false), Err(XmpError::TooLarge), "600 declarations around a kept value with 502"); + let wrap = 60; + let deep = format!( + "{}v\ + 1{}", + "".repeat(wrap), + "".repeat(wrap) + ); + let mut registry = Registry::default(); + let meta = xmp::parse(&deep, &mut registry).unwrap(); + let out = xmp::serialize(&meta, ®istry, true).unwrap(); + assert_eq!(xmp::parse(&out, &mut registry), Ok(meta)); +} + +/// Inside a packet, a start or a trailer in a CDATA section or a comment is text, and a packet that +/// is not UTF-8 is passed over for the next one. +#[test] +fn packet_markers_in_sections_are_text() { + let start = ""; + for section in [format!(""), format!(""), "]]>".to_string()] { + let inner = PACKET.replace("image/svg+xml", &format!("{section}")); + let bytes = format!("binary\0{inner}"); + assert_eq!(xmp::find_packet(bytes.as_bytes()).map(|s| (s.start, s.end)), Some((7, bytes.len())), "{section}"); + } + let mut bad = PACKET.as_bytes().to_vec(); + if let Some(at) = PACKET.find("image") { + bad[at] = 0xFF; + } + let both = [bad.as_slice(), b"gap", PACKET.as_bytes()].concat(); + let span = xmp::find_packet(&both).map(|s| (s.start, s.end)); + assert_eq!(span, Some((bad.len() + 3, both.len())), "the UTF-8 packet after one that is not"); + // A section that a trailer and then a later packet's start come before the end of does not + // hide that start. + let first = [start.as_bytes(), b""].concat(); + let second = PACKET.replace("image/svg+xml", "image/svg+xml"); + let both = [first.as_slice(), second.as_bytes()].concat(); + let span = xmp::find_packet(&both).map(|s| (s.start, s.end)); + assert_eq!(span, Some((first.len(), both.len())), "the packet after an unclosed section"); +} + +#[test] +fn array_forms_follow_their_options() { + assert_eq!(Form::from_options(0x200), Form::Bag); + assert_eq!(Form::from_options(0x400), Form::Seq); + assert_eq!(Form::from_options(0x800), Form::Alt); +} + +const PIECES: &[&str] = &[ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "1", + "text & more", + "&bogus;", + "]]>", + "", + "", + "", + "", + "", + "", +]; + +/// A property of a generated packet that reads. +#[derive(Clone, Debug)] +enum Generated { + Simple(String), + Uri(String), + Array(usize, Vec<(String, Option)>), + Kept(String), +} + +fn generated_property() -> impl Strategy { + let text = "[a-zA-Z0-9 &<>\"']{0,8}"; + prop_oneof![ + text.prop_map(Generated::Simple), + "[a-z]{1,6}".prop_map(|s| Generated::Uri(format!("http://r/{s}"))), + (0..3usize, proptest::collection::vec((text, proptest::option::of("[a-z]{2}(-[A-Z]{2})?")), 0..4)) + .prop_map(|(f, items)| Generated::Array(f, items)), + text.prop_map(Generated::Kept), + ] +} + +/// The packet the properties `props` make, each named by its position. +fn generated_packet(props: &[Generated]) -> String { + let mut body = String::new(); + for (n, p) in props.iter().enumerate() { + match p { + Generated::Simple(t) => body.push_str(&format!("{}", craft_xml::esc(t))), + Generated::Uri(u) => body.push_str(&format!("")), + Generated::Array(form, items) => { + let form = ["rdf:Bag", "rdf:Seq", "rdf:Alt"][*form]; + body.push_str(&format!("<{form}>")); + for (t, lang) in items { + let lang = lang.as_ref().map(|l| format!(" xml:lang='{l}'")).unwrap_or_default(); + body.push_str(&format!("{}", craft_xml::esc(t))); + } + body.push_str(&format!("")); + } + Generated::Kept(t) => body.push_str(&format!("{}", craft_xml::esc(t))), + } + } + format!( + "{body}" + ) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + /// A packet of simple values, URIs, arrays and kept values reads, and reads back the same from + /// what it serializes to. + #[test] + fn valid_packets_round_trip(props in proptest::collection::vec(generated_property(), 0..12)) { + let text = generated_packet(&props); + let mut registry = Registry::default(); + let meta = xmp::parse(&text, &mut registry); + prop_assert!(meta.is_ok(), "{}", text); + let meta = meta.unwrap_or_default(); + prop_assert_eq!(meta.props.len(), props.len()); + let out = xmp::serialize(&meta, ®istry, true); + prop_assert!(out.is_ok(), "{}", text); + let again = xmp::parse(&out.unwrap_or_default(), &mut registry); + prop_assert_eq!(again.as_ref().ok(), Some(&meta), "{}", text); + } + + /// Any arrangement of packet pieces reads without a panic, and what reads serializes to a packet + /// that reads back the same. + #[test] + fn arbitrary_packets_never_panic_and_round_trip(pieces in proptest::collection::vec(0..PIECES.len(), 0..24)) { + let text: String = pieces.iter().map(|&i| PIECES[i]).collect(); + let mut registry = Registry::default(); + if let Ok(meta) = xmp::parse(&text, &mut registry) { + let out = xmp::serialize(&meta, ®istry, true); + prop_assert!(out.is_ok(), "{text}"); + let out = out.unwrap_or_default(); + let again = xmp::parse(&out, &mut registry); + prop_assert_eq!(again.as_ref().ok(), Some(&meta), "{}\n{}", text, out); + } + } + + /// Arbitrary bytes never make the packet parser or scanner panic. + #[test] + fn arbitrary_bytes_never_panic(bytes in proptest::collection::vec(any::(), 0..512)) { + let _ = xmp::find_packet(&bytes); + let text = String::from_utf8_lossy(&bytes); + let _ = xmp::parse(&text, &mut Registry::default()); + } + + /// Arbitrary text through the script surface ends in a value or a script error, never an + /// internal fault. + #[test] + fn arbitrary_script_values_never_fault(name in "[a-z:\\[\\]0-9/@?]{0,12}", value in "\\PC{0,16}") { + let src = format!( + "new ExternalObject('lib:AdobeXMPScript'); var m = new XMPMeta(); try {{ m.setProperty(XMPConst.NS_DC, {name:?}, {value:?}); \ + m.appendArrayItem(XMPConst.NS_DC, 'z', 0, {value:?}, XMPConst.PROP_IS_ARRAY); new XMPMeta(m.serialize()).getProperty(XMPConst.NS_DC, {name:?}) }} catch (e) {{ e.message }}" + ); + if let Err(e) = realm().run(&src) { + prop_assert!(e.kind != RunErrorKind::Internal, "{src}: {e:?}"); + } + } +} diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index 71c1b63003..3e4954d99f 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -370,38 +370,51 @@ fn long_page_warning(set: &PdfSettings, artboard: usize, w: f64, h: f64, unit: f } } -/// The RGB colours and non-CMYK images a CMYK document carries, which the export separates into -/// CMYK. Their darkest values come out as rich blacks, so the export says how many there are. +/// The RGB colours and RGB images a CMYK document carries. Its RGB colours are always separated +/// into CMYK; its RGB images only with a CMYK destination (Output › Color conversion, or a +/// PDF/X-1a preset), else they are written in RGB (#1242). The export says how many of each +/// there are: converted ones' darkest values come out as rich blacks, and kept ones aren't CMYK. +/// Grey images stay grey either way and aren't counted. #[derive(Default)] pub(crate) struct RgbInCmyk { /// Distinct RGB colours, by the bits of their channels. pub(super) colours: HashSet<[u32; 3]>, - /// Keys of the raster images that aren't CMYK. - pub(super) images: HashSet, + /// Keys of the RGB images converted to CMYK. + pub(super) converted: HashSet, + /// Keys of the RGB images written in RGB. + pub(super) kept: HashSet, +} + +/// `n` `thing`s, in the plural unless `n` is 1. +fn count(n: usize, thing: &str) -> String { + format!("{n} {thing}{}", if n == 1 { "" } else { "s" }) } impl RgbInCmyk { pub(super) fn merge(&mut self, other: RgbInCmyk) { self.colours.extend(other.colours); - self.images.extend(other.images); + self.converted.extend(other.converted); + self.kept.extend(other.kept); } /// The warning for the export report; `None` when the document has nothing of the sort. pub(super) fn warning(&self) -> Option { - let (c, i) = (self.colours.len(), self.images.len()); - if c == 0 && i == 0 { - return None; + let (c, i, k) = (self.colours.len(), self.converted.len(), self.kept.len()); + let mut sentences = vec![]; + let converted: Vec<_> = [(c, "RGB colour"), (i, "RGB image")].into_iter().filter(|(n, _)| *n > 0).map(|(n, t)| count(n, t)).collect(); + if !converted.is_empty() { + sentences.push(format!( + "{}: they are converted to CMYK through the colour settings, so dark ones can come out as rich blacks on several plates; paint them with CMYK colours (Edit › Edit Colors › Convert to CMYK) for pure black ink", + converted.join(" and ") + )); } - let mut parts = vec![]; - if c > 0 { - parts.push(format!("{c} RGB colour{}", if c == 1 { "" } else { "s" })); + if k > 0 { + let (it, is) = if k == 1 { ("it", "is") } else { ("them", "are") }; + sentences.push(format!( + "{} that {is} written in RGB, not CMYK: to write {it} in CMYK, choose Output › Color conversion › Convert to destination with a CMYK destination, or the PDF/X-1a:2001 preset", + count(k, "RGB image") + )); } - if i > 0 { - parts.push(format!("{i} RGB or grey image{}", if i == 1 { "" } else { "s" })); - } - Some(format!( - "this CMYK document has {}: they are converted to CMYK through the colour settings, so dark ones can come out as rich blacks on several plates; paint them with CMYK colours (Edit › Edit Colors › Convert to CMYK) for pure black ink", - parts.join(" and ") - )) + (!sentences.is_empty()).then(|| format!("this CMYK document has {}", sentences.join("; and "))) } } diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 454a86fc34..0c7be022eb 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -165,8 +165,12 @@ impl Exporter<'_> { let mut unconverted = false; let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); - if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { - self.rgb_in_cmyk.images.insert(key.to_string()); + // RGB images of a CMYK document go to CMYK only with a CMYK destination; grey ones stay + // grey ([`crate::images::recode`]). + if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk && !crate::images::is_grey(&blob.bytes) { + let to_cmyk = matches!(out.pixels(), Some(crate::output::Pixels::Cmyk(_))); + let set = if to_cmyk { &mut self.rgb_in_cmyk.converted } else { &mut self.rgb_in_cmyk.kept }; + set.insert(key.to_string()); } let r = if cmyk_image { let icc = out.cmyk_image_icc(blob); diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index c0b67615f6..6681c02f27 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -528,6 +528,22 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic } } +/// Are samples of type `t` grey (with or without alpha)? [`recode`] keeps such pixels grey. +fn grey_type(t: ExtendedColorType) -> bool { + use ExtendedColorType as T; + matches!(t, T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16) +} + +/// Does the image in `bytes` hold grey samples, which [`recode`] keeps grey whatever the Output +/// settings? Reads only its header; `false` for one that can't be read. +pub(crate) fn is_grey(bytes: &[u8]) -> bool { + ImageReader::new(Cursor::new(bytes)) + .with_guessed_format() + .ok() + .and_then(|r| r.into_decoder().ok()) + .is_some_and(|d| grey_type(d.original_color_type())) +} + /// Encoded image `bytes` placed `size` points wide and high, as the Compression settings `c` ask: /// resampled when its resolution is above the threshold, compressed with ZIP or JPEG, its colours /// converted by `convert` (colour images). Pixels that keep their colours keep the ICC profile @@ -554,8 +570,7 @@ pub(crate) fn recode( let jpeg = reader.format() == Some(ImageFormat::Jpeg); let Ok(mut decoder) = reader.into_decoder() else { return keep }; let dims = decoder.dimensions(); - use ExtendedColorType as T; - let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); + let grey = grey_type(decoder.original_color_type()); // Pixels in a profile they are converted from are decoded, whatever the Compression settings. // Grey pixels keep their profile unless the destination is sRGB ([`ToSrgb::grey`]). let then = to_srgb.and_then(|t| t.then); diff --git a/crates/pdf/src/tests/output.rs b/crates/pdf/src/tests/output.rs index c0049e4ca5..8653aa155d 100644 --- a/crates/pdf/src/tests/output.rs +++ b/crates/pdf/src/tests/output.rs @@ -706,3 +706,61 @@ fn colours_are_in_the_profiles_assigned_to_the_document() { assert!(r.warnings.iter().any(|w| w.contains("No Such Press")), "{:?}", r.warnings); assert!(icc_streams(&r.bytes) == [cms::icc_bytes(&working).unwrap().to_vec()]); } + +/// A 4 × 4 greyscale PNG of one level. +fn grey_png(level: u8) -> Vec { + let img = craft_image_codecs::Image::from_raw(4, 4, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, vec![level; 16]) + .unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() +} + +/// The CMYK document warning says what happens to its RGB images (#1242): with No conversion +/// they are written in RGB, and it names the settings that write them in CMYK; with a CMYK +/// destination they are converted. Grey images stay grey either way and aren't counted. +#[test] +fn the_cmyk_document_warning_says_whether_rgb_images_are_converted() { + let warning = |d: &Document, settings: Value| { + let r = pdf(d, settings); + let w: Vec<_> = r.warnings.iter().filter(|w| w.contains("this CMYK document")).cloned().collect(); + assert!(w.len() <= 1, "{w:?}"); + w.into_iter().next() + }; + let mut d = image_doc(png([200, 30, 30])); + d.color_mode = ColorMode::Cmyk; + + // No conversion: the image is written in RGB, and the warning doesn't say otherwise. + let kept = warning(&d, json!({})).unwrap(); + assert!(kept.contains("1 RGB image") && kept.contains("written in RGB"), "{kept}"); + assert!(!kept.contains("converted to CMYK"), "{kept}"); + assert!(kept.contains("Convert to destination") && kept.contains("PDF/X-1a"), "{kept}"); + + // A CMYK destination converts it. + for settings in + [json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}}), json!({"standard": "pdfX1a", "compatibility": "1.3"})] + { + let converted = warning(&d, settings.clone()).unwrap(); + assert!(converted.contains("1 RGB image") && converted.contains("converted to CMYK"), "{settings}: {converted}"); + assert!(!converted.contains("written in RGB"), "{settings}: {converted}"); + } + + // A grey image is not an RGB image: nothing to warn about. + let mut grey = image_doc(grey_png(90)); + grey.color_mode = ColorMode::Cmyk; + for settings in [json!({}), json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}})] { + assert_eq!(warning(&grey, settings.clone()), None, "{settings}"); + } + + // RGB colours keep their wording beside images kept in RGB. + let mut both = image_doc(png([200, 30, 30])); + both.color_mode = ColorMode::Cmyk; + let l = both.layers[0].id; + let n = Node::path( + both.alloc_id(), + shapes::rectangle(Rect::new(50.0, 50.0, 70.0, 70.0)), + Appearance::basic(Paint::solid(Color::Rgb { r: 0.1, g: 0.1, b: 0.1 }), Paint::None, 0.0), + ); + both.insert(Some(l), 1, n).unwrap(); + let w = warning(&both, json!({})).unwrap(); + assert!(w.contains("1 RGB colour") && w.contains("converted to CMYK") && w.contains("rich blacks"), "{w}"); + assert!(w.contains("1 RGB image") && w.contains("written in RGB"), "{w}"); +} 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.rs b/crates/ui-egui/src/canvas.rs index d13d79e4b9..cb9ab68bd1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -74,7 +74,7 @@ pub(crate) fn animated_zoom(p: &vectorcraft_engine::Prefs) -> bool { /// Whether a 3D effect is edited in its dialog: the selection's marks and widgets give way to the dialog's gizmo. pub(crate) fn revolve_editing(app: &VectorcraftApp) -> bool { - app.three_d_dialog.is_some() + crate::dialogs::three_d::editing_current_drawing(app) } /// The arrows the canvas takes with nothing in the window focused, as it takes every arrow while it has the focus: 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/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 9cf1965cfc..9e25bcbf93 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -87,6 +87,8 @@ fn thumbnails(ctx: &egui::Context) -> Thumbnails { pub struct Panes { /// The panes the last frame drew, as (window, pane rect). pub(crate) last: Vec<(Win, egui::Rect)>, + /// The UI layer that drew the last tiled canvases. + last_layer: Option, /// The slots of `last`'s windows, in the same order: which windows they were, as document /// indices shift when a document closes. last_slots: Vec>, @@ -110,6 +112,7 @@ impl Panes { /// Forget every pane. The pictures go with the next frame that does not tile. fn clear(&mut self) { self.last.clear(); + self.last_layer = None; self.last_slots.clear(); self.fits.clear(); self.at = SplitAt::default(); @@ -322,6 +325,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.fits.clear(); } app.canvas.panes.last.clear(); + app.canvas.panes.last_layer = None; app.canvas.panes.last_slots.clear(); return false; } @@ -361,8 +365,10 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { let mut lines = std::mem::take(&mut app.canvas.panes.at); let placed = lines.clone(); let mut cells: Vec<(Win, egui::Rect)> = vec![]; + let mut layer = None; let split = SplitViews::new("Documents", arranged, Bind::bound(&mut lines)).count(shown.len()).active(active_pane).show(ui, |ui, body| { cells = shown.iter().copied().zip(placed.placed(arranged, shown.len(), body.rect, body.env.direction().is_rtl())).collect(); + layer = Some(ui.layer_id()); let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, art_area(app, *w, *cell))).collect(); let unfitted = refit_resized(app, &areas); // The other panes first, so that what the canvas draws past its pane (the Contextual Task Bar) @@ -381,6 +387,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { let activated = split.output.activated; app.canvas.panes.at = lines; app.canvas.panes.last = cells; + app.canvas.panes.last_layer = layer; if let Some(&(w, _)) = activated.and_then(|i| app.canvas.panes.last.get(i)) { crate::doc_windows::show_window(app, w); } @@ -410,6 +417,20 @@ fn slot(app: &VectorcraftApp, (i, n): Win) -> Option { app.session.documents().get(i).map(|d| (d.uid, n)) } +/// The drawing and document point under a browser file drop in the last shown tiled panes. +pub(crate) fn file_drop_at(app: &VectorcraftApp, pos: egui::Pos2) -> Option<(u64, Point)> { + let panes = &app.canvas.panes; + let layer = panes.last_layer?; + if app.ui_ctx.as_ref().and_then(|ctx| ctx.layer_id_at(pos)).is_some_and(|front| front != layer) { + return None; + } + panes.last.iter().zip(&panes.last_slots).find_map(|(&(win, cell), &shown)| { + let (doc, _) = shown.filter(|&shown| Some(shown) == slot(app, win) && cell.contains(pos))?; + let view = crate::doc_windows::view(app, win)?; + view.rect.contains(pos).then(|| (doc, view.canvas(app.ui_scaling(), view.rect).to_doc(pos))) + }) +} + /// The area window `w`'s view shows its art in: what its body last showed, `cell` before the first. fn art_area(app: &VectorcraftApp, w: Win, cell: egui::Rect) -> egui::Rect { crate::doc_windows::view(app, w).map(|v| v.rect).filter(|r| r.is_positive()).unwrap_or(cell) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 04e367dce5..b059903b50 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -899,6 +899,48 @@ fn halftone_preview_hides_dot_outlines_and_keeps_selection_bounds() { assert!(outlined(&mut app), "OK brings ordinary outlines back on the applied dots"); } +#[test] +fn halftone_waits_for_the_drawing_that_opened_the_preview() { + use crate::dialogs::{halftone, host}; + + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let ctx = app.ui_ctx.clone().unwrap(); + let draw = |app: &mut VectorcraftApp, x| { + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.ellipse", json!({"x": x, "y": 40, "width": 60, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#000000"})).unwrap(); + }; + draw(&mut app, 40); + let first = app.session.doc().unwrap().doc.clone(); + draw(&mut app, 200); + let second = app.session.doc().unwrap().doc.clone(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.menuDialog", json!({"command": halftone::CMD})).unwrap(); + host::pump(&mut app, &ctx); + assert!(halftone::previewing(&app)); + let id = app.effect_dialogs.halftone.as_ref().unwrap().id; + + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Other drawing's edit").unwrap(); + let dialogs = app.dialogs().unwrap(); + dialogs.with(|h| h.set_json_field(&ctx, id, "frequency", json!(25))).unwrap(); + host::pump(&mut app, &ctx); + assert_eq!(app.session.doc().unwrap().doc, second); + assert_eq!(app.session.doc().unwrap().interaction.as_ref().unwrap().label, "Other drawing's edit"); + dialogs.with(|h| h.confirm_by_id(&ctx, id)); + host::pump(&mut app, &ctx); + assert!(app.any_dialog_open()); + assert_eq!(app.session.doc().unwrap().doc, second); + + app.run("document.activate", json!({"index": 0})).unwrap(); + host::pump(&mut app, &ctx); + assert!(halftone::previewing(&app)); + crate::tests::picks::answer_dialog(&mut app, id, &[], true); + assert!(!app.any_dialog_open()); + assert_ne!(app.session.doc().unwrap().doc, first); + assert_eq!(app.session.documents()[1].doc, second); +} + // One headless canvas frame → the shapes drawn, `Shape::Vec`s flattened. fn shapes(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { let (shapes, mut delta) = frame_output(app, ctx); 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/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index f1d1b618af..fb1465d4a4 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -1165,6 +1165,7 @@ pub(crate) use style_dialog; pub(crate) struct CharStyleOptions { inner: HostedPropertiesDialog, opening: Arc, + document: u64, } impl CharStyleOptions { @@ -1180,12 +1181,21 @@ impl CharStyleOptions { } style_dialog!(CharStyleOptions, KIND); +/// The preview and the document activation that owns it, retained until the host reports Cancel. +#[derive(Default)] +pub(crate) struct Preview { + live: LivePreview, + activation: Option<(u64, u64)>, + interaction_selection: Option>, +} + pub fn open(app: &mut VectorcraftApp, name: &str) -> Result { crate::panels::character::end_typing(app); - let doc = &app.session.active().ok_or("no document open")?.doc; + let state = app.session.active().ok_or("no document open")?; + let (document, doc) = (state.uid, &state.doc); let def = doc.char_styles.iter().find(|s| s.name == name).ok_or_else(|| format!("no character style `{name}`"))?; let opening = Arc::new(Opening::new(name, def.attrs.clone(), &doc.setup, swatch_choices(doc))); - let dialog = CharStyleOptions { inner: hosted(KIND, tl!("Character Style Options"), &opening, name).previews(), opening }; + let dialog = CharStyleOptions { inner: hosted(KIND, tl!("Character Style Options"), &opening, name).previews(), opening, document }; app.dialogs().ok_or("no window")?.with(|host| host.open(dialog)); Ok(json!({"dialog": KIND})) } @@ -1210,15 +1220,46 @@ pub fn reset_panel(app: &mut VectorcraftApp) -> Result { /// The dialog's frame work: previews the values, commits at OK, and rolls the preview back at Cancel. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; - let Some(frame) = dialogs.with(|host| host.get_mut::().map(CharStyleOptions::frame)) else { + let active = app.session.active().map(|doc| (doc.uid, app.session.tool_resets())); + let interaction_selection = app.session.active().and_then(|doc| doc.interaction.as_ref().map(|interaction| interaction.selection.clone())); + let owns_interaction = app.char_style_preview.activation == active + && app + .char_style_preview + .interaction_selection + .as_ref() + .zip(interaction_selection.as_ref()) + .is_some_and(|(owned, current)| Arc::ptr_eq(owned, current)); + let Some((document, frame)) = dialogs.with(|host| host.get_mut::().map(|d| (d.document, d.frame()))) else { if matches!(dialogs.with(|host| host.take::()), Some(DialogResult::Cancel)) { - std::mem::take(&mut app.char_style_preview).cancel(app); + let preview = std::mem::take(&mut app.char_style_preview); + if owns_interaction { + preview.live.cancel(app); + } } return; }; - let live = std::mem::take(&mut app.char_style_preview); - let (live, done) = drive(app, live, tl!("Character Style Options"), "charStyle.edit", &frame); - app.char_style_preview = live; + let done = if let Some(activation) = active.filter(|(uid, _)| *uid == document) { + if interaction_selection.is_some() && !owns_interaction { + frame.ok.then(|| Err("finish the active edit before applying Character Style Options".into())) + } else { + let preview = std::mem::take(&mut app.char_style_preview); + let live = if owns_interaction { preview.live } else { LivePreview::default() }; + let (live, answer) = drive(app, live, tl!("Character Style Options"), "charStyle.edit", &frame); + let interaction_selection = + app.session.active().and_then(|doc| doc.interaction.as_ref().map(|interaction| interaction.selection.clone())); + app.char_style_preview = Preview { live, activation: Some(activation), interaction_selection }; + answer + } + } else if frame.ok { + let reason = if app.session.documents().iter().any(|doc| doc.uid == document) { + "switch back to the document where Character Style Options was opened" + } else { + "the document where Character Style Options was opened has closed" + }; + Some(Err(reason.into())) + } else { + None + }; if let Some(done) = done { let answer = done.map(drop).map_err(|why| reason(&why)); dialogs.with(|host| { diff --git a/crates/ui-egui/src/dialogs/char_style_options/tests.rs b/crates/ui-egui/src/dialogs/char_style_options/tests.rs index 048e16077d..af7ec9253e 100644 --- a/crates/ui-egui/src/dialogs/char_style_options/tests.rs +++ b/crates/ui-egui/src/dialogs/char_style_options/tests.rs @@ -126,6 +126,150 @@ fn styled(app: &mut VectorcraftApp, attrs: Value, text: &str) -> u64 { id } +fn options_in_the_first_of_two_documents() -> VectorcraftApp { + let mut app = app(); + styled(&mut app, json!({"size": 24.0}), "Opening document"); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + styled(&mut app, json!({"size": 12.0}), "Other document"); + app.run("document.activate", json!({"index": 0})).unwrap(); + open(&mut app, "Body"); + app +} + +#[test] +fn the_style_preview_stays_in_its_opening_document() { + let mut app = options_in_the_first_of_two_documents(); + let opening = app.session.doc().unwrap().doc.clone(); + set::(&app, "name", json!("Revised")); + pump(&mut app); + assert!(app.session.in_interaction()); + app.run("document.activate", json!({"index": 1})).unwrap(); + let other = app.session.doc().unwrap().doc.clone(); + set::(&app, "size", json!(18)); + pump(&mut app); + assert_eq!(app.session.doc().unwrap().doc, other, "Preview leaves the other document's Body style unchanged"); + assert!(!app.session.in_interaction()); + + app.run("document.activate", json!({"index": 0})).unwrap(); + pump(&mut app); + assert!(app.session.doc().unwrap().doc.char_styles.iter().any(|style| style.name == "Revised")); + cancel::(&mut app); + assert_eq!(app.session.doc().unwrap().doc, opening); +} + +#[test] +fn a_style_options_confirmation_stays_in_its_opening_document() { + let mut app = options_in_the_first_of_two_documents(); + set::(&app, "preview", json!(false)); + set::(&app, "name", json!("Revised")); + app.run("document.activate", json!({"index": 1})).unwrap(); + let other = app.session.doc().unwrap().doc.clone(); + let closed = ok::(&mut app); + + assert_eq!(app.session.doc().unwrap().doc, other, "OK leaves the other document's Body style unchanged"); + assert!(!closed, "the same draft remains available"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(ok::(&mut app)); + assert!(app.session.doc().unwrap().doc.char_styles.iter().any(|style| style.name == "Revised")); +} + +#[test] +fn cancelling_style_options_leaves_the_other_documents_gesture() { + let mut app = options_in_the_first_of_two_documents(); + set::(&app, "name", json!("Revised")); + pump(&mut app); + assert!(app.session.in_interaction()); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Another gesture").unwrap(); + app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + let gesture = app.session.doc().unwrap().doc.clone(); + + cancel::(&mut app); + + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); +} + +#[test] +fn switching_back_leaves_a_new_gesture_in_the_opening_document() { + let mut app = options_in_the_first_of_two_documents(); + set::(&app, "name", json!("Revised")); + pump(&mut app); + assert!(app.session.in_interaction()); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.session.begin_interaction("Another gesture").unwrap(); + app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + let gesture = app.session.doc().unwrap().doc.clone(); + + set::(&app, "size", json!(18)); + pump(&mut app); + assert!(!ok::(&mut app)); + assert_eq!(app.session.doc().unwrap().doc, gesture); + cancel::(&mut app); + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); +} + +fn options_with_a_newer_gesture() -> VectorcraftApp { + let mut app = app(); + styled(&mut app, json!({"size": 24.0}), "Opening document"); + open(&mut app, "Body"); + set::(&app, "name", json!("Revised")); + pump(&mut app); + assert!(app.session.in_interaction()); + let resets = app.session.tool_resets(); + app.session.cancel_interaction().unwrap(); + app.session.begin_interaction("Character Style Options").unwrap(); + app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + assert_eq!(app.session.tool_resets(), resets); + app +} + +#[test] +fn cancelling_style_options_preserves_a_newer_gesture_in_the_same_document() { + let mut app = options_with_a_newer_gesture(); + let gesture = app.session.doc().unwrap().doc.clone(); + cancel::(&mut app); + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); +} + +#[test] +fn style_options_preview_preserves_a_newer_gesture_in_the_same_document() { + let mut app = options_with_a_newer_gesture(); + let gesture = app.session.doc().unwrap().doc.clone(); + set::(&app, "size", json!(18)); + pump(&mut app); + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); +} + +#[test] +fn style_options_confirmation_preserves_a_newer_gesture_in_the_same_document() { + let mut app = options_with_a_newer_gesture(); + let gesture = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + assert!(!ok::(&mut app)); + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); +} + +#[test] +fn a_first_style_preview_preserves_an_existing_gesture() { + let mut app = app(); + styled(&mut app, json!({"size": 24.0}), "Opening document"); + open(&mut app, "Body"); + app.session.begin_interaction("Character Style Options").unwrap(); + app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + let gesture = app.session.doc().unwrap().doc.clone(); + set::(&app, "size", json!(18)); + pump(&mut app); + assert_eq!(app.session.doc().unwrap().doc, gesture); + assert!(app.session.in_interaction()); +} + #[test] fn unchanged_basic_fields_preserve_original_keys() { for attrs in [ 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 76a5e62ad0..d8e88f9bae 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -51,8 +51,8 @@ const GLOBAL: &str = "global"; pub(crate) struct Open { /// The dialog's id on the host. pub id: DialogId, - /// The document whose art the dialog can adjust. - document: Option, + /// The drawing and loaded generation whose art the dialog can adjust. + document: Option<(u64, u64)>, /// The preview the dialog's values run as one interaction. pub preview: LivePreview, } @@ -87,7 +87,7 @@ impl Adjust { fn try_open(self, app: &mut VectorcraftApp) -> Result<(), String> { const NO_WINDOW: &str = "no window to open the dialog in"; let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?; - let document = app.session.active().map(|st| st.uid); + let document = app.session.active().map(|st| (st.uid, st.reverts)); if let Some(old) = (self.slot)(&mut app.color_dialogs).take() && old.document == document { @@ -103,11 +103,14 @@ impl Adjust { /// OK: keeps the preview as one undo step; an `Err` keeps the dialog open with the reason. fn commit(self, app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { - let document = app.session.active().map(|st| st.uid); - let open = (self.slot)(&mut app.color_dialogs) - .as_ref() - .filter(|open| open.document == document) - .ok_or(tl!("This adjustment can only apply to the document where it was opened."))?; + let document = app.session.active().map(|st| (st.uid, st.reverts)); + let open = (self.slot)(&mut app.color_dialogs).as_ref().ok_or(tl!("This adjustment can only apply to the document where it was opened."))?; + if open.document != document { + if open.document.zip(document).is_some_and(|((uid, _), (active, _))| uid == active) { + return Err(tl!("Reopen the color adjustment after reverting the drawing").into()); + } + return Err(tl!("This adjustment can only apply to the document where it was opened.").into()); + } open.preview.clone().commit(app, self.cmd, (self.params)(&answer.fields))?; *(self.slot)(&mut app.color_dialogs) = None; Ok(()) @@ -117,7 +120,7 @@ impl Adjust { /// dialog is gone without OK. pub(super) fn pump(self, app: &mut VectorcraftApp) { let Some(mut open) = (self.slot)(&mut app.color_dialogs).take() else { return }; - let on_its_document = app.session.active().map(|st| st.uid) == open.document; + let on_its_document = app.session.active().map(|st| (st.uid, st.reverts)) == open.document; let shown = app.dialogs().and_then(|dialogs| { dialogs.with(|host| host.get_by_id::(open.id).map(|dialog| (dialog.is_previewing(), (self.params)(dialog.fields())))) }); @@ -126,7 +129,7 @@ impl Adjust { // `run` reports a failed preview to the status line itself. let _ = open.preview.run(app, on, self.label, self.cmd, ¶ms); } else { - // Switching documents rolled back the original interaction. + // Switching or reverting the drawing rolled back the original interaction. open.preview = LivePreview::default(); } *(self.slot)(&mut app.color_dialogs) = Some(open); @@ -157,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`. @@ -214,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)), ] } @@ -330,6 +333,37 @@ mod tests { assert_ne!(fill_hex(&app, source), "#cc6666"); } + #[test] + fn stale_color_adjustment_leaves_the_fill_restored_by_revert() { + let (mut app, ctx) = 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 dir = vectorcraft_testkit::TempDir::new("color-adjustment-revert"); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"color": "#808080"})).unwrap(); + app.run("file.saveAs", json!({"path": dir.join("color.vectorcraft")})).unwrap(); + app.run("paint.setFill", json!({"color": "#406080"})).unwrap(); + open(&mut app); + let doc = app.session.active().unwrap(); + let version = (doc.uid, doc.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let doc = app.session.active().unwrap(); + assert_eq!(doc.uid, version.0); + assert_ne!(doc.reverts, version.1); + let undo = doc.history.undo.len(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert_eq!(fill_hex(&app, id), "#808080"); + + set(&app, &ctx, "r", json!(20)); + host::pump(&mut app, &ctx); + assert_eq!(fill_hex(&app, id), "#808080", "old Preview leaves the saved fill in place"); + set(&app, &ctx, "preview", json!(false)); + confirm(&mut app, &ctx); + assert_eq!(fill_hex(&app, id), "#808080", "old OK leaves the saved fill in place"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + #[test] fn color_adjustment_cancel_leaves_the_new_documents_interaction_intact() { let (mut app, ctx, [source, destination]) = two_documents("#808080"); 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/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index c6e5a6780f..bdafe12b9d 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -90,12 +90,18 @@ struct Asked { command: String, params: Value, /// The document that must still be active for a document-specific confirmation. - document: Option, + document: Option, /// The automation roots in force when asked: the command runs under them. scope: ScopeHandle, /// Automation asked ([`VectorcraftApp::automation_asked`]): the command runs as automation. automated: bool, } + +struct DocumentOwner { + uid: u64, + reverts: Option, +} + wrapped_dialog!(Question, StandardPrompt, KIND); /// A message with a Close button. @@ -136,12 +142,19 @@ pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, /// Ask about the active document. OK is valid only while that document is active. pub(crate) fn ask_in_document(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, params: Value) { - if let Some(document) = app.session.active().map(|st| st.uid) { + if let Some(document) = app.session.active().map(|st| DocumentOwner { uid: st.uid, reverts: None }) { ask_for(app, Some(document), message, detail, command, params); } } -fn ask_for(app: &mut VectorcraftApp, document: Option, message: &str, detail: &str, command: &str, params: Value) { +/// Ask about items in the active document. Reverting its contents invalidates the approval. +pub(crate) fn ask_in_document_contents(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, params: Value) { + if let Some(document) = app.session.active().map(|st| DocumentOwner { uid: st.uid, reverts: Some(st.reverts) }) { + ask_for(app, Some(document), message, detail, command, params); + } +} + +fn ask_for(app: &mut VectorcraftApp, document: Option, message: &str, detail: &str, command: &str, params: Value) { let Some(dialogs) = app.dialogs() else { app.status(format!("{message} (no window to ask in)")); return; @@ -278,8 +291,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { && answer.choice == PromptChoice::Proceed && let Some(Asked { command, params, document, scope, automated }) = answer.take_tag::() { - if document.is_some_and(|document| app.session.active().is_none_or(|st| st.uid != document)) { - app.status(tl!("This dialog was opened in a different document.")); + let refusal = document.and_then(|owner| match app.session.active() { + Some(st) if st.uid == owner.uid => { + owner.reverts.filter(|reverts| *reverts != st.reverts).map(|_| tl!("The document was reverted. Reopen this dialog to continue.")) + } + _ => Some(tl!("This dialog was opened in a different document.")), + }); + if let Some(reason) = refusal { + app.status(reason); } else if let Err(e) = scope.run(|| crate::file_asks::as_automated(app, automated, |app| app.run(&command, params))) { app.status(e); } 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/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index 60ff63e67f..a5b7e40b56 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -150,8 +150,8 @@ pub(crate) struct Pick { pub id: DialogId, /// The key of the swatch that asked. pub key: String, - /// The document that contains the dimension. - pub document: u64, + /// The document and loaded contents that contain the dimension. + pub document: (u64, u64), /// The dimension the colour goes to. pub target: NodeId, } @@ -343,9 +343,13 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) { let Some(finished) = dialogs.with(|host| host.take_by_id::(pick.id)) else { return }; app.object_dialogs.dimension = None; let Some(ColorPickerResult { picked, .. }) = finished.ok() else { return }; - if app.session.active().map(|st| st.uid) != Some(pick.document) { + let Some(source) = app.session.active().filter(|st| st.uid == pick.document.0) else { app.status("The active document changed while the Color Picker was open"); return; + }; + if source.reverts != pick.document.1 { + app.status(tl!("The document was reverted. Reopen this dialog to continue.")); + return; } if let Some(mut o) = options_of(app, pick.target) && set_color(&mut o, &pick.key, picked.color) @@ -721,7 +725,7 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) { }); } if let Some(request) = edited.pick - && let Some(document) = app.session.active().map(|st| st.uid) + && let Some(document) = app.session.active().map(|st| (st.uid, st.reverts)) && let Some(dialogs) = app.dialogs() { let key = request.key.clone(); @@ -822,6 +826,51 @@ mod tests { assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [17, 34, 51]); } + #[test] + fn dimension_properties_picker_cannot_edit_a_dimension_restored_by_file_revert() { + use crate::tests::panel_harness::Panel; + + let dir = vectorcraft_testkit::TempDir::new("dimension-color-revert"); + let mut app = VectorcraftApp::new(vectorcraft_engine::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 made = app.run("dimension.create", json!({"a": [0, 0], "b": [72, 0], "options": {"lineColor": [17, 34, 51]}})).unwrap(); + let dimension = NodeId(made["id"].as_u64().unwrap()); + app.run("file.saveAs", json!({"path": dir.join("Dimension.vectorcraft")})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [dimension.0]})).unwrap(); + let state = app.session.active().unwrap(); + let opening = (state.uid, state.reverts); + let mut panel = Panel::new(app, properties_section); + let ctx = panel.ctx().clone(); + let host = WindowDialogs::of(&ctx, &WindowKey::main()); + let choose = |panel: &mut Panel| { + panel.click("Line Color"); + let id = panel.app().object_dialogs.dimension.as_ref().unwrap().id; + host.with(|h| h.set_json_field(&ctx, id, "color", json!("#123456"))).unwrap(); + id + }; + let stale = choose(&mut panel); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + let (drawing, undo) = { + let app = panel.app(); + let state = app.session.active().unwrap(); + ((state.uid, state.reverts), state.history.undo.len()) + }; + assert_eq!(drawing, (opening.0, opening.1 + 1)); + assert!(host.with(|h| h.confirm_by_id(&ctx, stale))); + pump(&mut panel.app(), &ctx); + assert_eq!(options_of(&panel.app(), dimension).unwrap().line_color, [17, 34, 51]); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + + panel.app().run("select.set", json!({"ids": [dimension.0]})).unwrap(); + let fresh = choose(&mut panel); + assert!(host.with(|h| h.confirm_by_id(&ctx, fresh))); + pump(&mut panel.app(), &ctx); + assert_eq!(options_of(&panel.app(), dimension).unwrap().line_color, [18, 52, 86]); + } + /// The Arrow Style rule of `ui.dialog.set` and the saved style: a head clears with `arrowStyle`, a built-in head /// sets its entry's two values, a name that is no built-in head is refused, and a draft that does not validate /// cannot be saved. diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index a515addb0e..cf8b1e113e 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -10,7 +10,7 @@ use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use craft::imaging::ui::filter_gallery::{ EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGallerySession, FilterIndex, FilterTree, @@ -20,9 +20,9 @@ use craft::theme::variant::Tone; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, HoldsOk, StackDialog, dialog_id}; -use craft::ui::display::Picture; +use craft::ui::display::{Picture, PictureSize}; use craft::ui::layout_components::{Row, Stack}; -use craft::ui::list::ThumbAspect; +use craft::ui::list::{ThumbAspect, ThumbSize}; use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue}; use craft::ui::primitives::textures::{Revision, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails}; @@ -32,6 +32,7 @@ use craft::ui::runtime::words::CommonWords; use craft::ui::sections::{DialogRole, FooterButton}; use egui::{Context, Ui}; use serde_json::{Map, Value, json}; +use vectorcraft_doc::Selection; use vectorcraft_effects::{EffectInfo, PIXEL_EFFECTS, PixelSpace}; use vectorcraft_geom::{Affine, Point}; @@ -45,7 +46,7 @@ use crate::file_asks::Owner; /// Thumbnail of one filter, in pixels at most. The drawing is original; the filter is this app's. const THUMB: usize = 36; -/// In-dialog preview, in pixels, drawn at twice this size. +/// Sample image dimensions before the dialog scales the image to its display size. const PREVIEW_W: usize = 120; const PREVIEW_H: usize = 84; @@ -75,35 +76,121 @@ struct StackEntry { params: Map, } -/// What the app keeps of the open gallery: the dialog's id and the canvas preview it runs. +/// What the app keeps of the open gallery and the canvas preview it runs. pub(crate) struct Open { id: DialogId, + opening: Arc<()>, + source: (u64, u64), preview: LivePreview, + preview_owner: Option, +} + +/// The interaction and batch preview last written by this gallery. +struct PreviewOwner { + selection: Weak, + batch: Option<(String, Value)>, +} + +impl Open { + fn check_source(&self, app: &VectorcraftApp) -> Result<(), String> { + let Some(doc) = app.session.active().filter(|doc| doc.uid == self.source.0) else { + return Err(tl!("Return to the original drawing to apply these effects").into()); + }; + if doc.reverts != self.source.1 { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + Ok(()) + } + + fn owns_preview(&self, app: &VectorcraftApp) -> bool { + app.session.active().filter(|doc| (doc.uid, doc.reverts) == self.source).and_then(|doc| doc.interaction.as_ref()).is_some_and(|interaction| { + self.preview_owner.as_ref().is_some_and(|owner| { + owner.selection.upgrade().is_some_and(|selection| Arc::ptr_eq(&selection, &interaction.selection)) + && owner.batch == interaction.preview + }) + }) + } + + fn cancel_preview(self, app: &mut VectorcraftApp) { + if self.owns_preview(app) { + self.preview.cancel(app); + } + } + + fn ready_to_edit(&mut self, app: &mut VectorcraftApp) -> Result { + if self.owns_preview(app) { + return Ok(true); + } + self.preview = LivePreview::default(); + self.preview_owner = None; + if app.session.in_interaction() { + app.keep_typing()?; + } + Ok(!app.session.in_interaction()) + } + + fn run_preview(&mut self, app: &mut VectorcraftApp, on: bool, batch: &Value) -> Result<(), String> { + if (on || self.owns_preview(app)) && self.ready_to_edit(app)? { + let ran = self.preview.run(app, on, LABEL, COMMAND, batch); + if !on { + self.preview_owner = None; + } else if ran.is_some() { + self.preview_owner = app + .session + .active() + .and_then(|doc| doc.interaction.as_ref()) + .map(|interaction| PreviewOwner { selection: Arc::downgrade(&interaction.selection), batch: interaction.preview.clone() }); + } + } + Ok(()) + } } /// Opens the gallery on the current selection. OK is held: [`commit`] keeps the previewed stack, and a refusal /// keeps the dialog open with its reason; Cancel takes the canvas preview away. pub fn open(app: &mut VectorcraftApp, _: &Value) -> Result { - if app.session.active().is_none_or(|s| s.selection.is_empty()) { + let Some(doc) = app.session.active().filter(|doc| !doc.selection.is_empty()) else { return Err(tl!("Select artwork to apply effects").into()); - } + }; + let source = (doc.uid, doc.reverts); let dialog = EffectGalleryDialog::new(app); - let rollback = |app: &mut VectorcraftApp| { - if let Some(open) = app.effect_dialogs.gallery.take() { - open.preview.cancel(app); + let opening = Arc::clone(&dialog.opening); + let cancelled = Arc::clone(&opening); + let rollback = move |app: &mut VectorcraftApp| { + if app.effect_dialogs.gallery.as_ref().is_some_and(|open| Arc::ptr_eq(&cancelled, &open.opening)) + && let Some(open) = app.effect_dialogs.gallery.take() + { + open.cancel_preview(app); } }; let options = HeldOptions { cancel: Some(Box::new(rollback)), ..HeldOptions::default() }; let id = open_held_with(app, dialog, commit, options).ok_or("no window")?; - app.effect_dialogs.gallery = Some(Open { id, preview: LivePreview::default() }); + if let Some(old) = app.effect_dialogs.gallery.take() { + old.cancel_preview(app); + } + app.effect_dialogs.gallery = Some(Open { id, opening, source, preview: LivePreview::default(), preview_owner: None }); Ok(Value::Null) } /// The held OK: keeps the previewed stack as one undo step. A refused batch leaves the gallery and its preview open. -fn commit(app: &mut VectorcraftApp, batch: &Value) -> Result<(), String> { - let Some(open) = app.effect_dialogs.gallery.take() else { return app.run(COMMAND, batch.clone()).map(drop) }; - let committed = open.preview.clone().commit(app, COMMAND, batch.clone()).map(drop); +fn commit(app: &mut VectorcraftApp, answer: &GalleryAnswer) -> Result<(), String> { + let Some(mut open) = app.effect_dialogs.gallery.take() else { + return Err(tl!("The Effect Gallery is closed").into()); + }; + if !Arc::ptr_eq(&answer.opening, &open.opening) { + app.effect_dialogs.gallery = Some(open); + return Err(tl!("The Effect Gallery is closed").into()); + } + let ready = open + .check_source(app) + .and_then(|()| if open.ready_to_edit(app)? { Ok(()) } else { Err(tl!("Finish the current edit before applying the effects").into()) }); + if let Err(why) = ready { + app.effect_dialogs.gallery = Some(open); + return Err(why); + } + let committed = std::mem::take(&mut open.preview).commit(app, COMMAND, answer.batch.clone()).map(drop); if committed.is_err() { + open.preview_owner = None; app.effect_dialogs.gallery = Some(open); } committed @@ -116,7 +203,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { let Some(mut open) = app.effect_dialogs.gallery.take() else { return }; let id = open.id; let shown = dialogs.with(|host| { - host.get_mut_by_id::(id).map(|dialog| { + host.get_mut_by_id::(id).filter(|dialog| Arc::ptr_eq(&open.opening, &dialog.opening)).map(|dialog| { let visible = dialog.entries(true); let asked = dialog.asked.take().map(|layer| (Arc::clone(&dialog.opening), layer)); (dialog.preview_on && !visible.is_empty(), stack_batch_params(&visible), asked) @@ -126,8 +213,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { app.effect_dialogs.gallery = Some(open); return; }; - // `run` reports a failed preview itself. - let _ = open.preview.run(app, on, LABEL, COMMAND, &batch); + if open.check_source(app).is_ok() + && let Err(why) = open.run_preview(app, on, &batch) + { + app.status(why); + } app.effect_dialogs.gallery = Some(open); if let Some((opening, layer)) = asked { ask_texture(app, id, opening, layer); @@ -137,6 +227,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { /// Load Texture follows `layer` within its gallery opening and drops the reply when either is gone. fn ask_texture(app: &mut VectorcraftApp, id: DialogId, opening: Arc<()>, layer: LayerId) { effect::pick_texture(app, Owner::Free, move |app, _, fields| { + let live = app.effect_dialogs.gallery.as_ref().is_some_and(|open| { + Arc::ptr_eq(&opening, &open.opening) && app.session.documents().iter().any(|doc| (doc.uid, doc.reverts) == open.source) + }); + if !live { + return; + } let Some(dialogs) = app.dialogs() else { return }; dialogs.with(|host| { if let Some(dialog) = host.get_mut_by_id::(id).filter(|dialog| Arc::ptr_eq(&opening, &dialog.opening)) { @@ -291,15 +387,22 @@ impl EffectGalleryDialog { } } +/// The stack filed for OK and the opening that supplied it. +#[derive(Clone)] +pub(crate) struct GalleryAnswer { + opening: Arc<()>, + batch: Value, +} + impl HoldsOk for EffectGalleryDialog { - type Answer = Value; + type Answer = GalleryAnswer; fn held_ok(self) -> Self { self } - fn take_ok(&mut self) -> Option { - self.held.take() + fn take_ok(&mut self) -> Option { + Some(GalleryAnswer { opening: Arc::clone(&self.opening), batch: self.held.take()? }) } fn answer_ok(&mut self, answer: Result<(), Label>) { @@ -356,7 +459,7 @@ impl StackDialog for EffectGalleryDialog { let Some(layer) = effects.get(current) else { return }; let image = || color_image(&preview_rgba(&visible, PREVIEW_W, PREVIEW_H), PREVIEW_W, PREVIEW_H); Stack::new().show(ui, |ui, _| { - Picture::new(tl!("Preview"), key, &image).aspect(ThumbAspect::new(10, 7)).show(ui); + Picture::new(tl!("Preview"), key, &image).aspect(ThumbAspect::new(10, 7)).extent(PictureSize::Sample(ThumbSize::Large)).show(ui); Row::new().show(ui, |ui, _| { let tree = FilterTree::new(index, &layer.filter, &thumbs, &Thumbs).layout(FilterTreeLayout::Lists).show(ui); if let Some(filter) = tree.picked { @@ -616,6 +719,122 @@ mod tests { app.session.active().unwrap().doc.node(NodeId(node)).unwrap().appearance.effects.clone() } + #[test] + fn localized_compact_gallery_pointer_applies_and_cancels() { + use egui::accesskit::Role; + use egui::{Event, Modifiers, MouseWheelSource, MouseWheelUnit, PointerButton, Pos2, RawInput, Rect, TouchPhase, pos2, vec2}; + + let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let mut preview_heights = Vec::new(); + for language in ["en", "de", "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 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: Option| { + frame(app, vec![]); + let nodes = frame(app, vec![]).platform_output.accesskit_update?.nodes; + let node = nodes.iter().map(|(_, node)| node).find(|node| { + let named = node.label() == Some(label) + || node.labelled_by().iter().any(|id| nodes.iter().any(|(key, name)| key == id && name.label() == Some(label))); + named && role.is_none_or(|role| node.role() == role) && node.bounds().is_some() + })?; + let bounds = node.bounds()?; + Some(Rect::from_min_max(pos2(bounds.x0 as f32, bounds.y0 as f32), pos2(bounds.x1 as f32, bounds.y1 as f32))) + }; + let click = |app: &mut VectorcraftApp, at: Pos2| { + assert!(viewport.contains(at), "{language}: pointer target is outside the actual 800 × 500 viewport: {at:?}"); + 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![]); + }; + let reach = |app: &mut VectorcraftApp, name: &str, role: Option, x: f32| { + let mut found = None; + for _ in 0..7 { + found = locate(app, name, role); + if let Some(rect) = found.filter(|rect| viewport.contains(rect.center())) { + return rect; + } + frame(app, vec![Event::PointerMoved(pos2(x, 310.0))]); + frame( + app, + vec![Event::MouseWheel { + unit: MouseWheelUnit::Point, + delta: vec2(0.0, -110.0), + phase: TouchPhase::Move, + modifiers: Modifiers::NONE, + source: MouseWheelSource::Unknown, + }], + ); + } + panic!("{language}: {name} cannot be reached in the actual viewport: {found:?}"); + }; + let label = |name: &'static str| crate::i18n::tr(lang, name); + + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let node = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let history = app.session.active().unwrap().history.undo.len(); + frame(&mut app, vec![]); + assert_eq!(ctx.content_rect(), viewport); + app.run("ui.effectGalleryDialog", json!({})).unwrap(); + let gallery = locate(&mut app, label("Effect Gallery"), Some(Role::Dialog)).expect("localized Effect Gallery"); + let picture = locate(&mut app, label("Preview"), Some(Role::Image)).expect("localized preview image"); + let ok = locate(&mut app, label("OK"), Some(Role::Button)).expect("localized OK button"); + eprintln!("{language}: window {viewport:?}, Gallery {gallery:?}, picture {picture:?}, OK {ok:?}"); + preview_heights.push((language, picture.height())); + assert!(app.session.in_interaction(), "{language}: initial live preview is active"); + + let cutout_label = crate::i18n::effect_name(lang, "artistic.cutout").unwrap(); + let cutout = reach(&mut app, &cutout_label, None, 330.0); + click(&mut app, cutout.center()); + assert_eq!( + effects(&app, node).first().map(|effect| effect.id.as_str()), + Some("artistic.cutout"), + "{language}: filter click updates preview" + ); + + let levels_label = label("Levels"); + let levels = if let Some(rect) = locate(&mut app, levels_label, None) { + rect + } else { + let rect = reach(&mut app, "Levels", None, 550.0); + eprintln!("{language}: generic setting shown as Levels instead of {levels_label}"); + rect + }; + let preview = reach(&mut app, label("Preview"), Some(Role::CheckBox), 550.0); + eprintln!("{language}: Cutout {cutout:?}, Levels {levels:?}, Preview checkbox {preview:?}"); + assert!(viewport.contains(levels.center()), "{language}: Levels numeric field is reachable"); + click(&mut app, preview.center()); + assert!(effects(&app, node).is_empty(), "{language}: turning Preview off restores the original"); + click(&mut app, ok.center()); + let applied = effects(&app, node); + assert_eq!(applied.len(), 1, "{language}: pointer OK applies one effect"); + assert_eq!(applied[0].id, "artistic.cutout"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1); + assert!(!app.session.in_interaction()); + + app.run("ui.effectGalleryDialog", json!({})).unwrap(); + let cancel = locate(&mut app, label("Cancel"), Some(Role::Button)).expect("localized Cancel button"); + assert!(app.session.in_interaction(), "{language}: reopening starts another preview"); + click(&mut app, cancel.center()); + let after_cancel = effects(&app, node); + assert_eq!(after_cancel.len(), 1, "{language}: pointer Cancel discards only the second preview"); + assert_eq!(after_cancel[0].id, "artistic.cutout"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1); + assert!(!app.session.in_interaction()); + } + assert!(preview_heights.iter().all(|(_, height)| *height >= 64.0), "the preview is an artwork sample: {preview_heights:?}"); + } + #[test] fn stack_preview_is_one_interaction() { let (mut app, ctx, node) = drawing(); @@ -716,4 +935,123 @@ mod tests { assert_eq!(answers, [false, false], "a reopened gallery keeps its own textures"); let _ = std::fs::remove_dir_all(&dir); } + + fn ownership_stack(app: &VectorcraftApp, ctx: &egui::Context) { + set(app, ctx, "effects", json!([{ "filter": "artistic.cutout", "visible": true, "params": { "levels": 3 } }])); + } + + fn second_drawing(app: &mut VectorcraftApp) -> u64 { + app.run("file.new", json!({"width": 220, "height": 220})).unwrap(); + app.run("shape.rectangle", json!({"x": 80, "y": 80, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap() + } + + fn hold_ok(app: &VectorcraftApp, ctx: &egui::Context) { + assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(ctx, id()))); + } + + #[test] + fn gallery_ownership_preview_resumes_in_the_opening_drawing() { + let (mut app, ctx, original) = drawing(); + ownership_stack(&app, &ctx); + frame(&mut app, &ctx); + assert_eq!(effects(&app, original)[0].id, "artistic.cutout"); + let other = second_drawing(&mut app); + frame(&mut app, &ctx); + assert!(effects(&app, other).is_empty(), "gallery preview reached the other drawing"); + assert!(!app.session.in_interaction()); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx); + assert_eq!(effects(&app, original)[0].id, "artistic.cutout"); + } + + #[test] + fn gallery_ownership_ok_refuses_the_other_drawing_and_can_retry() { + let (mut app, ctx, original) = drawing(); + ownership_stack(&app, &ctx); + hold_ok(&app, &ctx); + let other = second_drawing(&mut app); + let history = app.session.active().unwrap().history.undo.len(); + frame(&mut app, &ctx); + assert!(effects(&app, other).is_empty(), "gallery OK reached the other drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history); + app.run("document.activate", json!({"index": 0})).unwrap(); + let history = app.session.active().unwrap().history.undo.len(); + hold_ok(&app, &ctx); + frame(&mut app, &ctx); + assert_eq!(effects(&app, original)[0].id, "artistic.cutout"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1); + } + + #[test] + fn gallery_ownership_cancel_preserves_the_other_drawings_edit() { + let (mut app, ctx, _) = drawing(); + ownership_stack(&app, &ctx); + frame(&mut app, &ctx); + second_drawing(&mut app); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id()))); + frame(&mut app, &ctx); + assert!(app.session.in_interaction(), "gallery Cancel ended the other drawing's edit"); + assert!(app.session.active().unwrap().doc == before); + } + + #[test] + fn gallery_ownership_cancel_preserves_a_replaced_preview_in_the_same_drawing() { + let (mut app, ctx, _) = drawing(); + ownership_stack(&app, &ctx); + frame(&mut app, &ctx); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id()))); + frame(&mut app, &ctx); + assert!(app.session.in_interaction(), "gallery Cancel ended another preview on the same interaction"); + assert!(app.session.active().unwrap().doc == before); + } + + #[test] + fn gallery_ownership_replacement_keeps_its_own_preview_and_answer() { + let (mut app, ctx, original) = drawing(); + ownership_stack(&app, &ctx); + frame(&mut app, &ctx); + super::open(&mut app, &json!({})).unwrap(); + set(&app, &ctx, "effects", json!([{ "filter": "artistic.cutout", "visible": true, "params": { "levels": 5 } }])); + frame(&mut app, &ctx); + assert!(app.effect_dialogs.gallery.is_some(), "a replaced gallery's Cancel removed the new opening"); + assert_eq!(effects(&app, original)[0].params["levels"], 5); + hold_ok(&app, &ctx); + frame(&mut app, &ctx); + assert_eq!(effects(&app, original)[0].params["levels"], 5); + } + + #[test] + fn gallery_ownership_ok_refuses_a_reloaded_drawing() { + let (mut app, ctx, original) = drawing(); + 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("effect-gallery-opening-revert"); + let path = folder.join("drawing.vectorcraft"); + app.run("file.saveAs", json!({"path": path})).unwrap(); + app.run("shape.rectangle", json!({"x": 80, "y": 80, "width": 30, "height": 30})).unwrap(); + app.run("select.set", json!({"ids": [original]})).unwrap(); + let source = app.session.active().unwrap(); + let (uid, generation) = (source.uid, source.reverts); + ownership_stack(&app, &ctx); + hold_ok(&app, &ctx); + 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]})).unwrap(); + let history = app.session.active().unwrap().history.undo.len(); + frame(&mut app, &ctx); + assert!(effects(&app, original).is_empty(), "gallery OK reached the reloaded drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history); + super::open(&mut app, &json!({})).unwrap(); + ownership_stack(&app, &ctx); + hold_ok(&app, &ctx); + frame(&mut app, &ctx); + assert_eq!(effects(&app, original)[0].id, "artistic.cutout"); + } } 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 a7079a2021..7b28dc305d 100644 --- a/crates/ui-egui/src/dialogs/envelope.rs +++ b/crates/ui-egui/src/dialogs/envelope.rs @@ -61,8 +61,8 @@ pub(crate) struct Open { pub id: DialogId, /// Which of the three dialogs it is. pub kind: &'static str, - /// The drawing that supplied the selection and defaults at opening. - document: Option, + /// The drawing and loaded contents that supplied the selection and defaults at opening. + document: Option<(u64, u64)>, /// The envelope the dialog previews. pub preview: LivePreview, // PLAN: ef.C11's `Open` has no `generation`; the same kind reopened has the same id, so the id cannot tell the held Cancel of the replaced dialog from the new one's. @@ -72,7 +72,7 @@ pub(crate) struct Open { impl Open { fn on_original_drawing(&self, app: &VectorcraftApp) -> bool { - app.session.active().map(|st| st.uid) == self.document + app.session.active().map(|st| (st.uid, st.reverts)) == self.document } fn cancel_preview(self, app: &mut VectorcraftApp) { @@ -186,7 +186,7 @@ pub fn open(app: &mut VectorcraftApp, id: &str) -> Result { /// Options dialog sets the defaults for new envelopes and has nothing to preview. fn open_dialog(app: &mut VectorcraftApp, kind: &'static str, values: Map, envelope: bool) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let document = app.session.active().map(|st| st.uid); + let document = app.session.active().map(|st| (st.uid, st.reverts)); if let Some(previous) = app.effect_dialogs.envelope.take() { let id = previous.id; previous.cancel_preview(app); @@ -197,7 +197,7 @@ fn open_dialog(app: &mut VectorcraftApp, kind: &'static str, values: Map Result<(), String> return Err("the envelope dialog is gone".into()); }; 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 apply the envelope").into()); } let kind = open.kind; @@ -450,6 +453,114 @@ mod tests { app.effect_dialogs.envelope.as_ref().map(|open| open.id).expect("an open envelope dialog") } + fn type_count(panel: &mut crate::tests::panel_harness::Panel, name: &str, text: &str) { + panel.click(name); + 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_warp_choice_radio_and_slider_edits_reach_the_preview_and_ok() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + + let (app, _) = app_with_rect(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + let before = panel.app().session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut panel.app(), MAKE_WARP, json!({})); + panel.frame(); + let opening_bounds = envelope(&panel.app()).1.geometric_bounds(); + panel.click_role("Style", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + panel.click("Vertical"); + panel.click_role("Bend", Role::SLIDER); + panel.key(egui::Key::ArrowLeft, egui::Modifiers::NONE); + panel.frame(); + let id = dialog(&panel.app()); + let fields = json_fields(&panel.app(), id); + assert_ne!(fields["style"], "arc"); + assert_ne!(fields["bend"], 50.0); + let preview = envelope(&panel.app()).1; + let NodeKind::Envelope { ref kind, .. } = preview.kind else { panic!("an envelope preview") }; + let EnvelopeKind::Warp { style, bend, horizontal, .. } = &**kind else { panic!("a warp") }; + assert_eq!(style.as_str(), fields["style"].as_str().unwrap()); + assert_eq!(*bend, fields["bend"].as_f64().unwrap()); + assert!(!*horizontal); + let bounds = preview.geometric_bounds(); + assert_ne!(bounds, opening_bounds, "the nondefault warp changes the preview geometry"); + panel.click("OK"); + panel.frame(); + panel.frame(); + assert!(open_ids(&panel.app()).is_empty()); + assert_eq!(envelope(&panel.app()).1.geometric_bounds(), bounds); + assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before + 1); + } + + #[test] + fn real_mesh_counts_and_reset_maintain_shape_edits_reach_the_model() { + use crate::tests::panel_harness::Panel; + + let (app, _) = app_with_rect(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + crate::menus::invoke(&mut panel.app(), MAKE_MESH, json!({})); + type_count(&mut panel, "Rows", "2"); + type_count(&mut panel, "Columns", "3"); + assert!( + matches!(envelope(&panel.app()).1.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Mesh { rows: 2, cols: 3, .. })) + ); + panel.click("OK"); + panel.frame(); + panel.frame(); + let confirmed = envelope(&panel.app()).1; + crate::menus::invoke(&mut panel.app(), MAKE_MESH, json!({})); + panel.frame(); + assert!(panel.shows("Maintain Envelope Shape")); + panel.click("Maintain Envelope Shape"); + type_count(&mut panel, "Rows", "1"); + let id = dialog(&panel.app()); + assert_eq!(json_fields(&panel.app(), id)["maintainShape"], false); + assert!( + matches!(envelope(&panel.app()).1.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Mesh { rows: 1, cols: 3, .. })) + ); + panel.click("Cancel"); + panel.frame(); + assert_eq!(envelope(&panel.app()).1, confirmed); + } + + #[test] + fn real_options_controls_enable_dependents_and_confirm_defaults_without_preview() { + use crate::tests::panel_harness::Panel; + + let (mut app, _) = app_with_rect(); + app.run(OPTIONS_CMD, json!({"distortAppearance": false, "distortLinearGradients": false})).unwrap(); + let initial = app.session.execute("object.envelope.info", &json!({})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + crate::menus::invoke(&mut panel.app(), OPTIONS_CMD, json!({})); + panel.frame(); + assert!(!panel.enabled("Distort Linear Gradients")); + panel.click("Distort Appearance"); + assert!(panel.enabled("Distort Linear Gradients")); + panel.click("Distort Linear Gradients"); + panel.click("Anti-Alias"); + assert!(!panel.app().session.in_interaction(), "defaults have no artwork preview"); + panel.click("OK"); + panel.frame(); + panel.frame(); + let info = panel.app().session.execute("object.envelope.info", &json!({})).unwrap(); + assert_eq!(info["distortAppearance"], true); + assert_eq!(info["distortLinearGradients"], true); + assert_eq!(info["antiAlias"].as_bool(), initial["antiAlias"].as_bool().map(|on| !on)); + crate::menus::invoke(&mut panel.app(), OPTIONS_CMD, json!({})); + panel.frame(); + panel.click("Anti-Alias"); + panel.click("Cancel"); + panel.frame(); + assert_eq!(panel.app().session.execute("object.envelope.info", &json!({})).unwrap(), info); + } + #[test] fn warp_dialog_previews_and_ok_keeps_one_step() { let (mut app, rect) = app_with_rect(); @@ -517,6 +628,45 @@ mod tests { assert!(matches!(node.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Warp { bend: 31.0, .. }))); } + #[test] + fn envelope_warp_and_mesh_do_not_preview_or_apply_to_restored_art() { + for command in [MAKE_WARP, MAKE_MESH] { + let (mut app, rect) = app_with_rect(); + let dir = vectorcraft_testkit::TempDir::new("envelope-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(); + app.run("select.set", json!({"ids": [rect.0]})).unwrap(); + open(&mut app, command).unwrap(); + let id = dialog(&app); + pump(&mut app); + assert!(matches!(envelope(&app).1.kind, NodeKind::Envelope { .. })); + let source = app.session.active().unwrap(); + let (uid, reverts) = (source.uid, source.reverts); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [rect.0]})).unwrap(); + let loaded = app.session.active().unwrap(); + assert_eq!((loaded.uid, loaded.reverts), (uid, reverts + 1)); + let undo = loaded.history.undo.len(); + pump(&mut app); + assert!(matches!(envelope(&app).1.kind, NodeKind::Path { .. }), "{command} preview"); + let ctx = app.ui_ctx.clone().unwrap(); + host(&app, |h| h.confirm_by_id(&ctx, id)); + pump(&mut app); + assert!(matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_)))); + assert!(matches!(envelope(&app).1.kind, NodeKind::Path { .. }), "{command} approval"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + dismiss(&mut app, id); + open(&mut app, command).unwrap(); + let fresh = dialog(&app); + accept(&mut app, fresh); + assert!(matches!(envelope(&app).1.kind, NodeKind::Envelope { .. })); + } + } + #[test] fn cancelling_an_envelope_dialog_keeps_the_other_drawings_active_edit() { let (mut app, _) = app_with_rect(); diff --git a/crates/ui-egui/src/dialogs/expand.rs b/crates/ui-egui/src/dialogs/expand.rs index 9f810b6117..550f736a42 100644 --- a/crates/ui-egui/src/dialogs/expand.rs +++ b/crates/ui-egui/src/dialogs/expand.rs @@ -10,7 +10,7 @@ //! `object.expand.info`), `__canGradient` (Expand Gradient To applies) and `__canSteps` (it //! applies and makes objects). What only the art of symbol instances holds needs Object on. -use craft::ui::contract::SaveKey; +use craft::ui::contract::{Bind, SaveKey}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::memory::Lifetime; use serde_json::{Value, json}; @@ -152,7 +152,7 @@ fn dialog(app: &VectorcraftApp, info: ExpandInfo) -> Result egui::Context { app.ui_ctx.clone().expect("the test context") } diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index 7894461e9a..949382c23e 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -112,7 +112,7 @@ pub fn open(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) { fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Result<(), String> { let ctx = app.ui_ctx.clone().ok_or("no window")?; let source = app.session.active(); - let document = source.map(|source| source.uid); + let document = source.map(|source| (source.uid, source.reverts)); let n = source.map_or(0, |source| source.doc.artboards.len()); let missing = format.and_then(|f| UNAVAILABLE.iter().find(|u| u.0.eq_ignore_ascii_case(f.trim_start_matches('.')))); let format = match missing { @@ -138,17 +138,19 @@ fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Res export_host::open(app, Export::As { document }, false, dialog).map(|_| ()).ok_or_else(|| "no window".into()) } -fn require_source(app: &VectorcraftApp, document: Option) -> Result<(), String> { - let document = document.ok_or_else(|| tl!("Open Export As from the drawing you want to export").to_owned())?; - if app.session.active().is_none_or(|source| source.uid != document) { - return Err(tl!("Return to the original drawing to export it").into()); +fn require_source(app: &VectorcraftApp, document: Option<(u64, u64)>) -> Result<(), String> { + let (uid, reverts) = document.ok_or_else(|| tl!("Open Export As from the drawing you want to export").to_owned())?; + let source = + app.session.active().filter(|source| source.uid == uid).ok_or_else(|| tl!("Return to the original drawing to export it").to_owned())?; + if source.reverts != reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); } Ok(()) } /// Check the artboard range and that there is something to export; the save panel and the format's options or /// the file follow once the dialog has closed. -pub(super) fn confirm(app: &mut VectorcraftApp, document: Option, fields: &DialogFields) -> Result { +pub(super) fn confirm(app: &mut VectorcraftApp, document: Option<(u64, u64)>, fields: &DialogFields) -> Result { require_source(app, document)?; if let Some((_, hint)) = unavailable(fields) { return Err(hint.into()); @@ -175,7 +177,10 @@ pub(super) fn confirm(app: &mut VectorcraftApp, document: Option, fields: & let pages = Pages { use_artboards, all, range, selection: false }; Ok(Some(Box::new(move |app| { require_source(app, document)?; - io::export_path(app, None, f, move |app, path| options_or_write(app, f, plugin, path, pages)) + io::export_path(app, None, f, move |app, path| { + require_source(app, document)?; + options_or_write(app, f, plugin, path, pages) + }) }))) } diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 3011330cf5..bef9fda0f9 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -507,7 +507,7 @@ pub(super) fn artboard_thumb(app: &mut VectorcraftApp, ctx: &Context, i: usize) /// thumbnails. fn document_view(app: &mut VectorcraftApp, ctx: &Context) -> (Option, Vec>) { let Some(st) = app.session.active() else { return (None, Vec::new()) }; - let shown = Shown { key: (st.uid, st.revision), doc: Arc::clone(&st.doc) }; + let shown = Shown { key: (st.uid, st.revision), reverts: st.reverts, doc: Arc::clone(&st.doc) }; let thumbs = (0..shown.doc.artboards.len()).map(|i| artboard_thumb(app, ctx, i)).collect(); (Some(shown), thumbs) } @@ -516,6 +516,8 @@ fn document_view(app: &mut VectorcraftApp, ctx: &Context) -> (Option, Vec struct Shown { /// The document's uid and revision. key: (u64, u64), + /// Which contents of this tab were shown; File Revert preserves its uid. + reverts: u64, doc: Arc, } @@ -536,9 +538,9 @@ pub(crate) struct ExportForScreensDialog { /// What the format presets menu asked for, for the pump to run. pending: Option, /// The document an artboard rename began in, while it runs. - renaming_in: Option, - /// A committed artboard name: (document uid, artboard id, name), for the pump to run. - rename: Option<(u64, u32, String)>, + renaming_in: Option<(u64, u64)>, + /// A committed artboard name: ((document uid, reverts), artboard id, name), for the pump to run. + rename: Option<((u64, u64), u32, String)>, held: HeldAnswer>, } @@ -621,13 +623,13 @@ impl ExportForScreensDialog { } } if picks.rename_began { - self.renaming_in = Some(shown.key.0); + self.renaming_in = Some((shown.key.0, shown.reverts)); } // The name goes to the document the rename began in. if let Some((key, name)) = picks.renamed && let Ok(board) = u32::try_from(key) { - self.rename = Some((self.renaming_in.take().unwrap_or(shown.key.0), board, name)); + self.rename = Some((self.renaming_in.take().unwrap_or((shown.key.0, shown.reverts)), board, name)); } if on != boards(doc.artboards.len(), fields) { set_select(fields, if on.iter().all(|b| *b) { "all" } else { "range" }); @@ -999,15 +1001,16 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { // The export ran when OK was filed: the closed dialog's answer is not read. let _ = dialogs.with(|host| host.take_by_id::(id)); let key = app.session.active().map(|st| (st.uid, st.revision)); + let contents = app.session.active().map(|st| (st.uid, st.reverts)); let pdf_presets = pdf::presets(&app.session); let saved = &app.session.prefs.screen_export_presets; - let Some((shown, pending, rename, filed)) = dialogs.with(|host| { + let Some((shown, shown_contents, pending, rename, filed)) = dialogs.with(|host| { let d = host.get_mut_by_id::(id)?; screen_formats::preset_list(&mut d.presets, saved); if d.pdf_presets != pdf_presets { d.pdf_presets = pdf_presets; } - Some((d.doc.as_ref().map(|s| s.key), d.pending.take(), d.rename.take(), d.held.take())) + Some((d.doc.as_ref().map(|s| s.key), d.doc.as_ref().map(|s| (s.key.0, s.reverts)), d.pending.take(), d.rename.take(), d.held.take())) }) else { return; }; @@ -1029,15 +1032,15 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { } }); } - // A name typed in another document than the active one is dropped. - if let Some((uid, board, name)) = rename - && key.is_some_and(|(active, _)| active == uid) + // A name typed in another drawing or in content discarded by File Revert is dropped. + if let Some((origin, board, name)) = rename + && contents == Some(origin) { rename_artboard(app, board, &name); } if let Some(fields) = filed { - // OK validated its selection against the document the dialog showed before refreshing. - let answer = if shown.map(|(uid, _)| uid) == app.session.active().map(|st| st.uid) { + // OK validated its selection against the loaded contents shown before refreshing. + let answer = if shown_contents == contents { params(app, &fields).and_then(|p| io::export_for_screens(app, p)).map(drop).map_err(Label::from) } else { Err(Label::from(tl!("The active document changed. Review the export selection and try again."))) diff --git a/crates/ui-egui/src/dialogs/export_host.rs b/crates/ui-egui/src/dialogs/export_host.rs index fb68f64c51..79eb47b546 100644 --- a/crates/ui-egui/src/dialogs/export_host.rs +++ b/crates/ui-egui/src/dialogs/export_host.rs @@ -22,8 +22,8 @@ pub(crate) type After = Option Result, + /// The drawing and content generation whose export the dialog configures, when one was open. + document: Option<(u64, u64)>, }, /// The options of the raster format `format`. Raster { @@ -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. @@ -64,6 +64,8 @@ pub(crate) enum Export { pub(crate) struct Open { /// The hosted dialog's id. pub id: DialogId, + /// The drawing and loaded contents whose options and output this dialog controls. + document: Option<(u64, u64)>, /// Which dialog it is. pub kind: Export, /// Whether Export Selection opened it: OK then writes the selection alone. @@ -88,6 +90,22 @@ impl ExportDialogs { } } +impl Open { + fn check_source(&self, app: &VectorcraftApp) -> Result<(), String> { + if matches!(self.kind, Export::As { .. } | Export::Hpgl { .. }) { + return Ok(()); + } + let active = app.session.active().map(|doc| (doc.uid, doc.reverts)); + if active == self.document { + return Ok(()); + } + if active.zip(self.document).is_some_and(|((uid, _), (source, _))| uid == source) { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } + Err(tl!("Return to the original drawing to continue").into()) + } +} + /// `ids` paired with `labels` as the options of a choice row. pub(super) fn options>(ids: &[&'static str], labels: &[&'static str]) -> Vec<(String, L)> { ids.iter().zip(labels).map(|(id, label)| (id.to_string(), L::from(label))).collect() @@ -96,13 +114,18 @@ pub(super) fn options>(ids: &[&'static str], labels: &[&'s /// Opens `dialog` as the export dialog `kind` and records it; `None` without a window. A dialog of the same key /// replaces the one open, and its record. pub(crate) fn open(app: &mut VectorcraftApp, kind: Export, selection: bool, dialog: HostedParamDialog) -> Option { + let document = match &kind { + Export::As { .. } | Export::Hpgl { .. } => None, + Export::EpsCustom { parent } => app.export_dialogs.find(*parent)?.document, + _ => app.session.active().map(|doc| (doc.uid, doc.reverts)), + }; let options = match &kind { Export::EpsCustom { parent } => HeldOptions { parent: Some(*parent), cancel: None }, _ => HeldOptions::default(), }; let id = host::open_held_with(app, dialog, answer, options)?; app.export_dialogs.0.retain(|o| o.id != id); - app.export_dialogs.0.push(Open { id, kind, selection, after: None }); + app.export_dialogs.0.push(Open { id, document, kind, selection, after: None }); Some(id) } @@ -117,9 +140,10 @@ pub(super) fn set_fields(app: &VectorcraftApp, id: DialogId, fields: &[(&str, Va /// OK of the dialog `result` is from: its kind's `confirm`, and the step that follows kept for [`pump`]. fn answer(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> { - let (id, kind, selection) = - app.export_dialogs.find(result.id).map(|o| (o.id, o.kind.clone(), o.selection)).ok_or("this export dialog is no longer open")?; - let open = Open { id, kind, selection, after: None }; + let open = app.export_dialogs.find(result.id).ok_or("this export dialog is no longer open")?; + open.check_source(app)?; + let id = open.id; + let open = Open { id, document: open.document, kind: open.kind.clone(), selection: open.selection, after: None }; let after = confirm(app, &open, &result.fields)?; if let Some(record) = app.export_dialogs.0.iter_mut().find(|o| o.id == id) { record.after = after; @@ -137,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), } } @@ -197,14 +221,20 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some((footer, actions)) = taken else { // The dialog closed: the step after an OK runs, a cancelled one has none. if let Some(i) = app.export_dialogs.0.iter().position(|o| o.id == id) { - let record = app.export_dialogs.0.remove(i); - if let Some(after) = record.after { - let result = after(app); + let mut record = app.export_dialogs.0.remove(i); + if let Some(after) = record.after.take() { + let result = record.check_source(app).and_then(|()| after(app)); report(app, result); } } continue; }; + if let Err(error) = open.check_source(app) { + if footer.is_some() || !actions.is_empty() { + app.status(error); + } + continue; + } if let Export::Svg { mode } = kind { if footer.as_deref() == Some(svg_options::BROWSER_ACTION) && let Some(fields) = fields_of(app, id) 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/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs index 61bba50596..78a24f8868 100644 --- a/crates/ui-egui/src/dialogs/find_replace.rs +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -14,10 +14,9 @@ //! closed, and opens the dialog when there has been none. //! //! The walk lives in `UiState::last_find`: the Find text and the switches of the last request, its -//! `replace` text and `backwards`, the place it reached in `from` (`{id, start, end}`), the `uid` of -//! that document in `doc` and the match found in `found` (`{index, count}`). A place in a document -//! other than the active one, or reached with other Find text or switches, is not used: the search -//! starts again. [`pump`] runs the dialog's requests once per frame. +//! `replace` text and `backwards`, the place it reached in `from` (`{id, start, end}`), the drawing's +//! UID and Revert counter in `doc`, and the match in `found` (`{index, count}`). Changing the +//! loaded drawing, Find text, or switches restarts the search. [`pump`] runs the requests each frame. use craft::text::find::FindOptions; use craft::text::ui::find::{FindCheck, FindReplaceDialog, FindRequest, FindTab, ReplaceButtons}; @@ -56,9 +55,18 @@ pub fn menu_params() -> Value { json!({"find": null}) } -/// The `uid` of the active document. -fn active_uid(app: &VectorcraftApp) -> Option { - app.session.active().map(|d| d.uid) +/// The active drawing and its loaded generation. +fn active_drawing(app: &VectorcraftApp) -> Option<(u64, u64)> { + app.session.active().map(|d| (d.uid, d.reverts)) +} + +fn saved_drawing(last: &Map) -> Option<(u64, u64)> { + let [uid, reverts] = last.get("doc")?.as_array()?.as_slice() else { return None }; + Some((uid.as_u64()?, reverts.as_u64()?)) +} + +fn same_drawing(last: &Map, drawing: (u64, u64)) -> bool { + saved_drawing(last) == Some(drawing) } /// The match found belongs to an open dialog: the last search keeps its place, not the match. @@ -127,13 +135,20 @@ pub fn find_next(app: &mut VectorcraftApp) -> Result { return open(app, &Map::new()); }; forget_found(app); - let uid = active_uid(app); + let drawing = active_drawing(app); if let Some(o) = last.as_object_mut() { + let saved = saved_drawing(o); o.remove("replace"); o.remove("found"); - // A place in another document is no place in this one. - if uid.is_none() || o.remove("doc").and_then(|d| d.as_u64()) != uid { - o.remove("from"); + o.remove("doc"); + if saved != drawing || drawing.is_none() { + let restored = saved.zip(drawing).is_some_and(|((old_uid, _), (uid, _))| old_uid == uid); + if restored { + // An explicit start ignores the whole text frame currently selected. + o.insert("from".into(), Value::Null); + } else { + o.remove("from"); + } } } let r = app.run(NEXT, last)?; @@ -143,7 +158,7 @@ pub fn find_next(app: &mut VectorcraftApp) -> Result { } if let Some(l) = app.ui.last_find.as_mut() { l["from"] = json!({ "id": r["id"], "start": r["start"], "end": r["end"] }); - l["doc"] = json!(uid); + l["doc"] = json!(drawing); } Ok(r) } @@ -178,9 +193,9 @@ fn form(d: &FindReplaceDialog) -> Form { /// The place the last search reached, `{id, start, end}`, while its document is the active one and /// the Find text and the switches are `query`, those it was reached with. fn place<'a>(app: &VectorcraftApp, last: &'a Value, query: &Value) -> Option<&'a Value> { - let uid = active_uid(app)?; + let drawing = active_drawing(app)?; let last = last.as_object()?; - let same = last.get("doc").and_then(Value::as_u64) == Some(uid) && query_in(last) == *query; + let same = same_drawing(last, drawing) && query_in(last) == *query; same.then(|| last.get("from")).flatten().filter(|at| at.is_object()) } @@ -204,7 +219,7 @@ fn remember(app: &mut VectorcraftApp, form: &Form, at: Option, found: Opt last["backwards"] = json!(form.backwards); if let Some(at) = at { last["from"] = at; - last["doc"] = json!(active_uid(app)); + last["doc"] = json!(active_drawing(app)); } if let Some(found) = found { last["found"] = found; diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index d773e5a99b..e90efe3f8a 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -97,6 +97,48 @@ fn selected(p: &Panel) -> Vec { p.app().session.active().unwrap().selection.objects.iter().map(|id| id.0).collect() } +#[test] +fn a_cached_match_cannot_replace_text_restored_by_revert() { + let (mut app, ids) = app_with(&["Needle Needle"]); + let id = ids[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 dir = vectorcraft_testkit::TempDir::new("find-replace-reverted-match"); + app.run("file.saveAs", json!({"path": dir.join("text.vectorcraft")})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 10, "height": 10})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let st = app.session.active().unwrap(); + let version = (st.uid, st.reverts); + let mut p = Panel::new(app, draw); + choose(&p); + set(&p, "find", json!("Needle")); + set(&p, "replace", json!("Changed")); + p.click("Find Next"); + assert_eq!(matched(&p), Some((id, 0, 6))); + + p.app().run("file.revert", json!({"confirmed": true})).unwrap(); + { + let app = p.app(); + let st = app.session.active().unwrap(); + assert_eq!(st.uid, version.0); + assert_ne!(st.reverts, version.1); + } + let before = undo_steps(&p); + let form = with_dialog(&p, |d| super::form(d)); + // A Replace action dispatched before the dialog has refreshed must still check the match. + super::replace(&mut p.app(), &form, false).unwrap(); + assert_eq!(plain(&p, id), "Needle Needle"); + assert_eq!(undo_steps(&p), before); + pump(&p); + assert_eq!(matched(&p), None); + assert!(message(&p).is_empty()); + + p.click("Find Next"); + assert_eq!(matched(&p), Some((id, 0, 6))); + p.click("Replace"); + assert_eq!(plain(&p, id), "Changed Needle"); +} + /// The Edit menu's rows for Find and Replace, Check Spelling (in its Spelling submenu) and Edit Custom Dictionary /// are enabled, and invoking each puts that dialog on the host. #[test] @@ -374,3 +416,30 @@ fn a_search_place_stays_in_its_document_and_given_params_win() { choose(&p); assert_eq!((field(&p, "find"), field(&p, "matchCase")), (json!("cat"), json!(true))); } + +#[test] +fn edit_find_next_starts_at_the_first_restored_match_with_that_frame_selected() { + let (mut app, ids) = app_with(&["cat in the back", "cat cat in front"]); + let first = ids[1]; + 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("menu-find-next-revert"); + app.run("file.saveAs", json!({"path": dir.join("text.vectorcraft")})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 10, "height": 10})).unwrap(); + let mut p = Panel::new(app, draw); + choose(&p); + set(&p, "find", json!("cat")); + p.click("Find Next"); + assert_eq!(matched(&p), Some((first, 0, 3))); + p.click("Find Next"); + assert_eq!(matched(&p), Some((first, 4, 7))); + p.click("Close"); + + p.app().run("file.revert", json!({"confirmed": true})).unwrap(); + p.app().run("select.set", json!({"ids": [first]})).unwrap(); + let before = undo_steps(&p); + choose_find_next(&p); + assert_eq!(from(&p), json!({"id": first, "start": 0, "end": 3})); + assert_eq!(selected(&p), vec![first]); + assert_eq!(undo_steps(&p), before); +} 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 3ba900ff01..8a0f587513 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -13,24 +13,32 @@ //! Fields: `tab` (`color` or `swatches`). Agents can set `color` (hex), `opacity` and `location` (a //! point: `spread`) as percentages, and confirm; confirming reports no stop index. +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}; use serde_json::{Value, json}; use vectorcraft_color::gradient::move_stop; -use vectorcraft_color::{Color, FreeformPoint, GradientStop, Paint}; +use vectorcraft_color::{Color, FreeformPoint, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::GradientEditPaints; use vectorcraft_geom::{Point, Rect}; use vectorcraft_tools::params::color_json; @@ -54,28 +62,181 @@ pub(crate) enum Anchor { /// What the popover edits: the selected stop of the gradient behind the active proxy (with all /// its stops), or the selected point of a freeform gradient. enum Target { - Stop(Vec, usize), - Point(FreeformPoint, usize), + Stop(Box, usize), + Point(Box, FreeformPoint, usize), +} + +/// The paint target and selected stop or point shown when the popover opened. +#[derive(Clone, PartialEq, Eq)] +struct TargetKey { + document: u64, + objects: Vec, + item: Option, + fill: bool, + tool_paint: bool, + point: bool, + index: usize, +} + +impl TargetKey { + fn of(app: &VectorcraftApp, target: &Target) -> Option { + let doc = app.session.active()?; + let fill = app.session.fill_active; + let (point, index) = match target { + Target::Stop(_, index) => (false, *index), + Target::Point(_, _, index) => (true, *index), + }; + Some(Self { + document: doc.uid, + objects: doc.selection.objects.clone(), + item: app.session.appearance_item(), + fill, + tool_paint: app.session.tool_paints(!fill), + point, + index, + }) + } + + fn matches(&self, app: &VectorcraftApp, target: &Target) -> bool { + Self::of(app, target).as_ref() == Some(self) + } +} + +/// 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 { + shown: GradientPaint, + edited: GradientEditPaints, +} + +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.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); + } + } } impl Target { + fn paint(&self) -> &GradientPaint { + match self { + Self::Stop(paint, _) | Self::Point(paint, _, _) => paint, + } + } + fn color(&self) -> Color { match self { - Target::Stop(stops, i) => stops.get(*i).map_or(Color::BLACK, |s| s.color), - Target::Point(p, _) => p.color, + Target::Stop(paint, i) => paint.gradient.stops[*i].color, + Target::Point(_, p, _) => p.color, } } fn opacity(&self) -> f32 { match self { - Target::Stop(stops, i) => stops.get(*i).map_or(1.0, |s| s.opacity), - Target::Point(p, _) => p.opacity, + Target::Stop(paint, i) => paint.gradient.stops[*i].opacity, + Target::Point(_, p, _) => p.opacity, } } /// The location of a stop or the spread of a point, 0 to 1. fn amount(&self) -> f32 { match self { - Target::Stop(stops, i) => stops.get(*i).map_or(0.0, |s| s.offset), - Target::Point(p, _) => p.spread, + Target::Stop(paint, i) => paint.gradient.stops[*i].offset, + Target::Point(_, p, _) => p.spread, } } } @@ -85,10 +246,11 @@ fn selected(app: &VectorcraftApp) -> Option { if edits_points(app, &g) { let f = shown_points(&g); let i = app.session.selected_freeform_point().filter(|i| *i < f.points.len())?; - return Some(Target::Point(f.points[i], i)); + let point = f.points[i]; + return Some(Target::Point(g, point, i)); } let i = app.session.selected_stop().filter(|i| *i < g.gradient.stops.len())?; - Some(Target::Stop(g.gradient.stops, i)) + Some(Target::Stop(g, i)) } /// `stops` with stop `i` given `color`, linked to `link` (a global swatch and tint) or unlinked. @@ -127,13 +289,18 @@ impl Tab { /// The fields set from outside the popover or edited in it, as percentages where the field is one; each `None` is /// a field left alone. #[derive(Clone, Debug, Default, PartialEq)] -pub(crate) struct PopoverFields { +struct PopoverFields { color: Option, opacity: Option, location: Option, spread: Option, } +pub(crate) struct PopoverAnswer { + target: TargetOwner, + fields: PopoverFields, +} + /// The target's values and what the Color panel shows, as `pump` last pushed them. #[derive(Clone)] struct Feed { @@ -159,10 +326,15 @@ 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. pub(crate) struct GradientStopPopover { + target: TargetOwner, /// Where it opened. pub(crate) anchor: Anchor, /// The view it shows. @@ -174,11 +346,15 @@ 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 { - fn new(anchor: Anchor) -> Self { + fn new(anchor: Anchor, target: TargetOwner) -> Self { Self { + target, anchor, tab: Tab::default(), at: Pos2::ZERO, @@ -186,6 +362,7 @@ impl GradientStopPopover { feed: None, set: PopoverFields::default(), filed: Filed::default(), + own_mode: None, } } @@ -199,21 +376,24 @@ fn rejects(field: &str, value: &Value) -> String { } impl StackDialog for GradientStopPopover { - type Result = PopoverFields; + type Result = PopoverAnswer; fn id(&self) -> DialogId { dialog_id(KIND) } - fn show(&mut self, ui: &mut Ui, _stack: &DialogStack) -> Option> { - let Self { feed: Some(feed), tab, panel, filed, at, set, .. } = self else { return None }; + fn show(&mut self, ui: &mut Ui, _stack: &DialogStack) -> Option> { + let Self { feed: Some(feed), tab, panel, filed, at, .. } = self else { return None }; let mut open = true; let shown = Popover::new("Gradient stop", Bind::bound(&mut open)) .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) => Some(DialogResult::Ok(set.clone())), + Some(CloseReason::Enter) => self.confirm(ui.ctx()).map(DialogResult::Ok), Some(_) => Some(DialogResult::Cancel), None => None, } @@ -255,14 +435,15 @@ impl StackDialog for GradientStopPopover { } /// OK (agents): the fields that were set, which `pump` applies; an untouched popover confirms to no change. - fn confirm(&mut self, _ctx: &egui::Context) -> Option { - Some(self.set.clone()) + fn confirm(&mut self, _ctx: &egui::Context) -> Option { + Some(PopoverAnswer { target: self.target.clone(), fields: self.set.clone() }) } } /// 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 = [ @@ -275,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), } @@ -294,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. @@ -380,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; } }); } @@ -397,8 +614,13 @@ pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) { app.run("gradient.selectStop", json!({ "index": index })).ok(); } let Some(target) = selected(app) else { return }; + 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)); + host.open(GradientStopPopover::new(anchor, TargetOwner::new(key, paints, step, restores))); }); refresh(app, &ctx, dialog_id(KIND), &target); } @@ -409,9 +631,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let id = dialog_id(KIND); match dialogs.with(|host| host.take_by_id::(id)) { - Some(DialogResult::Ok(fields)) => { + Some(DialogResult::Ok(PopoverAnswer { target: owner, fields })) => { if fields != PopoverFields::default() && let Some(target) = selected(app) + && owner.matches(app, &target) { apply(app, &target, &fields); } @@ -420,18 +643,51 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { Some(_) => return, None => {} } - if !dialogs.with(|host| host.is_open::()) { + 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) else { - // The stop or point went away (undo, another object selected): nothing left to edit. + }; + 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); } + if filed.fields.location.is_some() + && !owner.key.point + && let Some(index) = app.session.selected_stop() + { + // The stop can cross its neighbor when its location changes. + owner.key.index = index; + } if let Some((name, color)) = filed.swatch && let Some(target) = selected(app) { @@ -441,25 +697,44 @@ 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); return; } - if let Some(target) = selected(app) { - refresh(app, ctx, id, &target); + let updated = selected(app).filter(|target| owner.key.matches(app, target)).zip(app.session.gradient_edit_paints(!owner.key.fill).ok()); + let Some((target, edited)) = updated else { + dialogs.with(|host| host.cancel_by_id(ctx, id)); + return; + }; + // 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 { + 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) { + popover.target = owner; + } + }); + refresh(app, ctx, id, &target); } /// Gives the target the swatch `name`'s colour. A global or spot color (or a tint of one) stays linked, and the /// swatch's color keeps its model. fn pick_swatch(app: &mut VectorcraftApp, target: &Target, name: &str, color: Color) { match target { - Target::Stop(stops, i) => { + Target::Stop(paint, i) => { let link = crate::panels::gradient::dropped_link(app, &json!({ "swatch": name })); - set_stops_keeping_models(app, &recolor(stops.clone(), *i, color, link), Some(*i), Live::Released); + set_stops_keeping_models(app, &recolor(paint.gradient.stops.clone(), *i, color, link), Some(*i), Live::Released); + } + Target::Point(_, _, i) => { + edit_point(app, "paint.freeform.setPoint", json!({ "index": i, "color": color_json(&color), "keepModel": true })); } - Target::Point(_, i) => edit_point(app, "paint.freeform.setPoint", json!({ "index": i, "color": color_json(&color), "keepModel": true })), } } @@ -467,8 +742,8 @@ fn pick_swatch(app: &mut VectorcraftApp, target: &Target, name: &str, color: Col fn apply(app: &mut VectorcraftApp, target: &Target, f: &PopoverFields) { let pct = |v: Option| v.map(|v| (v / 100.0).clamp(0.0, 1.0)); match target { - Target::Stop(stops, i) => { - let (mut stops, mut i) = (stops.clone(), *i); + Target::Stop(paint, i) => { + let (mut stops, mut i) = (paint.gradient.stops.clone(), *i); if let Some(c) = f.color { stops = recolor(stops, i, c, None); } @@ -482,7 +757,7 @@ fn apply(app: &mut VectorcraftApp, target: &Target, f: &PopoverFields) { } set_stops(app, &stops, Some(i), Live::Released); } - Target::Point(_, i) => { + Target::Point(_, _, i) => { let mut p = json!({ "index": i }); if let Some(c) = f.color { p["color"] = color_json(&c); @@ -499,6 +774,8 @@ fn apply(app: &mut VectorcraftApp, target: &Target, f: &PopoverFields) { #[cfg(test)] mod tests { + use craft::behavior::{EditEvent, GestureId, Mixed}; + use craft::color_ui::ui::{PanelTarget, PickedColor}; use vectorcraft_engine::Session; use super::*; @@ -565,7 +842,7 @@ mod tests { fn stops(app: &VectorcraftApp) -> Vec { match selected(app) { - Some(Target::Stop(stops, _)) => stops, + Some(Target::Stop(paint, _)) => paint.gradient.stops, _ => panic!("no stop selected"), } } @@ -591,13 +868,290 @@ mod tests { assert!(set(&app, "color", json!("red")).is_err()); } + #[test] + fn the_popover_discards_a_pending_edit_after_selecting_other_art() { + let mut app = app(); + let first = app.session.doc().unwrap().selection.objects[0]; + let gradient = json!({"stops": [{"offset": 0, "color": "#000000"}, {"offset": 0.5, "color": "#0000ff"}, {"offset": 1, "color": "#ffffff"}]}); + let second = app.run("shape.rectangle", json!({"x": 230, "y": 80, "width": 50, "height": 90})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"gradient": gradient})).unwrap(); + app.run("select.set", json!({"ids": [first.0]})).unwrap(); + open_popover(&mut app); + set(&app, "opacity", json!(25)).unwrap(); + app.run("select.set", json!({"ids": [second]})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + confirm(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + assert!(!is_open(&app)); + + open_popover(&mut app); + set(&app, "opacity", json!(25)).unwrap(); + confirm(&mut app); + assert_eq!(stops(&app)[1].opacity, 0.25); + } + + #[test] + fn the_popover_does_not_send_live_edits_to_another_stop() { + let mut app = app(); + open_popover(&mut app); + let dialogs = app.dialogs().unwrap(); + let ctx = ctx(&app); + dialogs.with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.fields.opacity = Some(25.0); + }); + app.run("gradient.selectStop", json!({"index": 2})).unwrap(); + host::pump(&mut app, &ctx); + assert!(!is_open(&app)); + assert_eq!(stops(&app)[2].opacity, 1.0); + } + + fn replace_gradient(app: &mut VectorcraftApp) { + let stops = json!([{"offset": 0, "color": "#000000"}, {"offset": 0.5, "color": "#0000ff"}, {"offset": 1, "color": "#ffffff"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [100, 150], "end": [200, 150]}})).unwrap(); + assert_eq!(app.session.selected_stop(), Some(1)); + } + + #[test] + fn the_popover_discards_confirmed_edits_to_a_replacement_gradient() { + let mut app = app(); + open_popover(&mut app); + set(&app, "opacity", json!(25)).unwrap(); + let ctx = ctx(&app); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog_id(KIND))); + replace_gradient(&mut app); + host::pump(&mut app, &ctx); + assert_eq!(stops(&app)[1].opacity, 1.0, "the finished answer belongs to the original gradient"); + } + + #[test] + fn the_popover_discards_live_edits_to_a_replacement_gradient() { + 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); + }); + replace_gradient(&mut app); + let ctx = ctx(&app); + host::pump(&mut app, &ctx); + assert_eq!(stops(&app)[1].opacity, 1.0, "the live edit belongs to the original gradient"); + 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(); + let first = app.session.active().unwrap().selection.objects[0]; + let second = app.run("shape.rectangle", json!({"x": 230, "y": 80, "width": 50, "height": 90})).unwrap()["id"].clone(); + let initial = json!({"stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#00ff00"}, {"offset": 1, "color": "#000000"}], + "start": [100, 150], "end": [200, 150]}); + app.run("paint.setFill", json!({"id": second, "gradient": initial})).unwrap(); + app.run("select.set", json!({"ids": [first.0, second]})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + assert_eq!(app.session.active().unwrap().selection.objects[0], first); + open_popover(&mut app); + set(&app, "opacity", json!(25)).unwrap(); + let proxy = active_paint(&app); + let selected = app.session.active().unwrap().selection.objects.clone(); + let gradient = json!({"stops": [{"offset": 0, "color": "#000000"}, {"offset": 0.5, "color": "#0000ff"}, {"offset": 1, "color": "#ffffff"}]}); + app.run("paint.setFill", json!({"id": second, "gradient": gradient})).unwrap(); + assert_eq!(app.session.active().unwrap().selection.objects, selected); + assert_eq!(app.session.selected_stop(), Some(1)); + assert_eq!(active_paint(&app), proxy); + let before = app.session.active().unwrap().doc.clone(); + confirm(&mut app); + assert!(app.session.active().unwrap().doc == before, "the edit must not overwrite the secondary replacement"); + } + + #[test] + fn its_live_color_drag_stays_open_and_commits_once() { + let mut app = app(); + open_popover(&mut app); + let undo = app.session.active().unwrap().history.undo.len(); + let ctx = ctx(&app); + let dialogs = app.dialogs().unwrap(); + let gesture = GestureId::new(1); + let pick = |hex| PickedColor::rgb(Srgba::from_hex(hex).unwrap()); + let before = pick("#00ff00"); + for (edit, expected) in + [(EditEvent::update(gesture, pick("#ff0000")), "#ff0000"), (EditEvent::commit(gesture, Mixed::Same(before), pick("#0000ff")), "#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!(is_open(&app)); + assert_eq!(stops(&app)[1].color.to_hex(), expected); + } + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + + #[test] + fn the_popover_keeps_editing_the_stop_after_moving_it() { + let mut app = app(); + open_popover(&mut app); + app.dialogs().unwrap().with(|host| { + host.get_mut_by_id::(dialog_id(KIND)).unwrap().filed.fields.location = Some(100.0); + }); + let ctx = ctx(&app); + host::pump(&mut app, &ctx); + assert!(is_open(&app)); + assert_eq!(app.session.selected_stop(), Some(2)); + set(&app, "opacity", json!(25)).unwrap(); + confirm(&mut app); + assert_eq!(stops(&app)[1].opacity, 1.0); + assert_eq!(stops(&app)[2].opacity, 0.25); + } + #[test] fn on_a_freeform_gradient_it_edits_the_selected_point() { let mut app = app(); app.run("paint.editGradient", json!({"kind": "freeform"})).unwrap(); app.run("paint.freeform.addPoint", json!({"at": [150, 150], "color": "#0000ff"})).unwrap(); let point = |app: &VectorcraftApp| match selected(app) { - Some(Target::Point(p, i)) => (p, i), + Some(Target::Point(_, p, i)) => (p, i), _ => panic!("no point selected"), }; let (p, i) = point(&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/graph_type.rs b/crates/ui-egui/src/dialogs/graph_type.rs index 49e540c4c1..3620442f4a 100644 --- a/crates/ui-egui/src/dialogs/graph_type.rs +++ b/crates/ui-egui/src/dialogs/graph_type.rs @@ -197,6 +197,7 @@ impl GraphTypeValues { #[derive(Clone)] struct GraphSubject { doc: u64, + reverts: u64, graph_id: u64, series: Vec, graph: GraphKind, @@ -385,6 +386,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields.insert(PAGE.into(), json!("options")); let mut s = GraphSubject { doc: st.uid, + reverts: st.reverts, graph_id: subject.id.0, series: subject.series, graph: spec.kind, @@ -433,8 +435,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { /// have ids of their own) or with nothing changed, else `graph.setType` with these parameters. /// `Err` while the dialog can't be applied. fn verdict(app: &VectorcraftApp, v: &GraphTypeValues, s: &GraphSubject) -> Result, &'static str> { - if !on_its_document(app, s) { + let Some(st) = app.session.active().filter(|st| st.uid == s.doc) else { return Ok(None); + }; + if st.reverts != s.reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.")); } if let Some(why) = problem(v, s) { return Err(why); @@ -569,7 +574,7 @@ fn pending(v: &GraphTypeValues, s: &GraphSubject) -> Value { /// Whether the active document is the one the dialog opened on. fn on_its_document(app: &VectorcraftApp, s: &GraphSubject) -> bool { - app.session.active().is_some_and(|st| st.uid == s.doc) + app.session.active().is_some_and(|st| (st.uid, st.reverts) == (s.doc, s.reverts)) } /// What the calculated tick values were calculated for: the options they depend on and the @@ -1591,4 +1596,32 @@ mod tests { assert_eq!(steps(&app), before); assert_eq!(app.session.execute(COMMAND, &json!({"id": second.0})).unwrap()["type"], "column"); } + + #[test] + fn graph_type_refuses_to_change_the_restored_graph() { + let mut app = app_with_graph("column"); + let graph = app.session.active().unwrap().selection.objects[0]; + let dir = vectorcraft_testkit::TempDir::new("graph-type-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(COMMAND, json!({"id": graph.0, "type": "bar"})).unwrap(); + open(&mut app).unwrap(); + set(&app, "type", json!("line")).unwrap(); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [graph.0]})).unwrap(); + let before = steps(&app); + crate::tests::picks::answer_dialog(&mut app, dialog_id(KIND), &[], true); + assert!(matches!(with(&app, |dialog| dialog.held_state()), Some(HeldOk::Refused(_)))); + assert_eq!(query(&mut app)["type"], "column"); + assert_eq!(steps(&app), before); + + let ctx = ctx(&app); + app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, dialog_id(KIND))); + open(&mut app).unwrap(); + set(&app, "type", json!("line")).unwrap(); + assert!(ok(&mut app)); + assert_eq!(query(&mut app)["type"], "line"); + } } 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/halftone.rs b/crates/ui-egui/src/dialogs/halftone.rs index e17bb4214b..d55e543396 100644 --- a/crates/ui-egui/src/dialogs/halftone.rs +++ b/crates/ui-egui/src/dialogs/halftone.rs @@ -25,6 +25,8 @@ pub(crate) const CMD: &str = "object.vectorHalftone"; pub(crate) struct Open { /// The dialog's id on the host. pub id: DialogId, + /// The drawing whose art the dialog previews and changes. + document: u64, /// The temporary dots the dialog shows while it previews. pub preview: LivePreview, } @@ -70,6 +72,7 @@ pub(crate) fn screen_params(live: bool, fields: &DialogFields) -> Vec { /// Opens Object › Vector Halftone, previewing from its first frame. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; + let document = app.session.active().ok_or("no document")?.uid; let defaults = fields(); let rows = screen_params(false, &DialogFields::new()); let initial = fields_of(&rows, defaults.as_object().unwrap_or(&Default::default())); @@ -78,6 +81,10 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { ParamDialog::command(CMD, tl!("Vector Halftone"), rows).previews(true).values(Bind::bound(fields)) }); let ok = |app: &mut VectorcraftApp, result: &ParamResult| { + let open = app.effect_dialogs.halftone.as_ref().ok_or("the dialog is closed")?; + if !open.in_source(app) { + return Err(tl!("Return to the original drawing to apply Vector Halftone").into()); + } let params = Value::Object(json_of(&screen_params(false, &result.fields), &result.fields)); let mut open = app.effect_dialogs.halftone.take().ok_or("the dialog is closed")?; let done = std::mem::take(&mut open.preview).commit(app, CMD, params); @@ -87,18 +94,29 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { done.map(|_| ()) }; let cancel: Box = Box::new(|app| { - if let Some(open) = app.effect_dialogs.halftone.take() { + if let Some(open) = app.effect_dialogs.halftone.take() + && open.in_source(app) + && owns_preview(app) + { open.preview.cancel(app); } }); let id = open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?; - app.effect_dialogs.halftone = Some(Open { id, preview: LivePreview::default() }); + app.effect_dialogs.halftone = Some(Open { id, document, preview: LivePreview::default() }); Ok(Value::Null) } /// Runs or ends the open dialog's preview for this frame. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut open) = app.effect_dialogs.halftone.take() else { return }; + if !open.in_source(app) { + open.preview = LivePreview::default(); + app.effect_dialogs.halftone = Some(open); + return; + } + if !owns_preview(app) { + open.preview = LivePreview::default(); + } let shown = app.dialogs().and_then(|host| { host.with(|h| { h.get_by_id::(open.id).map(|d| { @@ -117,6 +135,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// Whether the open Object → Vector Halftone dialog is showing its temporary dot group. pub(crate) fn previewing(app: &VectorcraftApp) -> bool { let Some(open) = app.effect_dialogs.halftone.as_ref() else { return false }; - app.dialogs().is_some_and(|host| host.with(|h| h.get_by_id::(open.id).is_some_and(HostedParamDialog::is_previewing))) - && app.session.active().and_then(|st| st.interaction.as_ref()?.preview.as_ref()).is_some_and(|(cmd, _)| cmd == CMD) + open.in_source(app) + && owns_preview(app) + && app.dialogs().is_some_and(|host| host.with(|h| h.get_by_id::(open.id).is_some_and(HostedParamDialog::is_previewing))) +} + +impl Open { + fn in_source(&self, app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|doc| doc.uid == self.document) + } +} + +fn owns_preview(app: &VectorcraftApp) -> bool { + app.session.active().and_then(|st| st.interaction.as_ref()?.preview.as_ref()).is_some_and(|(cmd, _)| cmd == CMD) } 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 749c1970a9..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}; @@ -43,7 +44,30 @@ fn rows(lengths: LengthUnits) -> Vec { /// Open Hyphenation 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")?; + use crate::panels::character; + + let editing = character::text_editing_kept(app)?; + character::text_style(app).ok_or("select some type first")?; + let source = app.session.active().ok_or("no document open")?; + let document = source.uid; + let mut target = Map::new(); + let mut story_focus = None; + let ids = if let Some((id, start, end)) = editing { + if let Some(story) = character::text_story(app) { + story_focus = Some(id); + story + } else { + target.insert("start".into(), json!(start)); + target.insert("end".into(), json!(end)); + vec![id] + } + } else { + character::selected_stories(app) + }; + if ids.is_empty() || source.selection.symbol_part.is_some() { + return Err("select some type first".into()); + } + target.insert("ids".into(), json!(ids.iter().map(|id| id.0).collect::>())); let mut fields = DialogFields::new(); set_shared(&mut fields, FLAGS[0], crate::panels::paragraph::shared_hyphenate(app)); set_shared(&mut fields, FLAGS[1], crate::panels::paragraph::shared_hyphenation_field(app, |h| h.capitalized)); @@ -55,13 +79,24 @@ 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 p = params(&result.fields, &initial); + let mut p = params(&result.fields, &initial); if p.is_empty() { return Ok(()); } - crate::panels::paragraph::run_on_paragraphs(app, "text.setFormat", Value::Object(p)).map(|_| ()) + if app.session.active().is_none_or(|st| st.uid != document) { + return Err(tl!("This dialog was opened in a different document.").to_owned()); + } + character::text_editing_kept(app)?; + p.extend(target.clone()); + if let Some(id) = story_focus { + let story = app.session.active().ok_or("no document open")?.doc.story_of(id); + p.insert("ids".into(), json!(story.iter().map(|id| id.0).collect::>())); + } + app.run("text.setFormat", Value::Object(p)).map(|_| ()) }) .ok_or("no window")?; Ok(Value::Null) @@ -108,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] @@ -156,4 +332,71 @@ mod tests { assert!(app.run("ui.hyphenation", json!({})).is_err()); assert!(!driver::is_open(&app)); } + + #[test] + fn hyphenation_confirm_keeps_the_opening_selection() { + let (mut app, first) = app(); + let second = app.run("text.create", json!({"x": 10, "y": 150, "text": "Other text"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [first]})).unwrap(); + app.run("ui.hyphenation", json!({})).unwrap(); + driver::set(&mut app, "hyphenate", json!(true)); + app.run("select.set", json!({"ids": [second]})).unwrap(); + driver::ok(&mut app); + assert_eq!((paras(&app, first).0.hyphenate, paras(&app, second).0.hyphenate), (true, false)); + } + + #[test] + fn hyphenation_confirm_keeps_the_opening_caret_paragraph() { + let (mut app, id) = app(); + app.session.select_tool("type", Default::default()).unwrap(); + let caret = |at| json!({"editing": id, "anchor": at, "caret": at}); + app.session.set_tool_option("textSelection", &caret(0)); + app.run("ui.hyphenation", json!({})).unwrap(); + driver::set(&mut app, "hyphenate", json!(true)); + app.session.set_tool_option("textSelection", &caret(5)); + driver::ok(&mut app); + let (first, second) = paras(&app, id); + assert_eq!((first.hyphenate, second.hyphenate), (true, false)); + } + + #[test] + fn hyphenation_confirms_the_caret_paragraph_after_buffered_typing() { + let (mut app, id) = app(); + app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let view = Default::default(); + app.session.select_tool("type", view).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 7, "caret": 7})); + app.session.tool_text("\nThree", view).unwrap(); + let text = &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind; + assert!(matches!(text, NodeKind::Text(t) if t.plain_text() == "One\nTwo")); + + app.run("ui.hyphenation", json!({})).unwrap(); + driver::set(&mut app, "hyphenate", json!(true)); + driver::ok(&mut app); + let NodeKind::Text(t) = &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("not text") }; + assert_eq!(t.plain_text(), "One\nTwo\nThree"); + assert_eq!([t.para_at(0).hyphenate, t.para_at(1).hyphenate, t.para_at(2).hyphenate], [false, false, true]); + } + + #[test] + fn hyphenation_confirm_leaves_the_other_drawing_unchanged() { + let (mut app, id) = app(); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let second = app.run("text.create", json!({"x": 10, "y": 10, "text": "Other drawing"})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(id, second, "local text IDs may match between drawings"); + app.run("select.set", json!({"ids": [second]})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.hyphenation", json!({})).unwrap(); + driver::set(&mut app, "hyphenate", json!(true)); + app.run("document.activate", json!({"index": 1})).unwrap(); + driver::ok(&mut app); + assert!(!paras(&app, second).0.hyphenate); + assert!(driver::is_open(&app)); + assert_eq!(driver::fields(&app).bool("hyphenate"), Some(true)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + driver::ok(&mut app); + assert!(!driver::is_open(&app)); + assert!(paras(&app, id).0.hyphenate); + } } 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/javascript_files.rs b/crates/ui-egui/src/dialogs/javascript_files.rs index c3a3fb0e6b..bbc16218e2 100644 --- a/crates/ui-egui/src/dialogs/javascript_files.rs +++ b/crates/ui-egui/src/dialogs/javascript_files.rs @@ -231,7 +231,11 @@ fn body(ui: &mut Ui, files: &[(String, String)], form: &mut Form) { form.file = crate::io::file_url(&path.to_string_lossy()); } } - let row = PathRow::new(caption("File or URL:"), Bind::bound(&mut form.file)).button(tl!("Choose…")).show(ui); + let mut row = PathRow::new(caption("File or URL:"), Bind::bound(&mut form.file)).button(tl!("Choose…")); + if !cx.env.host().is_some_and(|host| host.files().can_pick()) { + row = row.browse_reason(tl!("To link a script here, enter its URL.")); + } + let row = row.show(ui); if row.browse && form.pick.is_none() && let Some(host) = cx.env.host() @@ -397,19 +401,21 @@ mod tests { } #[test] - fn a_browser_file_pick_does_not_invent_a_local_script_url() { - let files = Arc::new(ScriptedFiles::held()); + fn browser_can_link_a_url_without_offering_a_local_file_picker() { + let files = Arc::new(ScriptedFiles::held().in_browser()); let form = Rc::new(RefCell::new(Form { file: "https://example.test/menu.js".into(), ..Default::default() })); let shown = Rc::clone(&form); let mut fixture = Fixture::new(move |ui| body(ui, &[], &mut shown.borrow_mut())); fixture.host(Arc::new(Host::builder(AppInfo { id: "test", name: "Test", version: "1.0" }).files(files.clone()).build())); fixture.settle(); let choose = fixture.by_label(tl!("Choose…")).expect("the Choose button"); + assert!(fixture.tree().is_disabled_key(choose.node)); fixture.click(&choose); fixture.settle(); - let picked = Picked::Contents(vec![("menu.js".into(), b"// local script".to_vec())]); - assert!(files.answer(picked).is_some(), "Choose… filed a browser pick"); - fixture.idle(3); + assert!(files.requests().is_empty()); assert_eq!(form.borrow().file, "https://example.test/menu.js"); + let add = fixture.by_label(tl!("Add")).expect("the Add button"); + fixture.click(&add); + assert_eq!(form.borrow().pending, Some(Pending::Add)); } } diff --git a/crates/ui-egui/src/dialogs/justification.rs b/crates/ui-egui/src/dialogs/justification.rs index 5b97daaedd..d29451406b 100644 --- a/crates/ui-egui/src/dialogs/justification.rs +++ b/crates/ui-egui/src/dialogs/justification.rs @@ -16,6 +16,7 @@ //! Behaviour reference (public documentation): //! . +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; // PLAN: assumed paths of `UnitKind` and `DialogId` use craft::ui::dialog::DialogId; @@ -37,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. @@ -51,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) } } @@ -92,7 +93,7 @@ fn problem(fields: &DialogFields) -> Option<&'static str> { /// The dialog over its values: three titled groups of Minimum, Desired and Maximum, Auto Leading and /// Single Word Justification. Preview starts off ([`HostedParamDialog::preview_off`]). -fn form(fields: &DialogFields) -> ParamDialog<'_> { +fn form(fields: &mut DialogFields) -> ParamDialog<'_> { let titles = [tl!("Word Spacing"), tl!("Letter Spacing"), tl!("Glyph Scaling")]; let columns = [tl!("Minimum"), tl!("Desired"), tl!("Maximum")]; let mut rows = Vec::new(); @@ -106,8 +107,9 @@ fn form(fields: &DialogFields) -> ParamDialog<'_> { rows.push(Param::number("autoLeading", tl!("Auto Leading:"), 120.0, 1.0, 0).bounds(Some(lo), Some(hi)).unit(UnitKind::Percent)); let options = single_word_choices().into_iter().map(|(id, label)| (id.to_owned(), label.into())).collect(); rows.push(Param::new("singleWord", tl!("Single Word Justification:"), ParamKind::choice(options, Some("fullJustify".to_owned())))); - let dialog = ParamDialog::new(KIND, tl!("Justification"), rows).previews(true); - match problem(fields) { + let reason = problem(fields); + let dialog = ParamDialog::new(KIND, tl!("Justification"), rows).previews(true).values(Bind::bound(fields)); + match reason { Some(why) => dialog.ok_enabled(false).ok_reason(why.into()), None => dialog, } @@ -116,7 +118,8 @@ fn form(fields: &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; @@ -142,12 +145,17 @@ pub fn open(app: &mut VectorcraftApp) -> Result { set_shared(&mut fields, "autoLeading", crate::panels::paragraph::shared_justification_f64(app, |j| j.auto_leading)); set_shared(&mut fields, "singleWord", crate::panels::paragraph::shared_single_word_justify(app).map(single_word_name)); let ctx = app.ui_ctx.clone().ok_or("no window")?; - let dialog = HostedParamDialog::new(&ctx, KIND, fields.clone(), |f| form(f)).preview_off(); + let dialog = HostedParamDialog::new(&ctx, KIND, fields.clone(), form).preview_off(); 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) { @@ -213,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(); @@ -317,6 +325,96 @@ mod tests { assert!(!driver::is_open(&app)); } + #[test] + fn justification_minimum_input_updates_validation_and_paragraphs() { + use egui::accesskit::Role; + use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + for lang in ["en", "de", "fr", "el"] { + for height in [700.0, 500.0] { + let (mut app, id) = app(); + app.session.prefs.interface_language = lang.into(); + let ctx = app.ui_ctx.clone().unwrap(); + ctx.enable_accesskit(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, height)); + let undo = app.session.active().unwrap().history.undo.len(); + 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() }) + }; + let control = |out: egui::FullOutput, role, name: &str| { + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + let by_id: std::collections::HashMap<_, _> = nodes.iter().map(|(id, node)| (*id, node)).collect(); + let dialog = nodes.iter().find(|(_, node)| node.role() == Role::Dialog).expect("Justification modal").0; + let mut pending = vec![dialog]; + let mut matches = Vec::new(); + while let Some(id) = pending.pop() { + let Some(node) = by_id.get(&id) else { continue }; + pending.extend_from_slice(node.children()); + if node.role() == role + && node.label() == Some(name) + && let Some(bounds) = node.bounds() + { + let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32); + let text = node + .children() + .iter() + .filter_map(|id| by_id.get(id)) + .find(|child| child.role() == Role::TextInput) + .and_then(|child| child.bounds()); + let target = text.map_or(at, |text| pos2(((text.x0 + text.x1) * 0.5) as f32, ((text.y0 + text.y1) * 0.5) as f32)); + if screen.contains(target) { + matches.push((at, target, node.is_disabled())); + } + } + } + // Word Spacing is the first Minimum control in the modal. + let (_, target, disabled) = matches + .into_iter() + .min_by(|a, b| a.0.y.total_cmp(&b.0.y)) + .unwrap_or_else(|| panic!("{lang} 800x{height}: missing {role:?} {name:?}")); + (target, disabled) + }; + let click = |draw: &mut dyn FnMut(&mut VectorcraftApp, Vec) -> egui::FullOutput, app: &mut VectorcraftApp, at| { + draw(app, vec![Event::PointerMoved(at)]); + for pressed in [true, false] { + draw(app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + }; + let key = |key, modifiers| Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers }; + + draw(&mut app, vec![]); + app.run("ui.justification", json!({})).unwrap(); + for _ in 0..8 { + draw(&mut app, vec![]); + } + for (typed, value, invalid) in [("120", 120.0, true), ("85", 85.0, false)] { + let (min, _) = control(draw(&mut app, vec![]), Role::SpinButton, crate::i18n::t("Minimum")); + click(&mut draw, &mut app, min); + draw(&mut app, vec![key(Key::A, Modifiers::COMMAND)]); + draw(&mut app, vec![Event::Text(typed.into())]); + draw(&mut app, vec![key(Key::Tab, Modifiers::NONE)]); + draw(&mut app, vec![]); + assert_eq!(driver::fields(&app).number("wordMin"), Some(value)); + let (ok, disabled) = control(draw(&mut app, vec![]), Role::Button, crate::i18n::t("OK")); + assert_eq!(disabled, invalid); + click(&mut draw, &mut app, ok); + for _ in 0..3 { + draw(&mut app, vec![]); + } + assert_eq!(driver::is_open(&app), invalid); + if invalid { + assert_eq!(paras(&app, id).0.justification.word_spacing, [80.0, 100.0, 133.0]); + } + } + assert_eq!(paras(&app, id).0.justification.word_spacing, [85.0, 100.0, 133.0]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + crate::i18n::set_current(crate::i18n::Lang::EN); + } + } + } + /// Preview shows the values on the canvas; Cancel rolls them back. #[test] fn justification_dialog_previews_and_cancel_restores() { @@ -512,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/missing_fonts.rs b/crates/ui-egui/src/dialogs/missing_fonts.rs index 75c72b0cef..96a32785e3 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts.rs @@ -21,7 +21,7 @@ use std::time::Duration; -use craft::host::{Host, PickId, PickKind, PickRequest}; +use craft::host::{PickKind, PickRequest}; use craft::ui::buttons::Button; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, clicked}; @@ -154,6 +154,8 @@ enum Act { Search, /// Stop the running search, and stay open. Stop, + /// Ask for a folder to search: the dialog closes, and comes back searching it. + Pick, } /// How the dialog finished: what to do, and the state to open the dialog again with. @@ -166,22 +168,11 @@ pub(crate) struct Answer { pub(crate) struct MissingFontsDialog { id: DialogId, state: State, - /// The folder pick Find in Folder… filed, until its answer comes. - ticket: Option, } impl MissingFontsDialog { fn new(state: State) -> Self { - MissingFontsDialog { id: dialog_id(KIND), state, ticket: None } - } - - /// Forget the pick the dialog is waiting for. - fn release(&mut self, ctx: &Context) { - if let Some(ticket) = self.ticket.take() - && let Some(host) = Host::try_of_ctx(ctx) - { - host.files().forget(ticket); - } + MissingFontsDialog { id: dialog_id(KIND), state } } } @@ -221,10 +212,6 @@ impl StackDialog for MissingFontsDialog { self.state.set(field, value) } - fn cancelled(&mut self, ctx: &Context) { - self.release(ctx); - } - fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let searching = self.state.searching(); let can_add = self.state.can_add(); @@ -232,23 +219,14 @@ impl StackDialog for MissingFontsDialog { let lines = progress(&Value::Object(self.state.status.clone())); let any_found = self.state.found.iter().any(|f| f["files"].as_array().is_some_and(|files| !files.is_empty())); let mut act = None; - let MissingFontsDialog { state, ticket, .. } = &mut *self; + let MissingFontsDialog { state, .. } = &mut *self; let State { fonts, next, found, chosen, can_pick, search_folder, .. } = state; let shown = FormDialog::new(tl!("Missing Fonts"), Bind::bound(chosen)) .ok_label(tl!("Add Fonts")) .cancel_label(tl!("Close")) .ok_enabled(can_add) .extra_buttons([FooterButton::new(tl!("Find Fonts"), DialogRole::Other)]) - .show(ui, |ui, form, chosen| { - if let Some(pending) = *ticket - && let Some(answer) = form.take_pick_answer(pending) - { - *ticket = None; - if let Some(path) = answer.first_path() { - *search_folder = path.to_string_lossy().into_owned(); - act = Some(Act::Search); - } - } + .show(ui, |ui, _, chosen| { Stack::new().show(ui, |ui, _| { Text::new(tl!("These fonts aren't available. Their text shows in another font.")).shade(Shade::Muted).show(ui); for f in fonts.iter() { @@ -284,11 +262,9 @@ impl StackDialog for MissingFontsDialog { *search_folder = next.clone(); act = Some(Act::Search); } - if *can_pick - && clicked(&Button::new(tl!("Find in Folder…")).id_salt("pick").enabled(!searching).show(ui)) - && let Some(host) = form.env.host().cloned() - { - *ticket = Some(host.files().pick(PickRequest::folder("fonts"))); + // The app asks for the folder, as Type › Find Font's Find in Folder… does. + if *can_pick && clicked(&Button::new(tl!("Find in Folder…")).id_salt("pick").enabled(!searching).show(ui)) { + act = Some(Act::Pick); } if searching && clicked(&Button::new(tl!("Stop")).id_salt("stop").show(ui)) { act = Some(Act::Stop); @@ -315,9 +291,6 @@ impl StackDialog for MissingFontsDialog { act = Some(Act::Find); } let closed = act.is_none() && shown.closed.is_some(); - if act.is_some() || closed { - self.release(ui.ctx()); - } match act { Some(act) => Some(DialogResult::Ok(Answer { act, state: self.state.clone() })), None if closed => Some(DialogResult::Cancel), @@ -399,6 +372,9 @@ fn settle(app: &mut VectorcraftApp, Answer { act, mut state }: Answer) { Act::Find => find_fonts(app, state.uid).map(|()| false), // The folder is searched once: one that doesn't start leaves the dialog without it. Act::Search => start_search(app, &mut state, &search_folder).map(|()| true), + // The app asks for the folder, as Type › Find Font's Find in Folder… does; the dialog comes back + // searching it. A question that is cancelled leaves the dialog closed. + Act::Pick => find_in_folder_for(app, state.uid, None).map(|_| false), Act::Stop => app.run("text.findFontFiles", json!({ "stop": true })).map(|_| { if let Ok(r) = app.session.execute("text.findFontFiles", &json!({})) { let error = follow(&mut state, &r); @@ -497,6 +473,12 @@ fn show_for(app: &mut VectorcraftApp, uid: u64, dialog: MissingFontsDialog) { /// `folder`), then open the dialog for the active document, searching it. pub(crate) fn find_in_folder_command(app: &mut VectorcraftApp, folder: Option) -> Result { let uid = app.session.active().map(|d| d.uid).ok_or("no document open")?; + find_in_folder_for(app, uid, folder) +} + +/// [`find_in_folder_command`] for the document `uid`, which a dialog left open may not be the +/// active one. +fn find_in_folder_for(app: &mut VectorcraftApp, uid: u64, folder: Option) -> Result { // Nothing to look for: no folder is asked for. dialog_for(app, uid).ok_or(NOTHING_MISSING)?; match folder { diff --git a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs index 36dc534870..dad177950a 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs @@ -195,6 +195,59 @@ fn the_documents_fonts_folder_is_offered_and_searched_off_the_ui_thread() { assert!(is_open::(&app), "a failed add keeps the dialog"); } +/// Find in Folder… closes the dialog and asks for the folder as the app does for Type › Find Font's +/// Find in Folder…; the dialog comes back searching the folder picked. +#[test] +fn find_in_folder_asks_for_the_folder_and_the_dialog_comes_back_searching_it() { + let root = folder("pick"); + std::fs::create_dir_all(root.join("somewhere")).unwrap(); + let mut app = app_for(&root); + let picks = crate::tests::picks::scripted(&mut app); + let doc = root.join("doc.vectorcraft"); + save_doc(&mut app, &doc, "No Such Font Family", false); + open(&mut app, &doc); + pump(&mut app); + let ctx = app.ui_ctx.clone().expect("a window context"); + let state = host(&app, |h| h.get::().map(|d| d.state.clone())).expect("the dialog is open"); + answer_cancel(&mut app); + assert!(!is_open::(&app)); + settle(&mut app, Answer { act: Act::Pick, state }); + assert_eq!(picks.requests().last().map(|r| r.kind), Some(PickKind::Folder), "the app asks for a folder"); + assert!(!is_open::(&app), "the dialog waits for the answer"); + picks.answer(&[&root.join("somewhere").to_string_lossy()]); + crate::tests::picks::poll(&mut app, &ctx); + pump(&mut app); + let f = fields(&app).expect("the dialog comes back"); + assert_eq!(f["folder"], json!(root.join("somewhere").to_string_lossy()), "searching the folder picked: {f}"); +} + +/// The dialog of a document that isn't the active one asks for its own folder, and searches for its +/// own fonts. +#[test] +fn find_in_folder_searches_for_the_fonts_of_the_dialogs_document() { + let root = folder("pick-other"); + std::fs::create_dir_all(root.join("somewhere")).unwrap(); + let mut app = app_for(&root); + let picks = crate::tests::picks::scripted(&mut app); + let (a, b) = (root.join("a.vectorcraft"), root.join("b.vectorcraft")); + save_doc(&mut app, &a, "No Such Font Family", false); + save_doc(&mut app, &b, "Source Sans 3", false); + open(&mut app, &a); + pump(&mut app); + let ctx = app.ui_ctx.clone().expect("a window context"); + let state = host(&app, |h| h.get::().map(|d| d.state.clone())).expect("the dialog is open"); + answer_cancel(&mut app); + open(&mut app, &b); + assert!(app.session.active().is_some_and(|d| d.uid != state.uid), "another document is the active one"); + settle(&mut app, Answer { act: Act::Pick, state: state.clone() }); + assert_eq!(picks.requests().last().map(|r| r.kind), Some(PickKind::Folder), "the app asks for a folder"); + picks.answer(&[&root.join("somewhere").to_string_lossy()]); + crate::tests::picks::poll(&mut app, &ctx); + pump(&mut app); + let back = host(&app, |h| h.get::().map(|d| d.state.uid)); + assert_eq!(back, Some(state.uid), "the dialog of the document it was for comes back"); +} + /// Find Fonts opens Type › Find Font on the first missing font, to replace it, and the Missing /// Fonts dialog doesn't come back for that open. #[test] 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/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index a76bdedd7a..8f1338f1e8 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -296,7 +296,8 @@ impl DocumentSettings for VcNewDocument { } }); }); - Row::new().show(ui, |ui, _| { + // Host viewports below the desktop main window's 800-point minimum need this row to wrap. + Row::new().wrap(ui.ctx().content_rect().width() < 800.0).show(ui, |ui, _| { Field::new(height.clone()).show(ui, |ui, _| size_field(ui, &height, &mut s.height, lengths)); Field::new(orientation.clone()).show(ui, |ui, _| { let entries = [ @@ -1109,4 +1110,66 @@ mod tests { assert!(!dir.join("Print.vectorcraft").exists()); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn orientation_remains_clickable_in_compact_web_windows() { + use crate::i18n::LangExt; + use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + for code in ["en", "de", "fr", "el"] { + for width in [800.0, 640.0, 540.0, 799.0, 801.0] { + let services = crate::Services { download: Some(Box::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.session.prefs.interface_language = code.into(); + let lang = crate::i18n::Lang::from_code(code).unwrap(); + crate::i18n::set_current(lang); + open(&mut app); + set(&app, "width", json!(400)).unwrap(); + set(&app, "height", json!(600)).unwrap(); + set(&app, "units", json!("pt")).unwrap(); + let context = ctx(&app); + let size = vec2(width, 500.0); + let screen = Rect::from_min_size(Pos2::ZERO, size); + let mut time = 0.0; + let mut draw = |app: &mut VectorcraftApp, events| { + time += 0.25; + let out = crate::testing::app_frame( + app, + &context, + RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }, + ); + assert_eq!(context.content_rect().size(), size, "the web host keeps the requested viewport"); + out + }; + for _ in 0..6 { + draw(&mut app, vec![]); + } + let original = fields(&app); + let out = draw(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + let bounds = nodes + .iter() + .find(|(_, node)| node.role() == egui::accesskit::Role::RadioButton && node.label() == Some(crate::i18n::tr(lang, "Landscape"))) + .and_then(|(_, node)| node.bounds()) + .expect("Landscape is shown"); + let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32); + draw(&mut app, vec![Event::PointerMoved(at)]); + for pressed in [true, false] { + draw(&mut app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + } + draw(&mut app, vec![]); + let turned = fields(&app); + assert_eq!(turned["width"], original["height"], "{code} {width}: Landscape swaps the page width"); + assert_eq!(turned["height"], original["width"], "{code} {width}: Landscape swaps the page height"); + for _ in 0..3 { + draw(&mut app, vec![]); + } + for idle in 0..3 { + let output = draw(&mut app, vec![]); + assert_eq!(output.platform_output.num_completed_passes, 1, "{code} {width}: idle frame {idle} repeats layout"); + } + } + } + crate::i18n::set_current(crate::i18n::Lang::EN); + } } diff --git a/crates/ui-egui/src/dialogs/new_swatch.rs b/crates/ui-egui/src/dialogs/new_swatch.rs index 6a66190187..4237147a9e 100644 --- a/crates/ui-egui/src/dialogs/new_swatch.rs +++ b/crates/ui-egui/src/dialogs/new_swatch.rs @@ -26,13 +26,17 @@ pub(crate) struct Open { pub(crate) id: DialogId, /// The name the dialog proposes for its colour. auto: String, + /// The drawing that supplied the paint and the possible colour group. + document: u64, } /// Open New Swatch for the active paint, going into color `group`. A color opens as a spot color /// with `spot`, and as a global process color with `global` alone. pub fn open(app: &mut VectorcraftApp, spot: bool, global: bool, group: Option<&str>) -> Result { let paint = crate::panels::active_paint(app); - let name = app.session.active().ok_or("no document open")?.doc.new_swatch_name(&paint); + let source = app.session.active().ok_or("no document open")?; + let document = source.uid; + let name = source.doc.new_swatch_name(&paint); let mut fields = DialogFields::new(); fields.set("name", name.as_str()); let (rows, kept) = match &paint { @@ -48,20 +52,24 @@ pub fn open(app: &mut VectorcraftApp, spot: bool, global: bool, group: Option<&s let dialog = hosted(&ctx, KIND, tl!("New Swatch"), fields, rows, false); let group = group.unwrap_or_default().to_owned(); let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { + if app.session.active().is_none_or(|st| st.uid != document) { + return Err(tl!("Return to the original drawing to create this swatch").into()); + } app.run("swatch.new", params(kept.as_ref(), &group, &answer.fields))?; app.ui.new_swatch = None; Ok(()) }; let options = HeldOptions { parent: None, cancel: Some(Box::new(|app: &mut VectorcraftApp| app.ui.new_swatch = None)) }; let id = open_held_with(app, dialog, ok, options).ok_or(NO_WINDOW)?; - app.ui.new_swatch = Some(Open { id, auto: name }); + app.ui.new_swatch = Some(Open { id, auto: name, document }); Ok(Value::Null) } /// Keeps the default name following the colour while the name has not been edited, and applies the corrections the /// colour row asked for. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { - let Some((id, auto)) = app.ui.new_swatch.as_ref().map(|o| (o.id, o.auto.clone())) else { return }; + let Some(open) = app.ui.new_swatch.as_ref().filter(|o| app.session.active().is_some_and(|st| st.uid == o.document)) else { return }; + let (id, auto) = (open.id, open.auto.clone()); super::swatch_options::correct(app, id); let Some(fields) = with_dialog(app, id, |d| d.fields().clone()) else { return }; if !fields.contains("color") || fields.text("name") != Some(auto.as_str()) { @@ -105,12 +113,93 @@ mod tests { (ctx, app) } + #[test] + fn a_new_swatch_stays_with_its_opening_drawing() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let ctx = app.ui_ctx.clone().unwrap(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 500.0))); + let frame = |app: &mut VectorcraftApp| { + crate::testing::app_frame(app, &ctx, egui::RawInput { screen_rect, ..Default::default() }); + }; + let new_file = |app: &mut VectorcraftApp| { + app.run("file.new", json!({"width":100,"height":100,"colorMode":"rgb"})).unwrap(); + app.session.doc().unwrap().uid + }; + let source = new_file(&mut app); + let other = new_file(&mut app); + assert_ne!(source, other); + app.run("document.activate", json!({"index":0})).unwrap(); + app.run("paint.setFill", json!({"color":"#336699"})).unwrap(); + let undo_source = app.session.doc().unwrap().history.undo.len(); + for _ in 0..4 { + frame(&mut app); + } + app.run("ui.newSwatch", json!({})).unwrap(); + let id = app.ui.new_swatch.as_ref().unwrap().id; + let name = "Opening Drawing Swatch"; + with_dialog(&app, id, |d| d.set_field("name", FieldValue::Text(name.to_owned()))).unwrap(); + for _ in 0..4 { + frame(&mut app); + } + + app.run("document.activate", json!({"index":1})).unwrap(); + let undo_other = app.session.doc().unwrap().history.undo.len(); + assert_eq!(app.session.doc().unwrap().uid, other); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)); + frame(&mut app); + let st = app.session.doc().unwrap(); + assert!(st.doc.swatch(name).is_none(), "OK created the opening drawing's swatch in the other drawing"); + assert_eq!(st.history.undo.len(), undo_other); + assert_eq!(app.ui.new_swatch.as_ref().unwrap().id, id, "the refused draft remains open"); + + app.run("document.activate", json!({"index":0})).unwrap(); + assert_eq!(app.session.doc().unwrap().uid, source); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)); + frame(&mut app); + let st = app.session.doc().unwrap(); + assert_eq!(st.doc.swatch(name).and_then(|s| s.paint.color()).map(|c| c.to_hex()).as_deref(), Some("#336699")); + assert_eq!(st.history.undo.len(), undo_source + 1); + assert!(app.ui.new_swatch.is_none()); + app.run("edit.undo", json!({})).unwrap(); + assert!(app.session.doc().unwrap().doc.swatch(name).is_none()); + } + /// Answers OK in the open dialog and lets the host run it. fn ok(app: &mut VectorcraftApp, ctx: &egui::Context) { app.dialogs().unwrap().with(|h| h.confirm_by_id(ctx, dialog_id(KIND))); crate::dialogs::host::pump(app, ctx); } + #[test] + fn an_untouched_name_uses_the_opening_drawings_swatches() { + use vectorcraft_color::Color; + + let (ctx, mut app) = setup(); + let suggested = |app: &VectorcraftApp, c: Color| app.session.doc().unwrap().doc.new_swatch_name(&Paint::solid(c)); + let color = Color::from_hex("#336699").unwrap(); + let name = suggested(&app, color); + app.run("file.new", json!({"width":100,"height":100})).unwrap(); + app.run("swatch.new", json!({"name":name,"color":"#445566"})).unwrap(); + assert_ne!(suggested(&app, color), name, "the other drawing would choose a different name"); + + app.run("document.activate", json!({"index":0})).unwrap(); + app.run("paint.setFill", json!({"color":"#336699"})).unwrap(); + app.run("ui.newSwatch", json!({})).unwrap(); + let id = app.ui.new_swatch.as_ref().unwrap().id; + let draft_name = |app: &VectorcraftApp| with_dialog(app, id, |d| d.fields().text("name").unwrap().to_owned()).unwrap(); + assert_eq!(draft_name(&app), name); + + app.run("document.activate", json!({"index":1})).unwrap(); + pump(&mut app, &ctx); + assert_eq!(draft_name(&app), name); + + app.run("document.activate", json!({"index":0})).unwrap(); + let color = Color::from_hex("#6789ab").unwrap(); + with_dialog(&app, id, |d| d.set_field("color", FieldValue::Json(json!(color)))).unwrap(); + pump(&mut app, &ctx); + assert_eq!(draft_name(&app), suggested(&app, color)); + } + #[test] fn a_warning_corrects_the_new_colour_only_until_ok() { let (ctx, mut app) = setup(); diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index 2b13671cdd..3ef9024618 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -29,6 +29,7 @@ pub(crate) struct NewTextStyle { opening: Opening, /// Whether the dialog makes a paragraph style. pub(crate) para: bool, + document: u64, target: Value, } @@ -54,7 +55,8 @@ style_dialog!(NewTextStyle, KIND); /// Open New Character Style (`para`: New Paragraph Style) with the name `charStyle.new` would give /// the style, to make it from the text `target` names. pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result { - let doc = &app.session.active().ok_or("no document open")?.doc; + let state = app.session.active().ok_or("no document open")?; + let (document, doc) = (state.uid, &state.doc); let name = vectorcraft_engine::cmd::textstyles::new_style_name(doc, para); let mut target = if target.is_object() { target } else { json!({}) }; let selected_attrs = vectorcraft_engine::cmd::textstyles::target_style_attrs(&app.session, &target, para); @@ -69,7 +71,7 @@ pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result Result().map(|d| (d.para, d.frame()))) else { + let Some((para, document, frame)) = dialogs.with(|host| host.get_mut::().map(|d| (d.para, d.document, d.frame()))) else { // The dialog closed: its answer or cancel has nothing left for the app to do. let _ = dialogs.with(|host| host.take::()); return; @@ -86,12 +88,18 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { if !frame.ok { return; } - let made = frame.params.and_then(|params| app.run(if para { "paraStyle.new" } else { "charStyle.new" }, params)); + let made = if app.session.active().is_some_and(|doc| doc.uid == document) { + frame.params.and_then(|params| app.run(if para { "paraStyle.new" } else { "charStyle.new" }, params)) + } else if app.session.documents().iter().any(|doc| doc.uid == document) { + Err("switch back to the document where this style was opened".into()) + } else { + Err("the document where this style was opened has closed".into()) + }; let answer = match &made { Ok(v) => { - if let Some((uid, name)) = app.session.active().and_then(|doc| v["name"].as_str().map(|name| (doc.uid, name.to_string()))) { - app.ui.text_styles.made.retain(|(pending_uid, pending_para, _)| *pending_uid != uid || *pending_para != para); - app.ui.text_styles.made.push((uid, para, name)); + if let Some(name) = v["name"].as_str() { + app.ui.text_styles.made.retain(|(pending_uid, pending_para, _)| *pending_uid != document || *pending_para != para); + app.ui.text_styles.made.push((document, para, name.to_string())); } Ok(()) } @@ -103,3 +111,53 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { } }); } + +#[cfg(test)] +mod tests { + use craft::ui::dialog::{HeldOk, StackDialog}; + use vectorcraft_engine::Session; + + use super::*; + + fn style_exists(app: &VectorcraftApp, para: bool, name: &str) -> bool { + let doc = &app.session.doc().unwrap().doc; + if para { doc.para_styles.iter().any(|style| style.name == name) } else { doc.char_styles.iter().any(|style| style.name == name) } + } + + fn assert_style_stays_in_its_opening_document(para: bool) { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let opening = app.session.doc().unwrap().uid; + app.run(if para { "ui.newParaStyle" } else { "ui.newCharStyle" }, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + let dialog = host.with(|h| h.get::().unwrap().id()); + let name = "Opening Document Style"; + host.with(|h| h.set_json_field(&ctx, dialog, "name", json!(name))).unwrap(); + + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + assert_ne!(app.session.doc().unwrap().uid, opening); + host.with(|h| h.confirm_by_id(&ctx, dialog)); + pump(&mut app, &ctx); + + assert!(!style_exists(&app, para, name), "OK must leave styles in the other document unchanged"); + assert!(app.ui.text_styles.made.is_empty(), "the other document must not highlight a style"); + assert!(matches!(host.with(|h| h.held_state(dialog)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + host.with(|h| h.confirm_by_id(&ctx, dialog)); + pump(&mut app, &ctx); + assert!(style_exists(&app, para, name), "the original document can accept the same draft"); + assert_eq!(app.ui.text_styles.made, [(opening, para, name.to_string())]); + } + + #[test] + fn new_character_style_confirmation_stays_in_its_document() { + assert_style_stays_in_its_opening_document(false); + } + + #[test] + fn new_paragraph_style_confirmation_stays_in_its_document() { + assert_style_stays_in_its_opening_document(true); + } +} diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index fdff36c966..49f355273a 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -32,7 +32,7 @@ use craft::ui::sections::GroupBox; use craft::ui::text::{NumberField, StepArrows}; use egui::{Context, Ui}; use serde_json::{Value, json}; -use vectorcraft_doc::NodeKind; +use vectorcraft_doc::{NodeId, NodeKind}; use crate::VectorcraftApp; @@ -98,7 +98,8 @@ pub struct Mosaic { pub struct ObjectMosaicDialog { id: DialogId, values: Mosaic, - /// The size (pt) of the image as of the last [`sync`]; the last size read while none is selected. + source: MosaicSource, + /// The last size (pt) read while the opening image was selected. image: (f64, f64), /// Whether an image is selected. selected: bool, @@ -115,12 +116,42 @@ fn label(text: &str) -> Label { text.to_owned().into() } -/// The size (pt) of the first selected image, which the mosaic is made from. -fn image_size(app: &VectorcraftApp) -> Option<(f64, f64)> { +/// The selected raster and the drawing contents it belongs to. +#[derive(Clone, Copy, PartialEq, Eq)] +struct MosaicSource { + document: u64, + reverts: u64, + history_restores: u64, + image: NodeId, +} + +impl MosaicSource { + fn size(self, app: &VectorcraftApp) -> Result<(f64, f64), String> { + let st = app + .session + .active() + .filter(|st| st.uid == self.document) + .ok_or_else(|| tl!("Return to the original drawing to create the mosaic.").to_owned())?; + if st.reverts != self.reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); + } + if st.history_restores != self.history_restores { + return Err(tl!("Reopen Create Object Mosaic after Undo or Redo.").to_owned()); + } + match selected_image(app) { + Some((source, size)) if source == self => Ok(size), + None => Err(NO_IMAGE.to_owned()), + _ => Err(tl!("Select the original image to create the mosaic.").to_owned()), + } + } +} + +/// The first selected image and its size in points, as the mosaic command reads them. +fn selected_image(app: &VectorcraftApp) -> Option<(MosaicSource, (f64, f64))> { let st = app.session.active()?; let node = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).find(|n| matches!(n.kind, NodeKind::Image(_)))?; let b = node.geometric_bounds()?; - Some((b.width(), b.height())) + Some((MosaicSource { document: st.uid, reverts: st.reverts, history_restores: st.history_restores, image: node.id }, (b.width(), b.height()))) } /// Open the dialog on the selected image, with the values `given` holds (the menu item's params, or @@ -128,7 +159,7 @@ fn image_size(app: &VectorcraftApp) -> Option<(f64, f64)> { /// command's defaults for the rest. With no image selected, or with params the command refuses, /// nothing opens and the error says why. pub fn open(app: &mut VectorcraftApp, given: &Value) -> Result { - let Some((w, h)) = image_size(app) else { return Err(NO_IMAGE.into()) }; + let Some((source, (w, h))) = selected_image(app) else { return Err(NO_IMAGE.into()) }; let none = json!({}); let given = if given.is_null() { &none } else { given }; app.session.check_params(COMMAND, given).map_err(|e| e.to_string())?; @@ -161,18 +192,19 @@ pub fn open(app: &mut VectorcraftApp, given: &Value) -> Result { }; let dialogs = app.dialogs().ok_or("no window")?; let lengths = crate::canvas::general_lengths(app); - dialogs.with(|host| host.open(ObjectMosaicDialog::new(values, (w, h), lengths))); + dialogs.with(|host| host.open(ObjectMosaicDialog::new(values, source, (w, h), lengths))); Ok(json!({ "dialog": KIND })) } -/// Pushes the selected image's size and the document's length units into the open dialog. A frame runs +/// Pushes the opening image's current size and length units into the open dialog. A frame runs /// it before the dialogs, and `ui.dialog.*` before each method. pub(crate) fn sync(app: &mut VectorcraftApp) { let Some(dialogs) = app.dialogs() else { return }; - let size = image_size(app); + let selected = selected_image(app); let lengths = crate::canvas::general_lengths(app); dialogs.with(|host| { if let Some(dialog) = host.get_mut::() { + let size = selected.filter(|(source, _)| *source == dialog.source).map(|(_, size)| size); dialog.sync(size, lengths); } }); @@ -181,9 +213,9 @@ pub(crate) fn sync(app: &mut VectorcraftApp) { /// What the dialog asked of the app. enum Work { /// Use Ratio: the counts for these values. - Ratio(Mosaic, (f64, f64)), + Ratio(Mosaic, MosaicSource), /// The held OK: the command for these values. - Run(Mosaic, (f64, f64)), + Run(Mosaic, MosaicSource), } /// Runs what the open dialog asked of the app, outside the host's lock: Use Ratio's counts, and the @@ -195,17 +227,19 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { let _ = host.take::(); let dialog = host.get_mut::()?; if std::mem::take(&mut dialog.use_ratio) { - return Some(Work::Ratio(dialog.values.clone(), dialog.image)); + return Some(Work::Ratio(dialog.values.clone(), dialog.source)); } - dialog.held.take().map(|values| Work::Run(values, dialog.image)) + dialog.held.take().map(|values| Work::Run(values, dialog.source)) }); match work { None => {} - Some(Work::Ratio(mut values, image)) => { - follow_ratio(&mut values, image); - let mut p = params(&values, image); - p["useRatio"] = json!(values.side.key()); - let counts = vectorcraft_engine::cmd::mosaic_counts(&app.session, &p).map_err(|e| e.to_string()); + Some(Work::Ratio(mut values, source)) => { + let counts = source.size(app).and_then(|image| { + follow_ratio(&mut values, image); + let mut p = params(&values, image); + p["useRatio"] = json!(values.side.key()); + vectorcraft_engine::cmd::mosaic_counts(&app.session, &p).map_err(|e| e.to_string()) + }); dialogs.with(|host| { let Some(dialog) = host.get_mut::() else { return }; match counts { @@ -218,13 +252,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { } }); } - Some(Work::Run(mut values, image)) => { - follow_ratio(&mut values, image); - // With no image selected the dialog says what it needs, not that the command is unavailable. - let answer = match image_size(app) { - Some(_) => app.run(COMMAND, params(&values, image)).map(|_| ()).map_err(Label::from), - None => Err(Label::from(NO_IMAGE.to_string())), - }; + Some(Work::Run(mut values, source)) => { + let answer = source + .size(app) + .and_then(|image| { + follow_ratio(&mut values, image); + app.run(COMMAND, params(&values, image)).map(|_| ()) + }) + .map_err(Label::from); dialogs.with(|host| { if let Some(dialog) = host.get_mut::() { dialog.held.answer(answer); @@ -235,16 +270,26 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { } impl ObjectMosaicDialog { - fn new(values: Mosaic, image: (f64, f64), lengths: LengthUnits) -> Self { - ObjectMosaicDialog { id: dialog_id(KIND), values, image, selected: true, lengths, note: None, use_ratio: false, held: HeldAnswer::new() } + fn new(values: Mosaic, source: MosaicSource, image: (f64, f64), lengths: LengthUnits) -> Self { + ObjectMosaicDialog { + id: dialog_id(KIND), + values, + source, + image, + selected: true, + lengths, + note: None, + use_ratio: false, + held: HeldAnswer::new(), + } } /// `size` is the selected image's size, `None` while none is selected: the last size stays and a /// switch to percentages is refused until one is. fn sync(&mut self, size: Option<(f64, f64)>, lengths: LengthUnits) { - self.lengths = lengths; self.selected = size.is_some(); if let Some(size) = size { + self.lengths = lengths; self.image = size; if self.note.as_ref().is_some_and(|n| n.as_str() == NO_IMAGE) { self.note = None; @@ -375,7 +420,7 @@ impl StackDialog for ObjectMosaicDialog { } fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { - let ObjectMosaicDialog { id: _, values, image, selected, lengths, note, use_ratio, held } = self; + let ObjectMosaicDialog { values, image, selected, lengths, note, use_ratio, held, .. } = self; // A refusal shows until a value it refused changes. if held.refusal().is_some_and(|(_, refused)| refused != values) { held.clear_refusal(); @@ -557,11 +602,15 @@ mod tests { /// An app with a 100 × 50 pt embedded image selected. fn app_with_image() -> VectorcraftApp { let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + add_image(&mut app); + app + } + + fn add_image(app: &mut VectorcraftApp) { app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap(); app.run("paint.setStroke", json!({"none": true})).unwrap(); app.run("object.rasterize", json!({"ppi": 72})).unwrap(); - app } /// The mosaic group's size and tile count. @@ -851,4 +900,72 @@ mod tests { ok(&mut app); assert_eq!(mosaic(&app).map(|m| m.2), Some(30)); } + + #[test] + fn held_mosaic_does_not_delete_another_drawings_raster() { + let mut app = app_with_image(); + open(&mut app, &json!({"columns": 2, "rows": 2, "deleteRaster": true})).unwrap(); + add_image(&mut app); + let second = image_id(&app); + let undo = app.session.active().unwrap().history.undo.len(); + ok(&mut app); + assert_eq!(mosaic(&app), None); + assert_eq!(image_id(&app), second); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(is_open(&mut app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + ok(&mut app); + assert_eq!(mosaic(&app), Some((100.0, 50.0, 4))); + assert!(!is_open(&mut app)); + } + + #[test] + fn held_mosaic_does_not_delete_a_raster_restored_by_revert() { + let mut app = app_with_image(); + let source = image_id(&app); + let dir = vectorcraft_testkit::TempDir::new("mosaic-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!({"dx": 10, "dy": 0})).unwrap(); + open(&mut app, &json!({"columns": 2, "rows": 2, "deleteRaster": true})).unwrap(); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": [source]})).unwrap(); + + let undo = app.session.active().unwrap().history.undo.len(); + ok(&mut app); + assert_eq!(mosaic(&app), None); + assert_eq!(image_id(&app), source); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(is_open(&mut app)); + + open(&mut app, &json!({"columns": 2, "rows": 2, "deleteRaster": true})).unwrap(); + ok(&mut app); + assert_eq!(mosaic(&app), Some((100.0, 50.0, 4))); + assert!(!is_open(&mut app)); + } + + #[test] + fn held_mosaic_does_not_delete_a_raster_created_after_undo() { + let mut app = app_with_image(); + let source = image_id(&app); + open(&mut app, &json!({"columns": 2, "rows": 2, "deleteRaster": true})).unwrap(); + + app.run("edit.undo", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.node(NodeId(source)).is_none_or(|node| !matches!(node.kind, NodeKind::Image(_)))); + app.run("object.rasterize", json!({"ppi": 72})).unwrap(); + assert_eq!(image_id(&app), source, "the new raster repeats the same ID and pixels"); + let undo = app.session.active().unwrap().history.undo.len(); + ok(&mut app); + assert_eq!(mosaic(&app), None, "the old approval cannot delete the new raster"); + assert_eq!(image_id(&app), source); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(is_open(&mut app)); + + open(&mut app, &json!({"columns": 2, "rows": 2, "deleteRaster": true})).unwrap(); + ok(&mut app); + assert_eq!(mosaic(&app), Some((100.0, 50.0, 4))); + assert!(!is_open(&mut app)); + } } 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/office_export.rs b/crates/ui-egui/src/dialogs/office_export.rs index 8c70367fbf..b99ec46c12 100644 --- a/crates/ui-egui/src/dialogs/office_export.rs +++ b/crates/ui-egui/src/dialogs/office_export.rs @@ -48,7 +48,7 @@ fn params(boards: &Boards, fields: &DialogFields) -> Vec { let ppi = number(fields, "ppi").unwrap_or(RESOLUTIONS[1]); let at = RESOLUTIONS.iter().position(|r| *r == ppi).unwrap_or(1); let board = (number(fields, "artboard").unwrap_or(0.0).max(0.0) as usize).min(boards.names.len().saturating_sub(1)); - let resolutions = RESOLUTIONS.iter().zip(RESOLUTION_LABELS.iter()).map(|(r, label)| (r.to_string(), Label::from(*label))).collect(); + let resolutions = RESOLUTIONS.iter().zip(RESOLUTION_LABELS.iter()).map(|(r, label)| (r.to_string(), Label::from(tl!(*label)))).collect(); let mut rows = vec![Param::new("ppi", tl!("Resolution:"), ParamKind::choice(resolutions, Some(RESOLUTIONS[1].to_string())))]; if boards.names.len() > 1 { let names = boards.names.iter().enumerate().map(|(i, name)| (i.to_string(), Label::from(name.clone()))).collect(); @@ -68,7 +68,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields.set("transparent", false); let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { let rows = params(&boards, fields); - ParamDialog::new(KIND, tl!("Save for Office Documents"), rows).values(Bind::bound(fields)).ok_label(Label::from("Save…")) + ParamDialog::new(KIND, tl!("Save for Office Documents"), rows).values(Bind::bound(fields)).ok_label(Label::from(tl!("Save…"))) }); export_host::open(app, Export::Office, false, dialog).ok_or("no window")?; Ok(Value::Null) diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 92cba2edb5..12205dca03 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -113,7 +113,10 @@ impl PathOp { pub(crate) struct Open { op: PathOp, id: DialogId, + document: u64, preview: LivePreview, + /// A distinct selection snapshot identifies the interaction that ran this preview. + preview_selection: Option>, /// The params the preview last answered for. last: Value, /// Simplify: the paths the preview ran on. @@ -126,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>, @@ -136,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; @@ -159,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()); @@ -358,6 +366,36 @@ fn take_open(app: &mut VectorcraftApp, op: PathOp) -> Option { Some(app.object_dialogs.path.remove(i)) } +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.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection)) + }) + } + + fn cancel(self, app: &mut VectorcraftApp) { + if self.owns_preview(app) { + self.preview.cancel(app); + } + } + + fn commit(&mut self, app: &mut VectorcraftApp, cmd: &str, params: Value) -> Result<(), String> { + if app.session.active().is_none_or(|state| state.uid != self.document) { + return Err(tl!("Return to the document where this dialog opened.").to_owned()); + } + if app.session.in_interaction() && !self.owns_preview(app) { + return Err(tl!("Finish the active edit before confirming.").to_owned()); + } + self.preview_selection = None; + self.last = Value::Null; + self.original.clear(); + self.shown = false; + std::mem::take(&mut self.preview).commit(app, cmd, params).map(drop) + } +} + /// Whether Object › Path › Simplify opens its dialog (the user kept its settings) instead of the slider. pub(crate) fn retained_simplify(app: &VectorcraftApp) -> bool { let Some(ctx) = app.ui_ctx.as_ref() else { return false }; @@ -393,6 +431,11 @@ fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remem app.status("There is no window to show the dialog in."); return; }; + let document = app.session.active().map(|state| state.uid); + if op.previews() && document.is_none() { + app.status("Open a document before editing paths."); + return; + } let lengths = crate::canvas::general_lengths(app); let opening = op.opening(); let key = op.key(); @@ -408,17 +451,11 @@ fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remem }); let ok = move |app: &mut VectorcraftApp, result: &craft::ui::patterns::form_dialogs::ParamResult| { let (cmd, params) = command(op, &result.fields); - match take_open(app, op) { - Some(record) => { - let id = record.id; - record.preview.commit(app, cmd, params).map(drop).inspect_err(|_| { - // The dialog stays open on the refusal, so it keeps previewing. - app.object_dialogs.path.push(Open { op, id, preview: LivePreview::default(), last: Value::Null, original: vec![], shown: false }); - })?; - } - None => { - app.run(cmd, params).map(drop)?; - } + if op.previews() { + let Some(mut record) = take_open(app, op) else { return Err(tl!("The path dialog is closed.").to_owned()) }; + record.commit(app, cmd, params).inspect_err(|_| app.object_dialogs.path.push(record))?; + } else { + app.run(cmd, params).map(drop)?; } match op { PathOp::Simplify => { @@ -432,24 +469,40 @@ fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remem Ok(()) }; if let Some(old) = take_open(app, op) { - old.preview.cancel(app); + old.cancel(app); } let id = if op.previews() { let cancel = Box::new(move |app: &mut VectorcraftApp| { + // A cancelled opening can leave a replacement with the same dialog ID. + let id = app.object_dialogs.path.iter().find(|record| record.op == op).map(|record| record.id); + if let Some(id) = id + && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::(id).is_some())) + { + return; + } if let Some(record) = take_open(app, op) { - record.preview.cancel(app); + record.cancel(app); } }); open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }) } else { open_held(app, dialog, ok) }; - match id { - Some(id) if op.previews() => { - app.object_dialogs.path.push(Open { op, id, preview: LivePreview::default(), last: Value::Null, original: vec![], shown: false }) + match (id, document) { + (Some(id), Some(document)) if op.previews() => { + app.object_dialogs.path.push(Open { + op, + id, + document, + preview: LivePreview::default(), + preview_selection: None, + last: Value::Null, + original: vec![], + shown: false, + }); } - Some(_) => {} - None => app.status("There is no window to show the dialog in."), + (Some(_), _) => {} + (None, _) => app.status("There is no window to show the dialog in."), } } @@ -464,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| { @@ -477,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."), } } @@ -508,6 +562,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { fn step(app: &mut VectorcraftApp, r: &mut Open) { let Some((on, fields)) = dialog_state(app, r.id) else { return }; + let Some(state) = app.session.active().filter(|state| state.uid == r.document) else { return }; + if !r.owns_preview(app) { + r.preview = LivePreview::default(); + r.preview_selection = None; + r.last = Value::Null; + r.original.clear(); + r.shown = false; + if state.interaction.is_some() { + return; + } + } let (cmd, params) = command(r.op, &fields); let stale = !on || r.last != params; if stale { @@ -515,13 +580,17 @@ fn step(app: &mut VectorcraftApp, r: &mut Open) { } if !on { r.last = Value::Null; + r.preview_selection = None; } let mut counts = stale.then_some(None); - if let Some(Ok(answer)) = r.preview.run(app, on, r.op.title(), cmd, ¶ms) { - r.last = params; - if r.op == PathOp::Simplify { - r.original = answer["ids"].as_array().into_iter().flatten().filter_map(|id| id.as_u64().map(NodeId)).collect(); - counts = Some(Some(json!({"before": answer["before"], "after": answer["after"]}))); + if let Some(answer) = r.preview.run(app, on, r.op.title(), cmd, ¶ms) { + r.preview_selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection)); + if let Ok(answer) = answer { + r.last = params; + if r.op == PathOp::Simplify { + r.original = answer["ids"].as_array().into_iter().flatten().filter_map(|id| id.as_u64().map(NodeId)).collect(); + counts = Some(Some(json!({"before": answer["before"], "after": answer["after"]}))); + } } } r.shown = on && fields.bool("showOriginal").unwrap_or(false); @@ -542,7 +611,7 @@ fn step(app: &mut VectorcraftApp, r: &mut Open) { /// on, with its id, as it was before the preview (from the interaction's snapshot). Empty /// otherwise. pub(crate) fn original_paths(app: &VectorcraftApp) -> Vec<(NodeId, &PathData)> { - let Some(r) = app.object_dialogs.path.iter().find(|r| r.op == PathOp::Simplify && r.shown) else { return vec![] }; + let Some(r) = app.object_dialogs.path.iter().find(|r| r.op == PathOp::Simplify && r.shown && r.owns_preview(app)) else { return vec![] }; let Some(it) = app.session.active().and_then(|st| st.interaction.as_ref()) else { return vec![] }; r.original .iter() @@ -555,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::*; @@ -570,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(); @@ -664,3 +793,99 @@ mod split_tests { assert_eq!(app.session.doc().unwrap().doc, editing); } } + +#[cfg(test)] +mod preview_document_tests { + use super::*; + use crate::dialogs::tests::{app, cancel, confirm, frame, set}; + + fn dense_path(app: &mut VectorcraftApp, top: f64) -> u64 { + let anchors: Vec<_> = (0..20).map(|i| json!({"x": 30 + i * 15, "y": top + (i % 2) as f64 * 0.1})).collect(); + let id = app.run("path.create", json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap(); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 19]]})).unwrap(); + id + } + + fn drawings() -> (VectorcraftApp, NodeId) { + let mut app = app(); + let id = dense_path(&mut app, 50.0); + app.run("file.new", json!({"width": 500, "height": 400})).unwrap(); + let other = dense_path(&mut app, 180.0); + assert_eq!(id, other, "the two drawings use the same path ID"); + app.run("document.activate", json!({"index": 0})).unwrap(); + (app, NodeId(id)) + } + + fn more_options(app: &mut VectorcraftApp) { + crate::menus::invoke(app, "object.path.simplify", json!({})); + crate::dialogs::simplify_slider::more_options(app).unwrap(); + } + + #[test] + fn simplify_options_skip_the_other_drawings_artwork() { + for from_slider in [false, true] { + let (mut app, _) = drawings(); + if from_slider { + more_options(&mut app); + } else { + let ctx = app.ui_ctx.clone().unwrap(); + set_saved_value(&ctx, &SIMPLIFY_KEY, Some(simplify_dialog(DEFAULT_TOLERANCE))); + crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + } + set(&mut app, "preview", json!(true)); + app.run("document.activate", json!({"index": 1})).unwrap(); + let other = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + + frame(&mut app, vec![]); + + assert!(app.session.doc().unwrap().doc == other, "Simplify preview leaves the other drawing unchanged"); + assert!(!app.session.in_interaction()); + assert!(!confirm(&mut app), "the draft stays with the opening drawing"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, vec![]); + assert!(app.session.in_interaction()); + assert!(confirm(&mut app)); + } + } + + #[test] + fn simplify_options_never_outline_another_drawings_same_id() { + let (mut app, id) = drawings(); + more_options(&mut app); + set(&mut app, "showOriginal", json!(true)); + set(&mut app, "preview", json!(true)); + frame(&mut app, vec![]); + assert_eq!(original_paths(&app).iter().map(|(path, _)| *path).collect::>(), [id]); + + app.run("document.activate", json!({"index": 1})).unwrap(); + app.session.begin_interaction("Other edit").unwrap(); + + assert!(original_paths(&app).is_empty(), "Show Original leaves the other drawing's canvas alone"); + assert!(cancel(&mut app)); + assert!(app.session.in_interaction(), "Cancel leaves the other drawing's edit in progress"); + } + + #[test] + fn offset_path_skips_the_other_drawings_artwork() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 20, "width": 100, "height": 60})).unwrap(); + app.run("select.all", json!({})).unwrap(); + crate::menus::invoke(&mut app, "object.path.offsetPath", json!({})); + set(&mut app, "offset", json!(12.0)); + set(&mut app, "preview", json!(true)); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 140, "y": 30, "width": 80, "height": 100})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let other = app.session.doc().unwrap().doc.clone(); + + frame(&mut app, vec![]); + + assert!(app.session.doc().unwrap().doc == other, "Offset Path preview leaves the other drawing unchanged"); + assert!(!confirm(&mut app)); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(confirm(&mut app)); + assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + } +} 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/perspective_plane.rs b/crates/ui-egui/src/dialogs/perspective_plane.rs index 13ec8754e0..117bf3b2b7 100644 --- a/crates/ui-egui/src/dialogs/perspective_plane.rs +++ b/crates/ui-egui/src/dialogs/perspective_plane.rs @@ -20,6 +20,7 @@ use crate::canvas::general_lengths; pub const KIND: &str = "perspectivePlane"; const OPENING_DOCUMENT: &str = "__openingDocument"; +const OPENING_REVERTS: &str = "__openingReverts"; /// What becomes of the objects on the plane: (`objects` value, label). const OBJECTS: [(&str, &str); 3] = [("none", "Do Not Move"), ("move", "Move All Objects"), ("copy", "Copy All Objects")]; @@ -50,7 +51,7 @@ fn build<'a>(title: &str, lengths: LengthUnits, _fields: &'a mut DialogFields) - /// Open the options of `plane` (`{plane}`; default the active plane), filled in with its location. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let state = app.session.active().ok_or("no document")?; - let document = state.uid; + let (document, reverts) = (state.uid, state.reverts); let g = PerspectiveGrid::current(&state.doc); let plane = match p.get("plane").and_then(Value::as_str) { Some(s) => Plane::parse(s).ok_or("plane must be left, right or ground")?, @@ -66,13 +67,18 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let mut fields = form::fields_of(¶ms(lengths), &map); // The held answer carries the drawing and plane from the same opening. fields.set(OPENING_DOCUMENT, document.to_string()); + fields.set(OPENING_REVERTS, reverts.to_string()); let heading = title(plane); let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |f| build(&heading, lengths, f)); // A refusal keeps the dialog open with the reason under its rows. let ok = |app: &mut VectorcraftApp, r: &ParamResult| { let document = r.fields.text(OPENING_DOCUMENT).and_then(|uid| uid.parse().ok()); - if !app.session.active().is_some_and(|state| Some(state.uid) == document) { + let Some(active) = app.session.active().filter(|state| Some(state.uid) == document) else { return Err(tl!("Perspective Plane Options can only change the document where it was opened.").to_owned()); + }; + let reverts = r.fields.text(OPENING_REVERTS).and_then(|value| value.parse::().ok()); + if reverts != Some(active.reverts) { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); } let plane = r.fields.text("plane").ok_or_else(|| tl!("The perspective plane is missing").to_owned())?; let objects = r.fields.text("objects").unwrap_or("none"); @@ -226,4 +232,35 @@ mod tests { let id = *st.selection.objects.first().unwrap(); assert_eq!(vectorcraft_tools::distort::perspective::attachment(st.doc.node(id).unwrap()).map(|a| a.0), Some(Plane::Right)); } + + #[test] + fn held_plane_options_cannot_move_or_copy_restored_artwork() { + let mut app = app(); + right_plane_with_art(&mut app); + let dir = vectorcraft_testkit::TempDir::new("perspective-plane-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("perspective.plane.move", json!({"plane": "right", "offset": 10.0, "objects": "none"})).unwrap(); + app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap(); + set(&app, "location", json!(40.0)); + set(&app, "objects", json!("copy")); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let restored = app.session.active().unwrap().doc.clone(); + let (id, _) = the_dialog(&app); + pump_ok(&mut app); + assert!(matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_)))); + assert_eq!(app.session.active().unwrap().doc, restored); + + let ctx = app.ui_ctx.clone().unwrap(); + host(&app, |h| h.cancel_by_id(&ctx, id)); + app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap(); + set(&app, "location", json!(40.0)); + set(&app, "objects", json!("copy")); + ok(&mut app); + let doc = &app.session.active().unwrap().doc; + assert_eq!(PerspectiveGrid::current(doc).right_offset, 40.0); + assert_eq!(doc.layers[0].children().unwrap().len(), 2); + } } 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/rearrange_artboards.rs b/crates/ui-egui/src/dialogs/rearrange_artboards.rs index d99e34f28f..3926501a05 100644 --- a/crates/ui-egui/src/dialogs/rearrange_artboards.rs +++ b/crates/ui-egui/src/dialogs/rearrange_artboards.rs @@ -156,7 +156,7 @@ fn open_with(app: &mut VectorcraftApp, indices: Option>) -> Result>, /// The artboards the dialog lays out (the document's, or the selected ones), which bounds Columns @@ -190,7 +190,7 @@ pub(crate) struct RearrangeArtboardsDialog { pub(crate) struct RearrangeAnswer { values: RearrangeValues, - document: u64, + document: (u64, u64), selected: Option>, } @@ -327,12 +327,13 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(DialogResult::Ok(RearrangeAnswer { values, document, selected })) = dialogs.with(|host| host.take::()) else { return; }; - let applied = if app.session.active().is_none_or(|st| st.uid != document) { - Err(tl!("Rearrange Artboards can only change the document where it was opened.").to_owned()) - } else if let Some(selected) = selected { - wait_for_click(app, &selected, values.params()) - } else { - app.run(CMD, values.params()).map(drop) + let applied = match app.session.active() { + Some(st) if st.uid == document.0 && st.reverts != document.1 => Err(tl!("Reopen Rearrange Artboards after reverting the drawing").to_owned()), + Some(st) if (st.uid, st.reverts) == document => match selected { + Some(selected) => wait_for_click(app, &selected, values.params()), + None => app.run(CMD, values.params()).map(drop), + }, + _ => Err(tl!("Rearrange Artboards can only change the document where it was opened.").to_owned()), }; match applied { Ok(()) => app.ui.rearrange_artboards_spacing = json!(values.spacing), @@ -352,7 +353,7 @@ fn wait_for_click(app: &mut VectorcraftApp, selected: &[(usize, u32)], mut param } params["indices"] = json!(indices); let (doc, tool) = (st.uid, app.session.tool_id().to_string()); - app.ui.rearrange_placement = Some(RearrangePlacement { doc, tool, params, ids, armed: false }); + app.ui.rearrange_placement = Some(RearrangePlacement { doc, reverts: st.reverts, tool, params, ids, armed: false }); app.status(PLACE_HINT); Ok(()) } @@ -370,11 +371,11 @@ pub(crate) fn cancel_placement(app: &mut VectorcraftApp) { } /// Whether a placement waits for its click: one whose document is no longer the active one, whose -/// tool is no longer the tool in use, or whose listed places no longer hold the artboards it was -/// confirmed for (removed or moved in the list) is dropped. +/// tool is no longer in use, or whose confirmed artboards were reloaded, removed or reordered +/// is dropped. pub(crate) fn refresh_placement(app: &mut VectorcraftApp) -> bool { let Some(pl) = app.ui.rearrange_placement.as_ref() else { return false }; - let same = app.session.active().filter(|d| d.uid == pl.doc).is_some_and(|d| { + let same = app.session.active().filter(|d| d.uid == pl.doc && d.reverts == pl.reverts).is_some_and(|d| { let listed = placed(pl); listed.len() == pl.ids.len() && listed.iter().zip(&pl.ids).all(|(i, id)| d.doc.artboards.get(*i).is_some_and(|a| a.id == *id)) }); @@ -402,6 +403,9 @@ pub(crate) fn arm(app: &mut VectorcraftApp) { /// point, or the pointer when Enter placed it); without `at` the grid starts at the first selected /// artboard's top-left. When every selected artboard is locked, the status bar says so. pub(crate) fn place(app: &mut VectorcraftApp, at: Option) { + if !refresh_placement(app) { + return; + } let Some(mut pl) = app.ui.rearrange_placement.take() else { return }; let listed = placed(&pl); let locked = app.session.active().is_some_and(|d| listed.iter().all(|i| d.doc.artboards.get(*i).is_some_and(|a| a.locked))); @@ -420,7 +424,9 @@ pub(crate) fn place(app: &mut VectorcraftApp, at: Option) { /// outline of each artboard that moves, in the Artboard tool's color, 1 point wide on screen. pub(crate) fn placement_overlays(app: &VectorcraftApp) -> Vec { let Some(pl) = app.ui.rearrange_placement.as_ref().filter(|pl| app.session.tool_id() == pl.tool) else { return vec![] }; - let (Some(at), Some(st)) = (app.hover_doc, app.session.active().filter(|d| d.uid == pl.doc)) else { return vec![] }; + let (Some(at), Some(st)) = (app.hover_doc, app.session.active().filter(|d| d.uid == pl.doc && d.reverts == pl.reverts)) else { + return vec![]; + }; let boards: Vec<&vectorcraft_doc::Artboard> = placed(pl).into_iter().filter_map(|i| st.doc.artboards.get(i)).collect(); let sizes: Vec<(f64, f64)> = boards.iter().map(|a| (a.rect.width(), a.rect.height())).collect(); let p = &pl.params; @@ -524,6 +530,64 @@ mod tests { check_rearrange_stays_in_opening_document(true); } + fn check_revert_retires_rearrange(selected: bool, already_confirmed: bool) { + let mut app = app(3); + 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("rearrange-artboards-revert"); + app.run("file.saveAs", json!({"path": dir.join("artboards.vectorcraft")})).unwrap(); + let saved = origins(&app); + let source = app.session.active().unwrap(); + let version = (source.uid, source.reverts); + + app.run(CMD, json!({"layout": "row", "spacing": 47})).unwrap(); + assert_ne!(origins(&app), saved); + if selected { + app.select_tool("artboard"); + open_selected(&mut app, &[0, 2]); + } else { + open_from_menu(&mut app); + } + set(&app, &[("layout", json!("row")), ("spacing", json!(37))]).unwrap(); + if already_confirmed { + ok(&mut app); + assert!(refresh_placement(&mut app)); + } + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let source = app.session.active().unwrap(); + assert_eq!(source.uid, version.0); + assert_ne!(source.reverts, version.1); + assert_eq!(origins(&app), saved); + let undo = source.history.undo.len(); + let remembered = app.ui.rearrange_artboards_spacing.clone(); + if already_confirmed { + assert!(!refresh_placement(&mut app), "reloaded artboards cannot receive a pending placement"); + place(&mut app, Some(Point::new(700.0, 300.0))); + } else { + ok(&mut app); + } + assert_eq!(origins(&app), saved, "reloaded artboards stay at their saved locations"); + assert!(app.ui.rearrange_placement.is_none()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.rearrange_artboards_spacing, remembered); + } + + #[test] + fn revert_retires_rearrange_all_artboards_settings() { + check_revert_retires_rearrange(false, false); + } + + #[test] + fn revert_retires_rearrange_selected_artboards_settings() { + check_revert_retires_rearrange(true, false); + } + + #[test] + fn revert_retires_rearrange_canvas_placement() { + check_revert_retires_rearrange(true, true); + } + #[test] fn rearrange_opening_keeps_the_intended_artboards_after_rows_move() { let mut app = app(3); 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/relink.rs b/crates/ui-egui/src/dialogs/relink.rs index b0d67a92f0..ac99cf9b0c 100644 --- a/crates/ui-egui/src/dialogs/relink.rs +++ b/crates/ui-egui/src/dialogs/relink.rs @@ -46,6 +46,7 @@ fn scope_label(scope: &str) -> Label { /// Open the dialog on the images and placed documents `ids` (default: the selected ones). pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { + let document = app.session.active().ok_or("no document open")?.uid; let ids = match p.get("ids").filter(|v| !v.is_null()) { Some(v) => v.as_array().cloned().ok_or_else(|| format!("`ids` must be an array of object ids, not {v}"))?, None => crate::panels::links::selected_ids(app).into_iter().map(Value::from).collect(), @@ -80,13 +81,18 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { links.push(json!({ "name": name, "ids": [id] })); } } - let dialog = RelinkDialog::new(ids, links); + let dialog = RelinkDialog::new(document, ids, links); crate::dialogs::host::open_held(app, dialog, relink).ok_or("no window")?; Ok(Value::Null) } /// The relink rule: one `links.relink` call with the answer's parameters, and the status it earns. -fn relink(app: &mut VectorcraftApp, params: &Value) -> Result<(), String> { +fn relink(app: &mut VectorcraftApp, (document, params): &(u64, Value)) -> Result<(), String> { + if app.session.active().is_none_or(|st| st.uid != *document) { + let reason = tl!("Relink can only change links in the document where it was opened."); + app.status(reason); + return Err(reason.to_owned()); + } let r = app.run(CMD, params.clone())?; let missed: Vec<&str> = r["notFound"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); app.status(crate::panels::links::relinked_status_missed(r["relinked"].as_array().map_or(0, Vec::len), &missed)); @@ -116,6 +122,8 @@ impl ItemSource for Names<'_> {} /// app (`HoldsOk`); with Each Link Separately it stays open until every link has a file. pub(crate) struct RelinkDialog { id: DialogId, + /// The document that owns the link IDs. + document: u64, ids: Vec, links: Vec, scope: String, @@ -127,9 +135,10 @@ pub(crate) struct RelinkDialog { } impl RelinkDialog { - fn new(ids: Vec, links: Vec) -> Self { + fn new(document: u64, ids: Vec, links: Vec) -> Self { RelinkDialog { id: dialog_id(KEY), + document, ids, links, scope: "selected".into(), @@ -185,17 +194,21 @@ impl RelinkDialog { } impl HoldsOk for RelinkDialog { - type Answer = Value; + type Answer = (u64, Value); fn held_ok(self) -> Self { self } - fn take_ok(&mut self) -> Option { - self.held.take() + fn take_ok(&mut self) -> Option { + self.held.take().map(|params| (self.document, params)) } fn answer_ok(&mut self, answer: Result<(), Label>) { + // A refused complete pass starts over so each new pick is assigned to a link. + if answer.is_err() && self.scope == "each" { + self.paths.clear(); + } self.held.answer(answer); } } @@ -393,6 +406,53 @@ mod tests { pass(app); } + fn check_relink_stays_in_opening_drawing(native_picker: bool) { + let (mut app, dir) = setup(if native_picker { "opening-picker" } else { "opening-path" }, &["source.png", "destination.png"]); + let picker = scripted(&mut app); + let original = dir.join("source.png"); + let destination = dir.join("destination.png"); + let source_id = place(&mut app, &original); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let destination_id = place(&mut app, &destination); + assert_eq!(source_id, destination_id, "linked objects may have the same local ID"); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.relinkDialog", json!({"ids": [source_id]})).unwrap(); + if native_picker { + ok(&mut app, &[]); + } + + let selected = new_file(&dir, "replacement.png"); + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + if native_picker { + picker.answer(&[&selected]); + pass(&mut app); + } else { + ok(&mut app, &[("path", json!(selected))]); + } + assert_eq!(link_path(&app, destination_id), destination.to_string_lossy()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "Relink can only change links in the document where it was opened."); + let dialog = relink_dialog(&app).id; + assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + ok(&mut app, &[("path", json!(selected))]); + assert!(open_dialogs(&app).is_empty()); + assert_eq!(link_path(&app, source_id), selected); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn relink_opening_drawing_is_required_for_a_path_confirmation() { + check_relink_stays_in_opening_drawing(false); + } + + #[test] + fn relink_opening_drawing_is_required_when_the_file_picker_answers() { + check_relink_stays_in_opening_drawing(true); + } + #[test] fn relink_opens_with_the_replace_choice_and_all_instances_relinks_every_copy() { let (mut app, dir) = setup("all", &["photo.png", "other.png"]); @@ -443,6 +503,39 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + #[test] + fn each_link_separately_lets_the_user_choose_new_paths_after_a_refusal() { + let (mut app, dir) = setup("each-after-refusal", &["one.png", "two.png"]); + let picker = scripted(&mut app); + let ids = [place(&mut app, &dir.join("one.png")), place(&mut app, &dir.join("two.png"))]; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.relinkDialog", json!({"ids": ids})).unwrap(); + ok(&mut app, &[("scope", json!("each"))]); + picker.answer(&[&new_file(&dir, "old-one.png")]); + pass(&mut app); + ok(&mut app, &[]); + app.run("document.activate", json!({"index": 1})).unwrap(); + picker.answer(&[&new_file(&dir, "old-two.png")]); + pass(&mut app); + let dialog = relink_dialog(&app).id; + assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + let paths = [new_file(&dir, "new-one.png"), new_file(&dir, "new-two.png")]; + for (i, path) in paths.iter().enumerate() { + ok(&mut app, &[]); + picker.answer(&[path]); + pass(&mut app); + if i == 0 { + assert_eq!(fields(&app)["paths"], json!([path]), "the second link still needs its new file"); + } + } + assert!(open_dialogs(&app).is_empty()); + assert_eq!(ids.map(|id| link_path(&app, id)), paths); + let _ = std::fs::remove_dir_all(dir); + } + /// An embedded image in the selection gets a row of its own, so Each Link Separately asks for /// its file too. #[test] diff --git a/crates/ui-egui/src/dialogs/revolve_gizmo.rs b/crates/ui-egui/src/dialogs/revolve_gizmo.rs index 985b13174a..32e66cb6f8 100644 --- a/crates/ui-egui/src/dialogs/revolve_gizmo.rs +++ b/crates/ui-egui/src/dialogs/revolve_gizmo.rs @@ -819,7 +819,9 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) { three_d::with_fields(app, |dialog| write(dialog, before, landed)); } } - super::three_d_classic::show_outline(app, ui, space); + if three_d::editing_current_drawing(app) { + super::three_d_classic::show_outline(app, ui, space); + } } #[cfg(test)] 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_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index 200b91f458..9076f18d21 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -513,6 +513,24 @@ fn eps_save_transparency_follows_the_color_preview() { assert_eq!(dialog(&mut app).bool("embedFonts"), Some(true)); } +#[test] +fn a_native_save_options_draft_cannot_redirect_its_path_to_another_drawing() { + let (mut app, written, _) = desktop("original.vectorcraft"); + assert_eq!(save_as(&mut app, "file.saveAs").as_deref(), Some(KIND)); + let draft_path = dialog(&mut app).text("path").unwrap().to_owned(); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + assert!(!ok(&mut app)); + assert_eq!(dialog(&mut app).text("path"), Some(draft_path.as_str())); + assert!(written.borrow().is_empty()); + assert!(app.session.active().unwrap().path.is_none()); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(ok(&mut app), "{}", app.ui.status); + assert_eq!(written.borrow()[0].0, draft_path); + assert!(app.session.documents()[1].path.is_none()); +} + /// #4931: a native file's Version is a menu of the versions VectorCraft writes, the current one /// first and chosen, each named by the releases that read it. An older version without /// compression saves plain, whatever Use Compression held. @@ -557,3 +575,44 @@ fn a_refused_save_says_so_in_an_alert() { let st = app.session.active().unwrap(); assert!(st.is_dirty() && st.path.is_none(), "not saved"); } + +#[test] +fn native_save_options_do_not_write_a_copy_after_file_revert() { + use craft::ui::dialog::HeldOk; + + for accepted_before_revert in [false, true] { + let (mut app, written, _) = desktop("revision-copy.vectorcraft"); + let dir = vectorcraft_testkit::TempDir::new("save-options-revert"); + let source = dir.join("source.vectorcraft"); + let record_outcome = app.services.write.take(); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": source})).unwrap(); + app.services.write = record_outcome; + app.run("shape.ellipse", json!({"x": 10, "y": 10, "width": 15, "height": 15})).unwrap(); + assert_eq!(save_as(&mut app, "file.saveAs").as_deref(), Some(KIND)); + let (ctx, id) = (app.ui_ctx.clone().unwrap(), top(&mut app)); + assert!(!host(&app, |h| h.confirm_by_id(&ctx, id))); + assert_eq!(host(&app, |h| h.held_state(id)), Some(HeldOk::Waiting)); + if accepted_before_revert { + super::super::host::pump(&mut app, &ctx); + assert_eq!(host(&app, |h| h.held_state(id)), Some(HeldOk::Accepted)); + assert!(host(&app, |h| h.confirm_by_id(&ctx, id))); + } + assert!(written.borrow().is_empty()); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + super::super::host::pump(&mut app, &ctx); + assert!(written.borrow().is_empty(), "the old options must not write restored contents"); + if accepted_before_revert { + assert!(app.ui.status.contains("document was reverted")); + } else { + assert!(matches!(host(&app, |h| h.held_state(id)), Some(HeldOk::Refused(_)))); + host(&app, |h| h.cancel_by_id(&ctx, id)); + super::super::host::pump(&mut app, &ctx); + } + assert_eq!(save_as(&mut app, "file.saveAs").as_deref(), Some(KIND)); + assert!(ok(&mut app)); + assert_eq!(written.borrow()[0].0, "revision-copy.vectorcraft"); + } +} diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index e003cf6a7e..506ef94fce 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -33,9 +33,12 @@ use crate::{VectorcraftApp, io}; const PENDING: &str = "savePdf"; /// Why a Summary cannot be written without the dialog. const NOT_OPEN: &str = "the Save PDF dialog is not open"; +const WRONG_DOCUMENT: &str = "Return to the original drawing to save the PDF or its summary"; /// What the Save PDF dialog was opened for; the preset editor has none. pub(crate) struct SavePdfJob { + /// The drawing this job reads and writes. + 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. @@ -69,6 +72,7 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) -> Result { /// [`open`], for Export Selection when `selection` (the page is the selection's crop). pub(crate) fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) -> Result { + let document = app.session.active().ok_or("no document")?.uid; let art_bounds = match params.get("useArtboards") { None | Some(Value::Null) => false, Some(Value::Bool(b)) => !b, @@ -102,7 +106,7 @@ pub(crate) fn open_with(app: &mut VectorcraftApp, params: &Value, selection: boo }; let preset = s("preset").map_or_else(|| default_preset_name(APP).to_string(), str::to_string); let dialog = base_dialog(app, settings).preset(preset).artboards(artboards); - let job = SavePdfJob { path: s("path").map(str::to_string), save_mode: None, flattener, selection }; + let job = SavePdfJob { document, path: s("path").map(str::to_string), save_mode: None, flattener, selection }; open_dialog(app, dialog, Some(job), String::new()) } @@ -279,11 +283,14 @@ fn drive(app: &mut VectorcraftApp, ctx: &egui::Context, open: &mut SavePdfOpen) } } // A failed write is told over the dialog, which shows again when the message closes. - if let Some(text) = filed.summary - && let Err(e) = write_summary(app, Some(id), None, &text) - && e != "cancelled" - { - app.status(e); + let source = check_source(app, open); + if let Some(text) = filed.summary { + let saved = source.clone().and_then(|()| write_summary(app, Some(id), None, &text)); + if let Err(e) = saved + && e != "cancelled" + { + app.status(crate::i18n::message(crate::i18n::current(), &e)); + } } let preset = filed.settings.get("flattenerPreset").and_then(Value::as_str).map(str::to_owned); if open.flattener_preset.is_some() @@ -294,7 +301,10 @@ fn drive(app: &mut VectorcraftApp, ctx: &egui::Context, open: &mut SavePdfOpen) } open.flattener_preset = preset; let settings = with_custom(open, filed.settings); - let warnings = worded(check(app, open, &settings)); + let warnings = match source { + Ok(()) => worded(check(app, open, &settings)), + Err(e) => worded(&Err(e)), + }; let prefs = &app.session.prefs; let (presets, names) = (prefs.pdf_presets.clone(), prefs.flattener_presets.iter().map(|p| p.name.clone()).collect::>()); let custom = open.job.as_ref().is_some_and(|j| j.flattener.is_some()); @@ -308,7 +318,7 @@ fn drive(app: &mut VectorcraftApp, ctx: &egui::Context, open: &mut SavePdfOpen) }); if let Some(answer) = filed.ok { let reply = match &open.job { - Some(job) => write(app, job, &answer), + Some(job) => check_source(app, open).and_then(|()| write(app, job, &answer)), None => save_preset(app, &open.editing, &answer), }; // A write that asks first (the save panel, or whether to replace the file the document was opened from) closes @@ -323,6 +333,15 @@ fn drive(app: &mut VectorcraftApp, ctx: &egui::Context, open: &mut SavePdfOpen) false } +fn check_source(app: &VectorcraftApp, open: &SavePdfOpen) -> Result<(), String> { + if let Some(job) = &open.job + && app.session.active().map(|doc| doc.uid) != Some(job.document) + { + return Err(WRONG_DOCUMENT.into()); + } + Ok(()) +} + /// OK of Custom…: the open save flattens with its options ([`super::flatten::apply_custom`]); when the saved preset /// they started from is gone, Save PDF's flattener preset shows no name. fn custom_ok(app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { @@ -654,6 +673,7 @@ pub(crate) fn save_summary(app: &mut VectorcraftApp, p: &Value) -> Result Result { + check_source(app, open)?; let Some(dialogs) = app.dialogs() else { return Err(NOT_OPEN.into()) }; let id = open.id; let not_open = || NOT_OPEN.to_string(); diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 2f1ea8b8e2..c76c79f1d0 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -427,6 +427,28 @@ fn confirm_runs_export_pdf_with_the_dialog_options() { assert!(app.ui.status.starts_with("Saved /tmp/out.pdf"), "{}", app.ui.status); } +#[test] +fn save_pdf_and_summary_wait_for_the_drawing_that_opened_them() { + let (mut app, written) = app(); + app.run("ui.savePdfDialog", json!({"path": "/tmp/out.pdf", "compatibility": "1.5"})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + let error = app.run(SAVE_SUMMARY, json!({"path": "/tmp/summary.txt"})).unwrap_err(); + assert!(error.contains("original drawing"), "{error}"); + confirm(&mut app); + assert!(is_open(&app)); + assert!(written.borrow().is_empty()); + assert_eq!(fget(&app, "compatibility"), "1.5"); + + app.run("document.activate", json!({"index": 0})).unwrap(); + confirm(&mut app); + assert!(!is_open(&app)); + let w = written.borrow(); + assert_eq!(w.len(), 1); + assert_eq!(w[0].0, "/tmp/out.pdf"); + assert_eq!(vectorcraft_pdf::import(&w[0].1).unwrap().artboards.len(), 3); +} + /// A Save PDF that fails keeps the dialog open (#6861); saving again, once it works, closes it. #[test] fn a_failed_save_says_why_in_the_dialog() { 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/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 7cfe2649ec..dd2b1219e2 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -9,11 +9,14 @@ //! `sprayStain` and `sprayStyle` (Symbol Sprayer, each `average` or `userDefined`); `proportional` //! and `affectsDensity` (Symbol Sizer). +use std::sync::{Arc, Weak}; + use craft::ui::contract::Bind; -use craft::ui::patterns::form_dialogs::{HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::{Label, LengthUnits}; use craft::ui::value_drag::SliderScale; use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeId}; use vectorcraft_tools::settings::SYMBOLISM; use super::{form, host, tool_options}; @@ -83,6 +86,7 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { NUMBERS.iter().chain(&SWITCHES).chain(&SPRAY).chain(&["method"]).filter_map(|key| Some((key.to_string(), o.get(*key)?.clone()))).collect(); values.insert("tool".into(), json!(tool)); let density_was = values.get("density").and_then(Value::as_f64).map(|d| d.clamp(1.0, 10.0)); + let density = DensityTarget { value: density_was, document: app.session.active().map(|doc| (doc.uid, doc.reverts)), sets: selected_sets(app) }; let fields = form::fields_of(¶ms, &values); let shown = params.clone(); let ok = move |app: &mut VectorcraftApp, result: &ParamResult| { @@ -96,12 +100,8 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { } vectorcraft_tools::symbolism::check_options(&tool, &values)?; vectorcraft_tools::option_check::check_values(&vectorcraft_tools::symbolism::SymbolismTool::new(&tool), &values)?; - if let Some(from) = density_was { - let to = result.fields.number("density").unwrap_or(from).clamp(1.0, 10.0); - let sets = selected_sets(app); - if from != to && !sets.is_empty() { - app.run("symbol.setDensity", json!({ "from": from, "to": to, "ids": sets }))?; - } + if let Some(density) = app.ui_ctx.as_ref().and_then(|ctx| ctx.data(|d| d.get_temp::(density_id()))) { + density.apply(app, &result.fields)?; } tool_options::set_options(app, &tool, values) }; @@ -109,7 +109,9 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |f| { ParamDialog::new(KIND, tl!("Symbolism Tools Options"), shown.clone()).values(Bind::bound(f)) }); - host::open_held(app, dialog, ok) + let id = host::open_held(app, dialog, ok)?; + ctx.data_mut(|d| d.insert_temp(density_id(), density)); + Some(id) }); if opened.is_none() { app.status(tl!("No window to show the dialog in.").to_string()); @@ -117,15 +119,59 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { json!({ "dialog": KIND }) } -/// The selected symbol sets that can be edited (a locked or hidden one keeps its density). -fn selected_sets(app: &VectorcraftApp) -> Vec { +#[derive(Clone)] +struct DensityTarget { + value: Option, + document: Option<(u64, u64)>, + sets: Vec<(NodeId, Weak)>, +} + +fn density_id() -> egui::Id { + egui::Id::unique((KIND, "density-target")) +} + +impl DensityTarget { + fn apply(&self, app: &mut VectorcraftApp, fields: &DialogFields) -> Result<(), String> { + let Some(from) = self.value else { return Ok(()) }; + let to = fields.number("density").unwrap_or(from).clamp(1.0, 10.0); + if from == to || self.sets.is_empty() { + return Ok(()); + } + let Some(doc) = app.session.active().filter(|doc| self.document.is_some_and(|(uid, _)| uid == doc.uid)) else { + return Err(tl!("Return to the original drawing to change its symbol set density").into()); + }; + if self.document.is_none_or(|(_, reverts)| reverts != doc.reverts) { + return Err(tl!("Reopen Symbolism Tools Options after reverting the drawing").into()); + } + let sets: Vec<_> = { + let editable = doc.doc.editable(); + self.sets + .iter() + .filter_map(|(id, original)| { + let same = doc.doc.node_arc(*id).is_some_and(|node| Arc::as_ptr(node) == original.as_ptr()); + (same && editable(*id)).then_some(id.0) + }) + .collect() + }; + if !sets.is_empty() { + app.run("symbol.setDensity", json!({ "from": from, "to": to, "ids": sets }))?; + } + Ok(()) + } +} + +/// The selected editable sets as they exist now. Undo may reuse their IDs for newly created art. +fn selected_sets(app: &VectorcraftApp) -> Vec<(NodeId, Weak)> { let Some(st) = app.session.active() else { return vec![] }; let editable = st.doc.editable(); st.selection .objects .iter() - .filter(|id| st.doc.node(**id).is_some_and(vectorcraft_engine::cmd::is_symbol_set) && editable(**id)) - .map(|id| id.0) + .filter(|id| editable(**id)) + .filter_map(|id| { + let node = st.doc.node_arc(*id)?; + vectorcraft_engine::cmd::is_symbol_set(node).then(|| (*id, Arc::downgrade(node))) + }) .collect() } @@ -196,6 +242,62 @@ mod tests { } /// A locked symbol set in the selection keeps its spacing, and OK still sets the options. + #[test] + fn density_draft_waits_for_the_drawing_with_its_selected_symbol_set() { + let mut app = app(); + let first = sprayed(&mut app); + let first_width = width(&app, first); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let second = sprayed(&mut app); + let (second_width, second_undo) = (width(&app, second), undo(&app)); + app.run("document.activate", json!({"index": 0})).unwrap(); + open(&mut app, "symbolSprayer"); + set_of(&mut app, KIND, "density", json!(9)).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + let error = try_confirm(&mut app, KIND).expect_err("the density draft belongs to the other drawing"); + assert!(error.contains("original drawing"), "{error}"); + assert_eq!((width(&app, second), undo(&app)), (second_width, second_undo)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + try_confirm(&mut app, KIND).unwrap(); + assert!(width(&app, first) < first_width); + } + + #[test] + fn density_draft_keeps_the_symbol_set_that_was_selected_at_open() { + let mut app = app(); + let first = sprayed(&mut app); + let first_width = width(&app, first); + app.run("select.set", json!({"ids": []})).unwrap(); + let second = app.run("symbol.spray", json!({"name": "Dot", "points": [[40, 200], [120, 200]], "radius": 4})).unwrap()["id"].as_u64().unwrap(); + let second_width = width(&app, second); + app.run("select.set", json!({"ids": [first]})).unwrap(); + open(&mut app, "symbolSprayer"); + set_of(&mut app, KIND, "density", json!(9)).unwrap(); + app.run("select.set", json!({"ids": [second]})).unwrap(); + try_confirm(&mut app, KIND).unwrap(); + assert!(width(&app, first) < first_width); + assert_eq!(width(&app, second), second_width); + } + + #[test] + fn density_draft_does_not_change_a_symbol_set_that_reuses_an_undone_id() { + let mut app = app(); + let original = sprayed(&mut app); + open(&mut app, "symbolSprayer"); + set_of(&mut app, KIND, "density", json!(9)).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(original)).is_none()); + let points: Vec = (0..8).map(|i| json!([50.0 + 35.0 * f64::from(i), 100.0])).collect(); + let new = app.run("symbol.spray", json!({"name": "Dot", "points": points, "radius": 4})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(new, original, "Undo restored the allocation counter"); + let (original_width, steps) = (width(&app, new), undo(&app)); + + try_confirm(&mut app, KIND).unwrap(); + assert_eq!((width(&app, new), undo(&app)), (original_width, steps)); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(9.0)); + } + #[test] fn ok_sets_the_options_with_a_locked_symbol_set_selected() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/tate_chu_yoko.rs b/crates/ui-egui/src/dialogs/tate_chu_yoko.rs index edb0fb5bf6..e2f32ef4fd 100644 --- a/crates/ui-egui/src/dialogs/tate_chu_yoko.rs +++ b/crates/ui-egui/src/dialogs/tate_chu_yoko.rs @@ -10,6 +10,7 @@ //! Behavior reference (public documentation): //! . +use craft::ui::contract::Bind; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog}; // PLAN: assumed path of `LengthUnits` use craft::ui::runtime::env::LengthUnits; @@ -38,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]) { @@ -47,14 +49,21 @@ 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::type_lengths(app); - let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| ParamDialog::new(KIND, tl!("Tate-chu-yoko Settings"), rows(lengths))); + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { + ParamDialog::new(KIND, tl!("Tate-chu-yoko Settings"), rows(lengths)).values(Bind::bound(fields)) + }); super::host::open_held(app, dialog, move |app, result| { let p = params(&result.fields, &initial); 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(|_| ()) }) @@ -99,6 +108,17 @@ mod tests { } } + #[test] + fn tate_chu_yoko_settings_step_the_opening_number_on_ok() { + let (mut app, id) = app(); + app.run("text.setFormat", json!({"tcyUpDown": 3, "tcyLeftRight": -7})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + panel.app().run("ui.tateChuYokoSettings", json!({})).unwrap(); + driver::step_number_and_ok(&mut panel, "Up/Down"); + assert_eq!(offsets(&panel.app(), id), [(4.0, -7.0)]); + assert!(!driver::is_open(&panel.app())); + } + /// `ui.tateChuYokoSettings` opens on the characters' values; OK sets both in one undo step. /// Automation sets the offsets in points, as a number row takes them. #[test] @@ -185,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_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index 7ab85da4ae..f11039d48a 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -378,6 +378,28 @@ fn export_as_waits_for_the_drawing_that_opened_it() { assert_eq!(&written.borrow()[0].1[16..20], 60u32.to_be_bytes()); } +#[test] +fn png_options_wait_for_the_drawing_that_opened_them() { + let (mut app, written) = app(1); + app.run("file.export.png", json!({})).unwrap(); + answer_saves(&mut app); + assert_eq!(kind(&app).as_deref(), Some("pngOptions")); + let draft = fields(&app); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + let error = try_confirm(&mut app).expect_err("PNG Options must refuse the other drawing"); + assert!(error.contains("original drawing"), "{error}"); + assert_eq!(kind(&app).as_deref(), Some("pngOptions")); + assert_eq!(fields(&app)["path"], draft["path"]); + assert!(written.borrow().is_empty()); + + app.run("document.activate", json!({"index": 0})).unwrap(); + confirm(&mut app); + let w = written.borrow(); + assert_eq!(w.len(), 1); + assert_eq!(&w[0].1[16..20], 60u32.to_be_bytes()); +} + /// Each format's Export As continues in its options dialog, writes nothing before that dialog's OK, and then /// writes its files: (case, artboards, Export As params, the options' key, the files, the pages of a PDF, the /// page size of a PDF of the art's bounds). @@ -504,3 +526,69 @@ fn export_as_writes_only_the_chosen_artboard_in_every_format() { } } } + +fn native_export_as_source() -> (VectorcraftApp, Written, crate::tests_picks::Picker, vectorcraft_testkit::TempDir) { + let (mut app, written) = app(1); + let dir = vectorcraft_testkit::TempDir::new("export-as-after-revert"); + let capture = written.clone(); + app.services.write = Some(Box::new(move |path, bytes| { + if path.ends_with(".vectorcraft") { + std::fs::write(path, bytes).map_err(|error| error.to_string()) + } else { + capture.borrow_mut().push((path.to_string(), bytes.to_vec())); + Ok(()) + } + })); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|error| error.to_string()))); + let picker = crate::tests_picks::scripted(&mut app); + app.run("file.saveAs", json!({"path": dir.join("Export.vectorcraft")})).unwrap(); + app.run("shape.ellipse", json!({"x": 45, "y": 20, "width": 10, "height": 10})).unwrap(); + (app, written, picker, dir) +} + +fn revert_export_source(app: &mut VectorcraftApp) { + let source = app.session.active().unwrap(); + let (uid, reverts) = (source.uid, source.reverts); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let source = app.session.active().unwrap(); + assert_eq!((source.uid, source.reverts), (uid, reverts + 1)); +} + +#[test] +fn export_as_refuses_an_approval_from_before_native_revert() { + let (mut app, written, picker, _dir) = native_export_as_source(); + app.run("file.exportAs", json!({"format": "png", "useArtboards": true})).unwrap(); + revert_export_source(&mut app); + + let error = try_confirm(&mut app).expect_err("an old Export As approval must stay in the dialog"); + assert!(error.contains("Reopen this dialog")); + assert_eq!(kind(&app).as_deref(), Some("exportAs")); + assert_eq!(fields(&app)["useArtboards"], true); + assert!(picker.requests().is_empty(), "the retired draft did not open a save picker"); + assert!(written.borrow().is_empty()); +} + +#[test] +fn export_as_cannot_use_a_destination_selected_after_native_revert() { + let (mut app, written, picker, _dir) = native_export_as_source(); + app.run("file.exportAs", json!({"format": "png"})).unwrap(); + try_confirm(&mut app).unwrap(); + assert_eq!(picker.requests().len(), 1); + revert_export_source(&mut app); + + picker.answer_saved("/output/Old.png", None); + crate::file_asks::poll(&mut app); + frame(&mut app); + assert!(kind(&app).is_none(), "the retired pick did not open PNG Options"); + assert!(written.borrow().is_empty()); + + app.run("file.exportAs", json!({"format": "png"})).unwrap(); + try_confirm(&mut app).unwrap(); + assert_eq!(picker.requests().len(), 2); + picker.answer_saved("/output/Fresh.png", None); + crate::file_asks::poll(&mut app); + frame(&mut app); + assert_eq!(kind(&app).as_deref(), Some("pngOptions")); + try_confirm(&mut app).unwrap(); + assert_eq!(names(&written), ["/output/Fresh.png"]); +} 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/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 1648e86648..b4ae88d15a 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -112,6 +112,62 @@ fn stays_open(app: &mut VectorcraftApp) { assert_eq!(kind(app).as_deref(), Some(export_for_screens::KIND)); } +#[test] +fn a_queued_download_requires_fresh_confirmation_after_file_revert() { + use craft::ui::dialog::{HeldOk, dialog_id}; + + for artboards in [1, 2] { + let dir = vectorcraft_testkit::TempDir::new("screens-held-revert"); + let path = dir.join("saved.vectorcraft").to_string_lossy().into_owned(); + let (mut app, log) = app(artboards, true); + app.run("artboard.rename", json!({"indices": [0], "name": "Saved"})).unwrap(); + app.session.execute("document.save", &json!({"path": path})).unwrap(); + app.run("artboard.rename", json!({"indices": [0], "name": "Edited"})).unwrap(); + let uid = app.session.active().unwrap().uid; + let reverts = app.session.active().unwrap().reverts; + open(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(export_for_screens::KIND); + assert!(!dialogs.with(|host| host.confirm_by_id(&ctx, id))); + assert_eq!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Waiting)); + + app.run("file.revert", json!({"confirmed": true})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, uid); + assert!(app.session.active().unwrap().reverts > reverts, "the actual file was loaded back into its tab"); + let settings = app.session.active().unwrap().doc.export_settings.clone(); + export_for_screens::pump(&mut app, &ctx); + assert!(log.borrow().is_empty(), "the retired drawing's approval exports no restored content"); + assert_eq!(app.session.active().unwrap().doc.export_settings, settings); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); + try_confirm(&mut app).unwrap(); + let log = log.borrow(); + let [(name, bytes)] = log.as_slice() else { panic!("one download") }; + if artboards == 1 { + assert_eq!(name, "Saved.png"); + } else { + let names = zip_names(bytes); + assert!(names.iter().any(|name| name.ends_with("Saved.png"))); + assert!(!names.iter().any(|name| name.contains("Edited"))); + } + } +} + +#[test] +fn a_queued_download_still_uses_ordinary_edits_in_the_same_loaded_drawing() { + use craft::ui::dialog::dialog_id; + + let (mut app, log) = app(1, true); + open(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(export_for_screens::KIND); + assert!(!dialogs.with(|host| host.confirm_by_id(&ctx, id))); + app.run("artboard.rename", json!({"indices": [0], "name": "Current"})).unwrap(); + export_for_screens::pump(&mut app, &ctx); + assert_eq!(log.borrow().iter().map(|(name, _)| name.as_str()).collect::>(), ["Current.png"]); +} + #[test] fn a_queued_export_requires_fresh_confirmation_after_switching_documents() { use craft::ui::dialog::{HeldOk, dialog_id}; @@ -1493,6 +1549,30 @@ fn renaming_an_artboard_in_export_for_screens_renames_it() { } } +/// A rename begun before File Revert cannot rename an artboard restored from the saved file. +#[test] +fn an_artboard_name_cannot_reach_the_contents_loaded_by_file_revert() { + for view in ["grid", "list"] { + let dir = vectorcraft_testkit::TempDir::new("screens-rename-revert"); + let path = dir.join("saved.vectorcraft").to_string_lossy().into_owned(); + let (mut app, log) = app(2, true); + app.session.execute("document.save", &json!({"path": path})).unwrap(); + app.run("shape.rectangle", json!({"x": 1, "y": 1, "width": 5, "height": 5})).unwrap(); + let reverts = app.session.active().unwrap().reverts; + let mut w = Window::default(); + w.names(&mut app); + open(&mut app); + set(&mut app, "view", json!(view)); + type_artboard_name(&mut w, &mut app, "2 Artboard 2", "Retired Name"); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + assert!(app.session.active().unwrap().reverts > reverts); + w.key(&mut app, egui::Key::Enter); + assert_eq!(app.session.active().unwrap().doc.artboards[1].name, "Artboard 2"); + assert!(app.session.active().unwrap().history.undo.is_empty()); + assert!(log.borrow().is_empty(), "the stale name does not export either"); + } +} + /// A name typed while another document becomes active (a command from the control channel or MCP) /// renames no artboard of the active document. #[test] 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/three_d.rs b/crates/ui-egui/src/dialogs/three_d.rs index 1bf8a87680..6d4effc8e0 100644 --- a/crates/ui-egui/src/dialogs/three_d.rs +++ b/crates/ui-egui/src/dialogs/three_d.rs @@ -1,7 +1,7 @@ //! The host of the 3D effects' dialog: opens it through the held-dialog mechanism, keeps the app facts its rows read, //! runs the live preview, and refuses values the effect cannot draw. The rows are built by [`super::revolve`]. -use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard}; +use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, Weak}; use craft::ui::contract::Bind; use craft::ui::contract::overlay::{FloatPlace, Place as OverlayPlace}; @@ -9,7 +9,7 @@ use craft::ui::dialog::DialogId; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog, ParamLayout, ParamResult}; use craft::ui::runtime::env::Label; use serde_json::{Map, Value}; -use vectorcraft_doc::{Document, Unit}; +use vectorcraft_doc::{Document, Selection, Unit}; use vectorcraft_effects::{MAP_ART, MAP_INVISIBLE, MAP_SHADE, MapSurface, is_classic_three_d}; use vectorcraft_engine::EngineError; @@ -26,6 +26,7 @@ const MAP_ART_PAGE: &str = "mapArt"; /// The open 3D dialog and what its pump keeps between passes. pub(crate) struct Session { id: DialogId, + source: Option<(u64, u64)>, effect: String, label: String, // PLAN: the contract has `item: Option`; the command needs `null` (the object's effects) apart from an omitted item. @@ -34,12 +35,19 @@ pub(crate) struct Session { edit_target: Value, aligned: bool, preview: LivePreview, + preview_owner: Option, /// The command params of the last Preview-off try; `None` while Preview is on, so turning it off tries again. tried: Option, /// What the rows read, pushed each pump. pub(crate) data: Arc>, } +/// The interaction and preview last written by the 3D dialog. +struct PreviewOwner { + selection: Weak, + command: Option<(String, Value)>, +} + /// The app facts the 3D rows read. #[derive(Clone)] pub(crate) struct Data { @@ -87,6 +95,67 @@ pub(crate) fn data(app: &VectorcraftApp, effect: Option<&str>, params: &Map bool { + self.source == active_drawing(app) + } + + fn check_source(&self, app: &VectorcraftApp) -> Result<(), String> { + let active = active_drawing(app); + if active == self.source { + Ok(()) + } else if active.map(|(id, _)| id) == self.source.map(|(id, _)| id) { + Err(tl!("The document was reverted. Reopen this dialog to continue.").into()) + } else { + Err(tl!("Return to the original drawing to apply the effect").into()) + } + } + + fn owns_preview(&self, app: &VectorcraftApp) -> bool { + self.is_current_drawing(app) + && self.preview_owner.as_ref().is_some_and(|owner| { + app.session.active().and_then(|doc| doc.interaction.as_ref()).is_some_and(|interaction| { + owner.selection.upgrade().is_some_and(|selection| Arc::ptr_eq(&selection, &interaction.selection)) + && owner.command == interaction.preview + }) + }) + } + + fn cancel_preview(&mut self, app: &mut VectorcraftApp) { + let owned = self.owns_preview(app); + let preview = std::mem::take(&mut self.preview); + self.preview_owner = None; + if owned { + preview.cancel(app); + } + } + + fn ready_to_edit(&mut self, app: &mut VectorcraftApp) -> Result { + if self.owns_preview(app) { + return Ok(true); + } + self.preview = LivePreview::default(); + self.preview_owner = None; + if app.session.in_interaction() { + app.keep_typing()?; + } + Ok(!app.session.in_interaction()) + } + + fn run_preview(&mut self, app: &mut VectorcraftApp, cmd: &str, params: &Value) -> Option> { + match self.ready_to_edit(app) { + Ok(true) => {} + Ok(false) => return None, + Err(why) => return Some(Err(why)), + } + let verdict = self.preview.run(app, true, &self.label, cmd, params)?.map(|_| ()); + self.preview_owner = app + .session + .active() + .and_then(|doc| doc.interaction.as_ref()) + .map(|interaction| PreviewOwner { selection: Arc::downgrade(&interaction.selection), command: interaction.preview.clone() }); + Some(verdict) + } + /// The command OK runs, and the params it takes. fn command(&self, params: &Map) -> (&'static str, Value) { super::effect::command_for(&self.effect, self.item.as_ref(), self.index, &self.edit_target, self.aligned, params.clone(), None) @@ -105,6 +174,10 @@ impl Session { } } +fn active_drawing(app: &VectorcraftApp) -> Option<(u64, u64)> { + app.session.active().map(|doc| (doc.uid, doc.reverts)) +} + /// Opens the dialog for the record `effect::open` resolved: `effect`, `item`, `index`, `aligned`, `editTarget` and the /// `params` to start from. pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result { @@ -112,6 +185,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result let info = vectorcraft_effects::effect_info(&effect).ok_or_else(|| format!("unknown effect `{effect}`"))?; let label = info.label.trim_end_matches('…').to_owned(); let params = p.get("params").and_then(Value::as_object).cloned().or_else(|| info.defaults.as_object().cloned()).unwrap_or_default(); + let source = active_drawing(app); let shared = Arc::new(RwLock::new(data(app, Some(&effect), ¶ms))); let mut fields = fields_of(&revolve::params(&read(&shared), &DialogFields::new(), Place::Dialog), ¶ms); fields.set("__effect", effect.clone()); @@ -146,13 +220,15 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result None => dialog, } }); - if let Some(old) = app.three_d_dialog.take() { - old.preview.cancel(app); - } - let options = HeldOptions { cancel: Some(Box::new(cancel)), ..HeldOptions::default() }; + let cancelled = Arc::clone(&shared); + let options = HeldOptions { cancel: Some(Box::new(move |app| cancel(app, &cancelled))), ..HeldOptions::default() }; let id = open_held_with(app, dialog, ok, options).ok_or("no window")?; + if let Some(mut old) = app.three_d_dialog.take() { + old.cancel_preview(app); + } app.three_d_dialog = Some(Session { id, + source, effect, label, item: p.get("item").cloned(), @@ -160,6 +236,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result edit_target: p.get("editTarget").cloned().unwrap_or(Value::Null), aligned: p.get("aligned").and_then(Value::as_bool) == Some(true), preview: LivePreview::default(), + preview_owner: None, tried: None, data: shared, }); @@ -169,6 +246,13 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result /// OK: the preview becomes one undo step. A refusal keeps the dialog, and the session, open. fn ok(app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { let mut s = app.three_d_dialog.take().ok_or_else(|| "the 3D dialog is gone".to_string())?; + let ready = s + .check_source(app) + .and_then(|()| if s.ready_to_edit(app)? { Ok(()) } else { Err(tl!("Finish the current edit before applying the effect").into()) }); + if let Err(why) = ready { + app.three_d_dialog = Some(s); + return Err(why); + } let (cmd, p, _) = s.request(&answer.fields); match std::mem::take(&mut s.preview).commit(app, cmd, p.clone()) { Ok(_) => { @@ -179,6 +263,7 @@ fn ok(app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { Ok(()) } Err(e) => { + s.preview_owner = None; app.three_d_dialog = Some(s); Err(e) } @@ -186,9 +271,11 @@ fn ok(app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> { } /// Cancel: the preview rolls back. -fn cancel(app: &mut VectorcraftApp) { - if let Some(s) = app.three_d_dialog.take() { - s.preview.cancel(app); +fn cancel(app: &mut VectorcraftApp, opening: &Arc>) { + if app.three_d_dialog.as_ref().is_some_and(|s| Arc::ptr_eq(opening, &s.data)) + && let Some(mut s) = app.three_d_dialog.take() + { + s.cancel_preview(app); } } @@ -197,10 +284,15 @@ fn dialog_of(app: &VectorcraftApp, id: DialogId, f: impl FnOnce(&mut HostedPa } fn peek(app: &VectorcraftApp, f: impl FnOnce(&HostedParamDialog) -> R) -> Option { - let id = app.three_d_dialog.as_ref()?.id; + let id = app.three_d_dialog.as_ref().filter(|s| s.is_current_drawing(app))?.id; app.dialogs()?.with(|h| h.get_by_id::(id).map(f)) } +/// Whether the active canvas should give its selection marks to the 3D dialog. +pub(crate) fn editing_current_drawing(app: &VectorcraftApp) -> bool { + app.three_d_dialog.as_ref().is_some_and(|s| s.is_current_drawing(app)) +} + /// Gives the gizmo and the outline the open dialog; `None` when there is none. pub(crate) fn with_fields(app: &mut VectorcraftApp, f: impl FnOnce(&mut HostedParamDialog) -> R) -> Option { let id = app.three_d_dialog.as_ref()?.id; @@ -265,6 +357,7 @@ fn surfaces(app: &mut VectorcraftApp, s: &Session, fields: &DialogFields, params /// refusal standing until the values change. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut s) = app.three_d_dialog.take() else { return }; + let current = s.is_current_drawing(app); // A dialog that closed is finished by the held drain (OK or Cancel), which owns the session's end. let Some((fields, previewing)) = dialog_of(app, s.id, |d| { match d.take_action().as_deref() { @@ -278,32 +371,213 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { return; }; let (cmd, p, params) = s.request(&fields); - let mut fresh = data(app, Some(&s.effect), ¶ms); + // Map Art keeps its read-only surface list current. While away, editable document data + // such as symbol names and artwork drop ownership still belongs to the opening drawing. + let mut fresh = if current { data(app, Some(&s.effect), ¶ms) } else { read(&s.data).clone() }; fresh.surfaces = surfaces(app, &s, &fields, ¶ms); *s.data.write().unwrap_or_else(PoisonError::into_inner) = fresh; - let mut verdict = s.preview.run(app, previewing, &s.label, cmd, &p).map(|r| r.map(|_| ())); - if previewing { + if !current { s.tried = None; - } else if app.session.in_interaction() && s.tried.as_ref() != Some(&p) { - // Changed values end the refusal of the values before them; they are tried once the other interaction ends. - verdict = Some(Ok(())); - } else if s.tried.as_ref() != Some(&p) { - // Waits for another interaction to end: trying inside it would replace its preview and cancel it. A failure - // to begin leaves no interaction: the try then reports it. - let _ = app.begin_interaction(&s.label); - verdict = Some(app.session.preview(cmd, &p).map(|_| ()).map_err(|e| match e { - EngineError::BadParams { msg, .. } => msg, - other => other.to_string(), - })); - // Only a try: without an interaction there is nothing to roll back. - let _ = app.session.cancel_interaction(); - s.tried = Some(p); + app.three_d_dialog = Some(s); + return; } + let verdict = if previewing { + s.tried = None; + s.run_preview(app, cmd, &p) + } else { + s.cancel_preview(app); + if s.tried.as_ref() == Some(&p) { + None + } else if app.session.in_interaction() { + // Clear the old refusal now and try again once the other interaction ends. + Some(Ok(())) + } else { + let tested = try_values(app, &s.label, cmd, &p); + s.tried = Some(p); + Some(tested) + } + }; if let Some(v) = verdict { dialog_of(app, s.id, |d| d.refuse(v.err().map(Label::from))); } app.three_d_dialog = Some(s); } +/// With Preview off, try changed values as a temporary interaction to expose engine refusals. +fn try_values(app: &mut VectorcraftApp, label: &str, cmd: &str, params: &Value) -> Result<(), String> { + app.begin_interaction(label)?; + let verdict = app.session.preview(cmd, params).map(|_| ()).map_err(|error| match error { + EngineError::BadParams { msg, .. } => msg, + other => other.to_string(), + }); + let _ = app.session.cancel_interaction(); + verdict +} + #[cfg(test)] pub(crate) mod tests_support; + +#[cfg(test)] +mod drawing_tests { + use craft::ui::dialog::StackDialog as _; + use serde_json::json; + use vectorcraft_doc::NodeId; + use vectorcraft_effects::EXTRUDE; + + use super::*; + + fn drawing() -> (VectorcraftApp, u64) { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let node = rectangle(&mut app, 10); + (app, node) + } + + fn rectangle(app: &mut VectorcraftApp, x: u32) -> u64 { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap() + } + + fn second_drawing(app: &mut VectorcraftApp) -> u64 { + app.run("file.new", json!({"width": 220, "height": 220})).unwrap(); + rectangle(app, 80) + } + + fn open_effect(app: &mut VectorcraftApp, preview: bool) { + app.run("effect.dialog", json!({"effect": EXTRUDE})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + with_fields(app, |dialog| dialog.set_json_field(&ctx, "preview", json!(preview))).unwrap().unwrap(); + } + + fn applied(app: &VectorcraftApp, node: u64) -> Vec { + app.session.active().unwrap().doc.node(NodeId(node)).unwrap().appearance.effects.iter().map(|effect| effect.id.clone()).collect() + } + + fn frame(app: &mut VectorcraftApp) { + let ctx = app.ui_ctx.clone().unwrap(); + super::super::host::pump(app, &ctx); + } + + fn hold_ok(app: &VectorcraftApp) { + let ctx = app.ui_ctx.clone().unwrap(); + let id = app.three_d_dialog.as_ref().unwrap().id; + assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id))); + } + + #[test] + fn three_d_ownership_preview_resumes_only_in_the_opening_drawing() { + let (mut app, original) = drawing(); + open_effect(&mut app, true); + let first = app.session.active().unwrap().uid; + frame(&mut app); + assert_eq!(applied(&app, original), [EXTRUDE]); + let other = second_drawing(&mut app); + frame(&mut app); + assert!(applied(&app, other).is_empty(), "3D preview reached the other drawing"); + assert!(!app.session.in_interaction()); + assert!(!gizmo_shown(&app)); + assert!(!crate::canvas::revolve_editing(&app)); + assert_eq!(read(&app.three_d_dialog.as_ref().unwrap().data).document_uid, Some(first)); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app); + assert_eq!(applied(&app, original), [EXTRUDE]); + assert!(gizmo_shown(&app)); + assert!(crate::canvas::revolve_editing(&app)); + } + + #[test] + fn three_d_ownership_ok_refuses_the_other_drawing_and_can_retry() { + let (mut app, original) = drawing(); + open_effect(&mut app, false); + hold_ok(&app); + let other = second_drawing(&mut app); + let history = app.session.active().unwrap().history.undo.len(); + frame(&mut app); + assert!(applied(&app, other).is_empty(), "3D OK reached the other drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history); + app.run("document.activate", json!({"index": 0})).unwrap(); + let history = app.session.active().unwrap().history.undo.len(); + hold_ok(&app); + frame(&mut app); + assert_eq!(applied(&app, original), [EXTRUDE]); + assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1); + } + + #[test] + fn three_d_ownership_cancel_leaves_the_other_drawings_preview_running() { + let (mut app, _) = drawing(); + open_effect(&mut app, true); + frame(&mut app); + second_drawing(&mut app); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let ctx = app.ui_ctx.clone().unwrap(); + let id = app.three_d_dialog.as_ref().unwrap().id; + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id))); + frame(&mut app); + assert!(app.session.in_interaction(), "3D Cancel ended the other drawing's edit"); + assert!(app.session.active().unwrap().doc == before); + } + + #[test] + fn three_d_ownership_preview_off_preserves_another_drawings_interaction() { + let (mut app, _) = drawing(); + open_effect(&mut app, true); + frame(&mut app); + let other = second_drawing(&mut app); + app.session.begin_interaction("Other drawing's edit").unwrap(); + app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let ctx = app.ui_ctx.clone().unwrap(); + with_fields(&mut app, |dialog| dialog.set_json_field(&ctx, "preview", json!(false))).unwrap().unwrap(); + frame(&mut app); + assert!(app.session.in_interaction()); + assert!(app.session.active().unwrap().doc == before); + assert!(applied(&app, other).is_empty()); + } + + #[test] + fn three_d_ownership_replacement_keeps_its_own_preview() { + let (mut app, original) = drawing(); + open_effect(&mut app, true); + frame(&mut app); + app.run("effect.dialog", json!({"effect": vectorcraft_effects::REVOLVE})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + with_fields(&mut app, |dialog| dialog.set_json_field(&ctx, "preview", json!(true))).unwrap().unwrap(); + frame(&mut app); + assert!(app.three_d_dialog.is_some(), "a replaced 3D dialog's Cancel removed the new opening"); + assert_eq!(applied(&app, original), [vectorcraft_effects::REVOLVE]); + hold_ok(&app); + frame(&mut app); + assert_eq!(applied(&app, original), [vectorcraft_effects::REVOLVE]); + } + + #[test] + fn three_d_ownership_ok_refuses_the_reloaded_drawing() { + let (mut app, original) = drawing(); + 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("three-d-opening-revert"); + let path = folder.join("drawing.vectorcraft"); + app.run("file.saveAs", json!({"path": path})).unwrap(); + rectangle(&mut app, 80); + app.run("select.set", json!({"ids": [original]})).unwrap(); + let source = app.session.active().unwrap(); + let (uid, generation) = (source.uid, source.reverts); + open_effect(&mut app, false); + hold_ok(&app); + 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]})).unwrap(); + let history = app.session.active().unwrap().history.undo.len(); + frame(&mut app); + assert!(applied(&app, original).is_empty(), "3D OK reached the reloaded drawing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history); + open_effect(&mut app, false); + hold_ok(&app); + frame(&mut app); + assert_eq!(applied(&app, original), [EXTRUDE]); + } +} 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