From 46d30a132ec6f604061d6898f81781d5b7558e25 Mon Sep 17 00:00:00 2001 From: el-j Date: Sun, 8 Nov 2026 01:29:30 +0100 Subject: [PATCH 001/193] Fix #4479: duplicate and Alt-drag copy artwork larger than artboard --- crates/doc/src/document_guides.rs | 72 +++++++++++++++++ crates/doc/src/tests.rs | 114 +++++++++++++++++++++++++++ crates/engine/src/cmd/panelcmds.rs | 22 +++--- crates/engine/src/tests/panelcmds.rs | 32 ++++++++ 4 files changed, 231 insertions(+), 9 deletions(-) diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index f4a037f365..100f6595d6 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -45,6 +45,30 @@ 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. + 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 mut best: Option<(usize, f64)> = None; + for (i, a) in self.artboards.iter().enumerate() { + let r = a.rect; + 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 { + let area = (inter_x1 - inter_x0) * (inter_y1 - inter_y0); + if area > 1e-9 && best.is_none_or(|(_, max_area)| area > max_area + 1e-9) { + best = Some((i, area)); + } + } + } + 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 › @@ -77,6 +101,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 4b75b01497..ee03511c3b 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -127,6 +127,120 @@ 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 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(&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, + }); + // 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, + }); + + // 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); +} + /// 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/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 6eeafd7c32..553a2cdf95 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, point_indices, 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)} a copy of each artboard, the copies placed together right of the last artboard as they lay, 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)} a copy of each artboard, the copies placed together right of the last artboard as they lay, 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")?; @@ -264,16 +265,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/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 0f95fc2f6f..abb4c28f8c 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -421,6 +421,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] From 41f878e8484c566d4950a3600711f6ef237b5a0b Mon Sep 17 00:00:00 2001 From: FredApps Date: Tue, 10 Nov 2026 17:21:19 +0100 Subject: [PATCH 002/193] #4479: a straight line hanging over an artboard is copied with it artboard_for_bounds compared overlap areas, and a horizontal or vertical line has none, so a line whose center is outside every artboard belonged to none and Duplicate/Copy Artboard left it behind, while a rectangle of any thickness in the same place was copied. For bounds with no width or no height, the overlap is now the length of the line on the artboard (CodeRabbit's zero-width/zero-height finding). --- crates/doc/src/document_guides.rs | 25 ++++++++++++++++--------- crates/doc/src/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index f0ea467cad..a92d6e1975 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -47,23 +47,30 @@ impl Document { /// 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 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 { - let area = (inter_x1 - inter_x0) * (inter_y1 - inter_y0); - if area > 1e-9 && best.is_none_or(|(_, max_area)| area > max_area + 1e-9) { - best = Some((i, area)); - } + 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) diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index ee03511c3b..64ccd4ec21 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -150,6 +150,11 @@ fn art_for_artboard_copy_takes_artwork_larger_than_artboard_or_with_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())) @@ -169,6 +174,7 @@ fn art_for_artboard_copy_takes_artwork_larger_than_artboard_or_with_bleed() { 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: @@ -239,6 +245,20 @@ fn artboard_for_bounds_edge_cases_and_tie_breaks() { // 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 From 56972deedacf6cf3bcdf5b7639f75fa9a54ed985 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 01:48:53 -0800 Subject: [PATCH 003/193] Add a color-mode menu to the gradient stop editor --- crates/ui-egui/src/dialogs/gradient_stop.rs | 11 +- crates/ui-egui/src/panels/color.rs | 29 +- .../tests/gradient_stop_color_mode_menu.rs | 444 ++++++++++++++++++ docs/gaps.md | 5 +- docs/roadmap.md | 5 +- docs/target-app-parity.md | 6 +- docs/ui-parity.md | 4 +- 7 files changed, 490 insertions(+), 14 deletions(-) create mode 100644 crates/ui-egui/tests/gradient_stop_color_mode_menu.rs diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 63dcfa916b..07004c6202 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -102,6 +102,7 @@ fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let swatches = d.str("tab") == "swatches"; let mut tab = None; let mut eyedropper = false; + let mut mode_menu_pointer = false; let resp = egui::Area::new(area) .order(egui::Order::Foreground) .fixed_pos(pos) @@ -121,6 +122,9 @@ fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { { eyedropper = true; } + if !swatches { + mode_menu_pointer = crate::panels::color::mode_button(app, ui); + } }); ui.add_space(6.0); if swatches { @@ -163,7 +167,12 @@ fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } // The click that opened the popover (the Gradient panel's colour chip) or the double-click // (a stop's chip) lands outside it: only a later click elsewhere closes it (#577). - if frame > opened && resp.clicked_elsewhere() && !ctx.input(|i| i.pointer.button_double_clicked(egui::PointerButton::Primary)) { + // The mode dropdown is a child of this popover, even where it extends beyond its rectangle. + if frame > opened + && !mode_menu_pointer + && resp.clicked_elsewhere() + && !ctx.input(|i| i.pointer.button_double_clicked(egui::PointerButton::Primary)) + { app.ui.dialog = None; } } diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index b156185ff3..d30b8e4ab2 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -881,6 +881,27 @@ pub(crate) fn show_sized(app: &mut VectorcraftApp, ui: &mut Ui, height: f32) { } } +/// The Color panel's mode choices, also used by the gradient stop editor. +fn mode_items(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target) { + // Tint mode checks no colour mode: picking one makes the tint a process colour. + let cur = shown_mode(app, tgt.color().as_ref()); + for m in Mode::ALL { + if menu_item(ui, tl!(m.label()), true, m == cur && tgt.tint().is_none()) { + set_mode(app, tgt, m); + } + } +} + +/// A compact mode chooser. Reports pointer ownership of its dropdown so an enclosing popover +/// does not mistake a click on one of its rows for a click elsewhere. +pub(crate) fn mode_button(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { + let tgt = target(app, ui); + let mode = shown_mode(app, tgt.color().as_ref()); + let label = if tgt.tint().is_some() { tl!("Tint") } else { tl!(mode.label()) }; + let (_, menu) = egui::containers::menu::MenuButton::from_button(egui::Button::new(label).small()).ui(ui, |ui| mode_items(app, ui, &tgt)); + menu.is_some_and(|m| m.response.container_contains_pointer()) +} + pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let hidden = app.ui.color_hide_options; if menu_item(ui, if hidden { tl!("Show Options") } else { tl!("Hide Options") }, true, false) { @@ -893,13 +914,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { ui.separator(); let tgt = target(app, ui); let color = tgt.color(); - // Tint mode checks no colour mode: picking one makes the tint a process colour. - let cur = shown_mode(app, color.as_ref()); - for m in Mode::ALL { - if menu_item(ui, tl!(m.label()), true, m == cur && tgt.tint().is_none()) { - set_mode(app, &tgt, m); - } - } + mode_items(app, ui, &tgt); ui.separator(); let enabled = color.is_some() || super::active_mixed(app, ui.ctx()); for (label, invert) in [(tl!("Invert"), true), (tl!("Complement"), false)] { diff --git a/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs b/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs new file mode 100644 index 0000000000..3bb31a263d --- /dev/null +++ b/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs @@ -0,0 +1,444 @@ +//! The stop/point popover uses the Color panel's real mode chooser. +// Integration tests may unwrap and panic (AGENTS.md, Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::{Mutex, MutexGuard}; + +use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, Shape, pos2, vec2}; +use serde_json::{Value, json}; +use vectorcraft_color::{GradientPaint, Paint, cms}; +use vectorcraft_engine::Session; +use vectorcraft_ui_egui::{VectorcraftApp, i18n, panels::color::Mode, theme}; + +static UI_STATE: Mutex<()> = Mutex::new(()); +const MODES: [&str; 5] = ["Grayscale", "RGB", "HSB", "CMYK", "Web Safe RGB"]; +type FrameObserver = Box; + +struct GlobalState { + language: i18n::Lang, + colors: cms::ColorSettings, + _lock: MutexGuard<'static, ()>, +} + +impl GlobalState { + fn new() -> Self { + let lock = UI_STATE.lock().unwrap_or_else(|e| e.into_inner()); + let language = i18n::current(); + let colors = cms::active_settings(); + i18n::set_current(i18n::Lang::EN); + cms::set_active(&cms::ColorSettings { rgb: cms::SRGB.into(), ..Default::default() }).unwrap(); + Self { language, colors, _lock: lock } + } +} + +impl Drop for GlobalState { + fn drop(&mut self) { + cms::set_active(&self.colors).unwrap(); + i18n::set_current(self.language); + } +} + +fn key(key: Key, pressed: bool) -> Event { + Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: Modifiers::NONE } +} + +fn visit_shapes(shape: &Shape, clip: Rect, visit: &mut impl FnMut(&Shape, Rect)) { + if let Shape::Vec(shapes) = shape { + for shape in shapes { + visit_shapes(shape, clip, visit); + } + } else { + visit(shape, clip); + } +} + +struct Scene { + app: VectorcraftApp, + ctx: egui::Context, + last_output: egui::FullOutput, + // Optional test-frame observation consumes initial texture uploads before they are cleared. + on_frame: Option, + size: egui::Vec2, + time: f64, + freeform: bool, + buttons: Vec<(String, Rect)>, +} + +impl Scene { + /// No UI frames: an observer can attach before the first font upload. + fn new(size: egui::Vec2, freeform: bool) -> Self { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("app.language", json!({"lang": "en"})).unwrap(); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 120, "height": 100})).unwrap(); + app.run( + "paint.setFill", + json!({"keepModel": true, "gradient": { + "kind": if freeform { "freeform" } else { "linear" }, + "stops": [{"offset": 0, "color": "#2468ac"}, {"offset": 1, "color": "#e09020"}] + }}), + ) + .unwrap(); + app.run("paint.setStroke", json!({"none": true, "focus": false})).unwrap(); + assert!(app.session.fill_active, "removing the stroke must retain the intended gradient fill proxy"); + assert!(matches!(app.session.proxy_paints().0, Paint::Gradient(_)), "the actual active fill, not fallback markers, is a gradient"); + app.select_tool("directSelection"); + if freeform { + app.run("paint.freeform.selectPoint", json!({"index": 0})).unwrap(); + } + app.run("window.panel", json!({"panel": "gradient"})).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + egui_extras::install_image_loaders(&ctx); + ctx.enable_accesskit(); + Self { app, ctx, last_output: Default::default(), on_frame: None, size, time: 0.0, freeform, buttons: vec![] } + } + + fn frame(&mut self, events: Vec) { + self.time += 1.0 / 60.0; + // The normal host tick selects the App's language before painting, too. + i18n::set_current(self.app.ui_language()); + let mut raw = RawInput { + events, + time: Some(self.time), + focused: true, + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, self.size)), + ..Default::default() + }; + self.app.raw_input_hook(&self.ctx, &mut raw); + let mut output = self.ctx.run_ui(raw, |ui| self.app.ui(ui)); + self.buttons.clear(); + let update = output.platform_output.accesskit_update.as_ref().expect("AccessKit enabled"); + for (_, node) in &update.nodes { + if let Some((label, bounds)) = node.label().zip(node.bounds()) { + self.buttons + .push((label.to_owned(), Rect::from_min_max(pos2(bounds.x0 as f32, bounds.y0 as f32), pos2(bounds.x1 as f32, bounds.y1 as f32)))); + } + } + if let Some(observer) = &mut self.on_frame { + observer(&self.ctx, &output); + } + output.textures_delta.clear(); + self.last_output = output; + } + + fn idle(&mut self, count: usize) { + for _ in 0..count { + self.frame(vec![]); + } + } + + fn click_with(&mut self, point: Pos2, modifiers: Modifiers) { + self.frame(vec![ + Event::ModifiersChanged(modifiers), + Event::PointerMoved(point), + Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: true, modifiers }, + ]); + self.frame(vec![Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: false, modifiers }]); + self.frame(vec![Event::ModifiersChanged(Modifiers::NONE)]); + } + + fn click(&mut self, point: Pos2) { + self.click_with(point, Modifiers::NONE); + } + + fn escape(&mut self) { + self.frame(vec![key(Key::Escape, true)]); + self.frame(vec![key(Key::Escape, false)]); + self.idle(2); + } + + fn popover(&self) -> Rect { + self.ctx.memory(|m| m.area_rect(egui::Id::unique("gradient-stop-popover"))).expect("actual painted popover area") + } + + fn assert_editor(&self) { + assert_eq!(self.app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("gradientStop")); + } + + fn painted(&self, mut visitor: impl FnMut(&Shape, Rect)) { + for clipped in &self.last_output.shapes { + visit_shapes(&clipped.shape, clipped.clip_rect, &mut visitor); + } + } + + fn open_stop(&mut self) { + self.idle(8); + if self.freeform { + // The real Color: chip in freeform_section is the 18-point square next to its label. + let mut labels = vec![]; + let mut chips = vec![]; + self.painted(|shape, clip| match shape { + Shape::Text(text) if text.galley.text() == "Color:" => { + labels.push(text.galley.rect.translate(text.pos.to_vec2())); + } + Shape::Rect(rect) + if (rect.rect.width() - 18.0).abs() < 0.01 && (rect.rect.height() - 18.0).abs() < 0.01 && clip.contains(rect.rect.center()) => + { + chips.push(rect.rect) + } + _ => {} + }); + chips.retain(|chip| { + labels.iter().any(|label| { + chip.left() >= label.right() && chip.left() - label.right() < 20.0 && (chip.center().y - label.center().y).abs() < 10.0 + }) + }); + chips.dedup(); + assert_eq!(chips.len(), 1, "actual freeform Color chip, not a fabricated dialog: {chips:?}"); + self.click(chips[0].center()); + } else { + let mut markers = vec![]; + self.painted(|shape, clip| { + if let Shape::Path(path) = shape + && path.closed + && path.points.len() == 5 + { + let rect = Rect::from_points(&path.points); + if (rect.width() - 12.0).abs() < 0.01 + && (rect.height() - 15.0).abs() < 0.01 + && path.points[0].distance(pos2(rect.center().x, rect.top())) < 0.01 + && clip.contains(rect.center()) + { + markers.push(rect.center()); + } + } + }); + assert_eq!(markers.len(), 2, "real two-stop Gradient panel: {markers:?}"); + markers.sort_by(|a, b| a.x.total_cmp(&b.x)); + self.click(markers[0]); + self.click(markers[0]); + } + self.idle(3); + self.assert_editor(); + if self.freeform { + assert_eq!(self.app.session.selected_freeform_point(), Some(0)); + } else { + assert_eq!(self.app.session.selected_stop(), Some(0)); + } + } + + fn button(&self, label: &str) -> Rect { + let popover = self.popover(); + let matches: Vec<_> = self + .buttons + .iter() + .filter(|(text, rect)| text == label && rect.is_positive() && popover.contains(rect.center())) + .map(|(_, rect)| *rect) + .collect(); + assert_eq!(matches.len(), 1, "one actual accessible {label:?} button; labels: {:?}", self.buttons); + matches[0] + } + + fn open_mode(&mut self, label: &str) { + self.assert_editor(); + let button = self.button(label); + assert!(self.popover().contains(button.center())); + self.click(button.center()); + self.idle(3); + assert!(egui::Popup::is_any_open(&self.ctx), "actual child menu opens"); + self.assert_editor(); + } + + fn mode_rows(&self) -> Vec<(String, bool, Rect)> { + let mut rows: Vec<_> = self + .buttons + .iter() + .filter_map(|(text, rect)| { + let (label, checked) = if let Some(label) = text.strip_prefix("✓ ") { (label, true) } else { (text.strip_prefix(" ")?, false) }; + MODES.contains(&label).then_some((label.to_owned(), checked, *rect)) + }) + .collect(); + rows.sort_by(|a, b| a.2.top().total_cmp(&b.2.top())); + rows + } + + fn assert_modes(&self, current: Option<&str>) { + let rows = self.mode_rows(); + assert_eq!(rows.iter().map(|(label, _, _)| label.as_str()).collect::>(), MODES); + for (label, checked, rect) in rows { + assert_eq!(checked, current == Some(label.as_str()), "current row: {label}"); + assert!(Rect::from_min_size(Pos2::ZERO, self.size).contains(rect.center())); + } + } + + fn choose_mode(&mut self, label: &str) -> Rect { + let rows = self.mode_rows(); + let rect = rows.iter().find(|(text, _, _)| text == label).expect("actual offered mode").2; + self.click(rect.center()); + self.idle(3); + assert!(!egui::Popup::is_any_open(&self.ctx), "picking a mode closes only its dropdown"); + self.assert_editor(); + rect + } + + fn gradient(&self) -> GradientPaint { + let Paint::Gradient(g) = self.app.session.proxy_paints().0 else { panic!("gradient fill") }; + *g + } + + fn snapshot(&self) -> Value { + let state = self.app.session.active().unwrap(); + json!({"doc": state.doc.as_ref(), "selection": state.selection, + "undo": state.history.undo.iter().map(|e| json!({"label":e.label,"doc":e.doc.as_ref(),"selection":e.selection.as_ref()})).collect::>(), + "redo": state.history.redo.iter().map(|e| json!({"label":e.label,"doc":e.doc.as_ref(),"selection":e.selection.as_ref()})).collect::>(), + "step": state.history.step(), "stop": self.app.session.selected_stop(), "point": self.app.session.selected_freeform_point()}) + } + + fn geometry(&self) -> Value { + let state = self.app.session.active().unwrap(); + json!(state.selection.objects.iter().map(|id| &state.doc.node(*id).unwrap().kind).collect::>()) + } + + fn spectrum(&self) -> Rect { + let popover = self.popover(); + let mut found = vec![]; + self.painted(|shape, clip| { + if let Shape::Mesh(mesh) = shape + && mesh.vertices.len() == 73 * 13 + && mesh.indices.len() == 72 * 12 * 6 + { + let points: Vec<_> = mesh.vertices.iter().map(|v| v.pos).collect(); + let rect = Rect::from_points(&points); + if popover.contains(rect.center()) && clip.contains(rect.center()) { + found.push(rect); + } + } + }); + assert_eq!(found.len(), 1, "actual 72-by-12 Color spectrum mesh"); + found[0] + } +} + +#[test] +fn gradient_stop_mode_baseline_shift_and_menu_are_display_only() { + let _globals = GlobalState::new(); + let mut scene = Scene::new(vec2(960.0, 720.0), false); + scene.open_stop(); + let before = scene.snapshot(); + let original = scene.gradient(); + assert_eq!(original.gradient.stops[0].color.model(), cms::Model::Rgb); + // A legitimate existing control must succeed before the intended old-source failure. + scene.click_with(scene.spectrum().center(), Modifiers::SHIFT); + scene.idle(3); + assert_eq!(scene.app.ui.color_mode, Some(Mode::Hsb)); + assert_eq!(scene.snapshot(), before, "Shift cycling changes display, not art/history"); + scene.open_mode("HSB"); // Baseline: this actual chooser is absent on ed6f. + scene.assert_modes(Some("HSB")); + assert_eq!(scene.snapshot(), before, "opening the menu is not an edit"); + scene.escape(); + assert!(!egui::Popup::is_any_open(&scene.ctx)); + scene.assert_editor(); + assert_eq!(scene.snapshot(), before); + scene.open_mode("HSB"); + scene.choose_mode("RGB"); + scene.open_mode("RGB"); + scene.assert_modes(Some("RGB")); + scene.choose_mode("HSB"); + assert_eq!(scene.gradient(), original); + assert_eq!(scene.snapshot(), before, "RGB/HSB preserve native RGB and one-stop selection"); + scene.escape(); + assert!(scene.app.ui.dialog.is_none(), "after dropdown dismissal the next Escape closes the editor"); + assert_eq!(scene.snapshot(), before); +} + +#[test] +fn gradient_stop_mode_converts_only_selected_stop_and_unlinks_tint_with_one_undo() { + let _globals = GlobalState::new(); + for tint in [false, true] { + let mut scene = Scene::new(vec2(960.0, 720.0), false); + if tint { + scene.app.run("swatch.new", json!({"name":"Ink","color":{"c":0,"m":1,"y":0,"k":0},"spot":true})).unwrap(); + scene + .app + .run( + "paint.setFill", + json!({"gradient":{"stops":[ + {"offset":0,"swatch":"Ink","tint":50}, {"offset":1,"color":"#e09020"} + ]}}), + ) + .unwrap(); + } + scene.open_stop(); + let before = scene.snapshot(); + let original = scene.gradient(); + let geometry = scene.geometry(); + let undo = scene.app.session.active().unwrap().history.undo.len(); + if tint { + assert_eq!(original.gradient.stops[0].swatch.as_deref(), Some("Ink")); + assert!((original.gradient.stops[0].tint - 0.5).abs() < 1e-6); + } + scene.open_mode(if tint { "Tint" } else { "RGB" }); + scene.assert_modes(if tint { None } else { Some("RGB") }); + scene.choose_mode("CMYK"); + let converted = scene.gradient(); + assert_eq!(converted.gradient.stops[0].color.model(), cms::Model::Cmyk); + assert!(converted.gradient.stops[0].swatch.is_none(), "process mode unlinks a tint"); + let mut expected = original.clone(); + expected.gradient.stops[0].color = converted.gradient.stops[0].color; + expected.gradient.stops[0].swatch = None; + expected.gradient.stops[0].tint = 1.0; + expected.gradient.stops[0].plates = None; + assert_eq!(converted, expected, "other stops, placement and gradient settings are untouched"); + assert_eq!(scene.geometry(), geometry); + assert_eq!(scene.app.session.active().unwrap().history.undo.len(), undo + 1); + scene.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(serde_json::to_value(scene.app.session.active().unwrap().doc.as_ref()).unwrap(), before["doc"]); + assert_eq!(scene.gradient(), original); + if !tint { + // Hide Options is the existing compact mixer; its child menu can outgrow the editor. + scene.app.run("ui.colorPanel", json!({"options": false})).unwrap(); + scene.idle(3); + scene.open_mode("RGB"); + scene.assert_modes(Some("RGB")); + let row = scene.mode_rows().into_iter().find(|(label, _, _)| label == "Web Safe RGB").unwrap().2; + let parent = scene.popover(); + assert!(!parent.contains(row.center()), "compact editor must expose a real child row outside itself: parent={parent:?}, row={row:?}"); + scene.choose_mode("Web Safe RGB"); + assert_eq!(scene.app.ui.color_mode, Some(Mode::WebSafe)); + assert_ne!( + scene.gradient().gradient.stops[0].color, + original.gradient.stops[0].color, + "the original non-web-safe RGB stop is actually converted" + ); + assert_eq!(scene.geometry(), geometry); + scene.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(serde_json::to_value(scene.app.session.active().unwrap().doc.as_ref()).unwrap(), before["doc"]); + assert_eq!(scene.gradient(), original, "one Undo restores the pre-conversion paint"); + } + // A real outside click closes both editor and child, without another edit. + scene.idle(3); + // Undo restores art, while the chosen display mode remains a UI preference. + scene.open_mode(if tint { "Tint" } else { "Web Safe RGB" }); + let closed_boundary = scene.snapshot(); + let outside = pos2(2.0, scene.size.y - 2.0); + assert!(!scene.popover().contains(outside)); + assert!(scene.mode_rows().iter().all(|(_, _, r)| !r.contains(outside))); + scene.click(outside); + scene.idle(3); + assert!(scene.app.ui.dialog.is_none()); + assert!(!egui::Popup::is_any_open(&scene.ctx)); + assert_eq!(scene.snapshot(), closed_boundary); + } +} + +#[test] +fn gradient_stop_mode_freeform_point_uses_the_same_real_menu() { + let _globals = GlobalState::new(); + let mut scene = Scene::new(vec2(960.0, 720.0), true); + scene.open_stop(); + let before = scene.snapshot(); + let original = scene.gradient(); + scene.open_mode("RGB"); + scene.assert_modes(Some("RGB")); + scene.choose_mode("HSB"); + assert_eq!(scene.app.ui.color_mode, Some(Mode::Hsb)); + assert_eq!(scene.gradient(), original, "display-only point editing keeps every freeform point"); + assert_eq!(scene.snapshot(), before); + scene.open_mode("HSB"); + scene.escape(); + scene.assert_editor(); + scene.escape(); + assert!(scene.app.ui.dialog.is_none()); + assert_eq!(scene.snapshot(), before); +} diff --git a/docs/gaps.md b/docs/gaps.md index eda7bb21dd..1d921be864 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Gradient stop editor: its Color tab offers the five Color panel modes (#7918); scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -118,6 +118,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall ## G1 Interaction fidelity +- **Done (#7918):** The gradient stop editor’s Color tab offers the Color panel’s five color modes without Shift-clicking the spectrum, sharing its saved mode, conversions and tint unlinking. Mode selection keeps the editor open, with the menu taking Escape first. Evidence: `crates/ui-egui/tests/gradient_stop_color_mode_menu.rs`. Broader G1 scope and estimates unchanged. + macOS cursor delivery (#2292) is narrowed to a native host adapter using the existing artwork and aligned 1×/2× representations. Headless tests cover visible fallbacks, preparation and ownership; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain open validation work (see [hardware parity](hardware-parity.md)). This does not close the interaction-fidelity gap or change its score/estimate. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. @@ -895,6 +897,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale, RGB, HSB, CMYK and Web Safe RGB, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. | | 2026-11-14 | minor | Type: Middle Eastern & South Asian and Standard composers per paragraph (#4935): Paragraph panel menu, paragraph styles, `text.setFormat {composer}` and the native file; the Standard composers set Indic, Arabic and Hebrew type glyph by glyph. `.ai`, EPS and PDF files carry no composer. Scores and estimates unchanged. | | 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. | | 2026-11-12 | minor | 3D: The seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins (the seams of Revolve and of colored lights, and 3D (Classic) Wireframe edges, were already round): no thorns on edge-on facets, and facets with no neighbour now have rounded convex corners ([three-d.md](three-d.md#seams)). Scores and estimates unchanged. | diff --git a/docs/roadmap.md b/docs/roadmap.md index fae091f647..fccdaba309 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (#8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Gradient stop editor: its Color tab offers the five Color panel modes (#7918); scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -159,7 +159,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M0 | Skeleton + vertical slice | ✅ done | — | | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | -| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | +| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops (the stop editor offers the five Color panel modes, #7918), freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | @@ -208,6 +208,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale, RGB, HSB, CMYK and Web Safe RGB, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. | | 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) keeps the line cap, line join and miter limit of the graphics state it is stroked with, as paths do, instead of butt caps, miter joins and a miter limit of 10; a glyph filled and then stroked otherwise than the run its fill joined comes in as a run of its own, so the glyphs before it keep their stroke (#7741; `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`). Scores and estimates unchanged. | | 2026-11-15 | minor | M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimates unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..74c1b43a81 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (#8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Gradient stop editor: its Color tab offers the five Color panel modes (#7918); scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -249,7 +249,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); gradient stop editor color-mode menu (#7918) | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | @@ -1698,6 +1698,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Hue Clockwise and Hue Counterclockwise, VectorCraft's own gradient methods, in the Gradient panel's Method menu and on `paint.editGradient` and `paint.setFill` (`method`: `hue-clockwise`, `hue-counterclockwise`): a linear, radial, conic or diamond gradient's colors mix around the hue wheel, with hue, saturation and brightness each changing evenly from one stop to the next and the hue angle keeping one direction, as the fixed-direction rules of [CSS Color 4](https://www.w3.org/TR/css-color-4/#hue-interpolation) do: falling with Hue Clockwise (red, magenta, blue), which is clockwise on the color wheels, and rising with Hue Counterclockwise (red, yellow, green). Hues less than half a color level apart count as one hue, so a color and its tint do not turn the wheel. A gray stop takes the hue of the stop it mixes with, and black its saturation too. The canvas and raster exports draw it through stops on that curve, within half a color level; Reverse Gradient turns the method the other way with the stops, so the ramp keeps its colors. SVG and PDF write it as an RGB image, EPS as a shading in process colors, and a legacy `.ai` file and the `.ai` editing data with the colors between its stops as stops of their own, with a warning. - Gradient spread, VectorCraft's own setting: Pad, Repeat or Reflect, with a Repeats count of 1 to 100, in the Gradient panel and on `paint.editGradient` and `paint.setFill`; Repeat and Reflect run a linear, radial, conic or diamond gradient's stops that many times along the vector and on past its ends, the Gradient tool marks where the runs meet, and SVG writes and reads `spreadMethod`, CSS writes repeating gradients, PDF writes a conic's sweep shading over one run and the other kinds with their stops repeated across the shape, as EPS, legacy `.ai` and the `.ai` editing data do. - The stop popover a double-click on a stop opens (the Gradient tool's annotator or the Gradient panel) has an eyedropper beside its Color and Swatches tabs: it closes the popover and samples the next colour clicked on the art into the stop, as the Gradient panel's eyedropper does (#4681). + - The stop editor’s Color tab has a compact menu named for the current mode: Grayscale, RGB, HSB, CMYK or Web Safe RGB (#7918). It shares the Color panel’s saved mode and color conversion, including making a linked tint a process color. A mode choice keeps the editor open; Escape closes the menu before the editor, and a click outside both closes the editor. The same controls edit a freeform point. Evidence: `crates/ui-egui/tests/gradient_stop_color_mode_menu.rs`. Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. @@ -2651,6 +2652,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale, RGB, HSB, CMYK and Web Safe RGB, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. | | 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | | 2026-11-14 | minor | Paragraph composers (#4935): `text.setFormat {composer}` and paragraph styles take `singleLine` and `everyLine` (the Middle Eastern & South Asian composers, what all type used and the default) and `standardSingleLine` and `standardEveryLine`, which break lines the same way and set a complex script (Indic, Arabic, Hebrew) glyph by glyph as the font maps its characters, with no conjuncts, reordering, marks placed or joining forms. The choice is per paragraph, saved in the native file only when it is not Every-line, and not written to `.ai`, EPS or PDF files, whose composer setting this app has no recorded format for. Scores and estimates unchanged. Tests `tests::composers`. | | 2026-11-14 | minor | G5: Weather Icons joins Basic Shapes, UI Frames, Map Markers, Inventory Icons and Skill Icons as a sixth built-in symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow; original procedural vector symbols generated in code, no default 9-slice); area score and estimate unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8e06948b33..cac615d413 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (#8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Gradient stop editor: its Color tab offers the five Color panel modes (#7918); scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -458,6 +458,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Gradient panel: Method, Classic or Perceptual (30.0) | done | Method menu under the Stroke buttons for linear and radial gradients (`paint.editGradient` `method`); [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/control-perceptual-interpolation-in-gradients.html); `panels::gradient` test | | Gradient panel: Presets (30.0) | done | Presets menu by library (theme) plus Saved: applies a preset to the gradient behind the active proxy, keeping its placement, one undo step; panel menu Save Gradient Preset…, Delete Gradient Preset, Hide/Show Presets (`gradient.presets.*`); `panels::gradient` tests | | Gradient panel: delete a stop | done | Delete Stop at the right end of the ramp deletes the selected stop, and a stop dragged down off the ramp is deleted on release, never below two stops, one undo step each; [Gradient panel options](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/gradient-tool-and-panel.html); `panels::gradient` test | +| Gradient stop editor: Color mode menu | done | Compact current-mode menu offers Grayscale, RGB, HSB, CMYK and Web Safe RGB, sharing the Color panel mode and conversion; a choice keeps the editor open, Escape closes the menu first, and clicking outside both dismisses the editor (#7918); `crates/ui-egui/tests/gradient_stop_color_mode_menu.rs` | | Gradient tool: the annotator's end handle changes the length; Alt-drag changes the length and angle together | done | A plain drag keeps the end on the bar's line, at least 10 px from the start (VectorCraft's own minimum); Alt-drag moves it freely, Shift with Alt at 45° steps; [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html); `xform::gradient` tests | | Workspaces (save, reset, switch); each remembers the layout changes made in it across switches and restarts until Reset | done | `UiState::workspace_changes` | | Opening a file: after 0.4 s a progress window with the file name, a moving bar (reading counts no steps), how many more files wait, Cancel (Esc: the file doesn't open) and Continue in Background; never over another dialog or progress window | done | #5930; `opening::show`, `file.cancelOpen`, `file.openInBackground`. Save, Place and Close still show only the status bar's spinner (Place and Save run off the UI thread; Close is immediate) | @@ -554,6 +555,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale, RGB, HSB, CMYK and Web Safe RGB, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. | | 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | | 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. | | 2026-11-12 | minor | Numeric fields: a focus click released more than 1 pt from its press keeps the caret; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326). Scores and estimates unchanged. | From 31206e50e85087759f8938497aded060fea118bb Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 19 Nov 2026 17:07:47 +0000 Subject: [PATCH 004/193] 8068: keep canvas navigation during sampler-owned primary input Deliver independent navigation once through the existing modal and hover rules, preserving sampler ownership and mapped-handle gates. Add a real-frame owned-release zoom regression with ordinary, release-only, dock and accepted-color controls. --- crates/ui-egui/src/canvas.rs | 35 +++++-- crates/ui-egui/src/canvas/input.rs | 24 ++++- crates/ui-egui/src/panels/three_d.rs | 5 + .../tests/image_trace_ignore_sampler.rs | 99 +++++++++++++++++++ docs/target-app-parity.md | 5 +- docs/ui-parity.md | 5 +- 6 files changed, 159 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e4d21df36f..8f116d8db6 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -735,6 +735,8 @@ fn input_after_sampler_refresh(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::R let (consumed, ordinary_pressed) = begin_ignore_sampler_pointer(ui, resp.id, cancelled); if !consumed && (ordinary_pressed || !cancelled || !ui.input(|i| i.pointer.any_pressed())) { canvas_input(app, ui, resp, rect); + } else if consumed { + canvas_navigation(app, ui, resp, rect); } end_ignore_sampler_pointer(ui, resp.id); } @@ -753,17 +755,34 @@ pub(crate) fn canvas_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo // open, has the press: the drag moves the graphic, not the object. } else { handle_input(app, ui, resp, rect); - // `hover_doc` is the document point under the pointer in the view `handle_input` left. The - // wheel, a pan, a Rotate View drag, the Zoom tool and a Presentation Mode click move the view - // there. A dialog, floating panel or menu over the canvas hides it (Object Highlighting - // showed through them: #4518), unless a drag that began on the canvas goes on there. - let moved = Xf::at(rect, app.view().unwrap_or(&View::default()), app.canvas_ui_zoom); - let dragging = ui.data(|d| d.get_temp::(drag_id()).is_some()); - app.hover_doc = - ui.input(|i| i.pointer.hover_pos()).filter(|p| rect.contains(*p) && (dragging || drag::on_canvas(ui, resp, *p))).map(|p| moved.to_doc(p)); + update_hover_doc(app, ui, resp, rect); } } +/// A consumed sampler primary frame may still carry independent view navigation. +fn canvas_navigation(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect) { + if app.ui.dialog.as_ref().is_some_and(crate::dialogs::revolve_gizmo::active) + || (resp.context_menu_opened() && resp.hovered() && ui.input(|i| i.pointer.any_pressed())) + || crate::panels::three_d::graphic_handle_drag_active(ui.ctx()) + { + // Keep the existing gesture gates without closing a popup or dispatching a handle press. + return; + } + input::handle_navigation(app, ui, resp, rect); + update_hover_doc(app, ui, resp, rect); +} + +fn update_hover_doc(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect) { + // `hover_doc` is the document point under the pointer in the view canvas input left. The + // wheel, a pan, a Rotate View drag, the Zoom tool and a Presentation Mode click move the view + // there. A dialog, floating panel or menu over the canvas hides it (Object Highlighting + // showed through them: #4518), unless a drag that began on the canvas goes on there. + let moved = Xf::at(rect, app.view().unwrap_or(&View::default()), app.canvas_ui_zoom); + let dragging = ui.data(|d| d.get_temp::(drag_id()).is_some()); + app.hover_doc = + ui.input(|i| i.pointer.hover_pos()).filter(|p| rect.contains(*p) && (dragging || drag::on_canvas(ui, resp, *p))).map(|p| moved.to_doc(p)); +} + /// The pointer over the canvas: the view tools' cursors, else the tool's own. fn canvas_cursor(app: &mut VectorcraftApp, ui: &Ui, view_info: vectorcraft_engine::ViewInfo, hover_still: bool) { if opening::long_operation_busy(app) { diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index a6a0509de5..71b7f06c03 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -10,8 +10,17 @@ use super::view::{ }; use super::{Color32, Drag, Mods, Point, PointerEvent, PointerKind, Pos2, Shape, Stroke, Ui, VectorcraftApp, View, Xf, json}; -/// Dispatch canvas pointer, keyboard and drop events through the active document view. -pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect) { +struct NavigationInput { + cancelled: bool, + modal: bool, + pointer: egui::PointerState, + m: egui::Modifiers, + space: bool, + hover: Option, +} + +/// The shared view-navigation phase, before any canvas primary input is delivered. +fn navigation_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect) -> NavigationInput { if let Some(feed) = app.services.stylus.as_ref() { feed.bind_repaint(ui.ctx()); } @@ -19,6 +28,17 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo let cancelled = crate::dialogs::refresh_brush_key_color(app); let modal = crate::panel_docking::modal_open(app, ui.ctx()); let (pointer, m, space, hover) = wheel_view(app, ui, resp, rect, modal); + NavigationInput { cancelled, modal, pointer, m, space, hover } +} + +/// Navigate while the sampler owns primary input, without delivering that input to another tool. +pub(super) fn handle_navigation(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect) { + let _ = navigation_input(app, ui, resp, rect); +} + +/// Dispatch canvas pointer, keyboard and drop events through the active document view. +pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect) { + let NavigationInput { cancelled, modal, pointer, m, space, hover } = navigation_input(app, ui, resp, rect); if (cancelled && pointer.primary_pressed()) || crate::dialogs::brush_key_color_input(app, ui, resp, rect) { return; } diff --git a/crates/ui-egui/src/panels/three_d.rs b/crates/ui-egui/src/panels/three_d.rs index 61993a8581..211cc9528b 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -460,6 +460,11 @@ struct HandleDrag { owner: (u64, Vec), } +/// Whether a mapped graphic already owns a drag, without delivering or changing its input. +pub(crate) fn graphic_handle_drag_active(ctx: &egui::Context) -> bool { + ctx.data(|data| data.get_temp::(handle_drag_id()).is_some()) +} + /// The active document's uid and its selected objects' ids: what a handle drag moves graphics for. fn drag_owner(app: &VectorcraftApp) -> (u64, Vec) { app.session.active().map(|st| (st.uid, st.selection.objects.iter().map(|id| id.0).collect())).unwrap_or_default() diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs index fec0805f58..ec913f3d4d 100644 --- a/crates/ui-egui/tests/image_trace_ignore_sampler.rs +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -1443,3 +1443,102 @@ fn review_597048_a_later_drag_release_does_not_replace_a_qualified_double_click( assert_eq!(ctx.input(|i| i.pointer.interact_pos()), Some(away)); assert_eq!(app.session.active().unwrap().isolation, Some(group), "the qualified Double belongs to the earlier group release"); } + +fn review_9086_camera(app: &VectorcraftApp) -> (Point, f64, f64) { + let v = app.view().unwrap(); + (v.center, v.zoom, v.rotation) +} + +fn review_9086_assert_camera(app: &VectorcraftApp, expected: (Point, f64, f64), label: &str) { + let actual = review_9086_camera(app); + assert!(actual.0.distance(expected.0) < 1e-6, "{label}: center {:?}, expected {:?}", actual.0, expected.0); + assert!((actual.1 - expected.1).abs() < 1e-9, "{label}: zoom {}, expected {}", actual.1, expected.1); + assert!((actual.2 - expected.2).abs() < 1e-9, "{label}: navigation does not rotate the view"); +} + +fn review_9086_valid_down(app: &mut VectorcraftApp, ctx: &egui::Context, hit: Point) -> (Pos2, Pos2, f64, f64) { + let expected = review_gesture_state(app); + let camera = review_9086_camera(app); + let target = selected(app).id; + click_control(app, ctx, SAMPLE_TIP); + assert_eq!(app.session.tool_id(), "eyedropper", "CONTROL: the real panel button arms the sampler"); + let binding = app.ui.trace_ignore_sampler.as_ref().expect("CONTROL: a real panel binding exists"); + let state = app.session.active().unwrap(); + assert_eq!((binding.doc, binding.target, binding.revision), (state.uid, target, state.revision)); + assert_eq!(binding.back, "selection"); + assert_eq!(app.session.tool_options()["imageTraceIgnoreColor"], json!({"doc":state.uid,"target":target.0,"revision":state.revision})); + // click_control leaves the pointer over this actual docked panel button. + let dock = ctx.input(|i| i.pointer.hover_pos()).expect("CONTROL: the real dock button has a pointer position"); + assert!(!app.canvas_rect.unwrap().contains(dock), "CONTROL: this point is on the dock, outside the canvas"); + let at = review_gesture_screen(app, ctx, hit); + let (start, step) = review_gesture_times(ctx); + review_gesture_press(app, ctx, at, start); + assert_eq!(app.session.tool_id(), "selection", "CONTROL: opaque sampler Down completes and returns its bound tool"); + assert!(app.ui.trace_ignore_sampler.is_none(), "CONTROL: the successful Down clears the sampler binding"); + assert!(ctx.input(|i| i.pointer.primary_down()), "CONTROL: this is the real still-owned press before Up"); + assert_eq!(review_gesture_state(app), expected, "CONTROL: Preview-off sampling changes no art, selection, revision, history, paint or isolation"); + review_9086_assert_camera(app, camera, "CONTROL: sampling itself preserves the displayed camera"); + (at, dock, start, step) +} + +#[test] +fn review_4629359086_owned_sampler_up_preserves_trackpad_zoom() { + const FACTOR: f32 = 1.25; + // A real ordinary unarmed frame proves that Zoom reaches the canvas exactly once. + let (mut ordinary, ordinary_ctx, _, hit, _) = review_gesture_completion_fixture(); + assert!(ordinary.ui.trace_ignore_sampler.is_none()); + assert_eq!(ordinary.session.tool_id(), "selection"); + let at = review_gesture_screen(&ordinary, &ordinary_ctx, hit); + let initial = review_9086_camera(&ordinary); + let state = review_gesture_state(&ordinary); + let pinned = canvas::Xf::at(ordinary.canvas_rect.unwrap(), ordinary.view().unwrap(), ordinary_ctx.zoom_factor()).to_doc(at); + let (start, _) = review_gesture_times(&ordinary_ctx); + frame_at(&mut ordinary, &ordinary_ctx, start, vec![Event::PointerMoved(at), Event::Zoom(FACTOR)]); + let zoomed = review_9086_camera(&ordinary); + assert!((zoomed.1 / initial.1 - f64::from(FACTOR)).abs() < 1e-7, "CONTROL: ordinary trackpad Zoom applies exactly one factor"); + let still_pinned = canvas::Xf::at(ordinary.canvas_rect.unwrap(), ordinary.view().unwrap(), ordinary_ctx.zoom_factor()).to_doc(at); + assert!(still_pinned.distance(pinned) < 1e-6, "CONTROL: ordinary zoom stays pinned to the real canvas pointer"); + assert_eq!(review_gesture_state(&ordinary), state, "CONTROL: ordinary navigation changes no non-view state"); + + // Release-only comes first and proves the real sample was accepted, not merely cancelled. + let (mut release_only, release_ctx, _, hit, _) = review_gesture_completion_fixture(); + let (at, _, start, step) = review_9086_valid_down(&mut release_only, &release_ctx, hit); + let state = review_gesture_state(&release_only); + review_gesture_release(&mut release_only, &release_ctx, at, start + step); + review_9086_assert_camera(&release_only, initial, "CONTROL: sampler Up without navigation leaves the view unchanged"); + assert_eq!(review_gesture_state(&release_only), state); + assert_eq!(release_only.session.tool_id(), "selection"); + click_control(&mut release_only, &release_ctx, "Trace"); + assert_eq!(settings(&release_only)["params"]["ignoreColor"], "#255395", "CONTROL: the real valid Down accepted its opaque source color"); + assert_eq!(settings(&release_only)["params"]["ignoreWhite"], true); + + // The same owned Up over the real dock must not admit navigation from the panel. + let (mut docked, dock_ctx, _, hit, _) = review_gesture_completion_fixture(); + let (_, dock, start, step) = review_9086_valid_down(&mut docked, &dock_ctx, hit); + let state = review_gesture_state(&docked); + frame_at(&mut docked, &dock_ctx, start + step, vec![Event::PointerMoved(dock), review_596866_button(dock, false), Event::Zoom(FACTOR)]); + review_9086_assert_camera(&docked, initial, "CONTROL: dock hover cannot start canvas navigation"); + assert_eq!(review_gesture_state(&docked), state); + assert_eq!(docked.session.tool_id(), "selection"); + assert!(!dock_ctx.input(|i| i.pointer.primary_down())); + click_control(&mut docked, &dock_ctx, "Trace"); + assert_eq!(settings(&docked)["params"]["ignoreColor"], "#255395", "CONTROL: the rejected dock zoom does not cancel the valid sample"); + + let (mut app, ctx, _, hit, _) = review_gesture_completion_fixture(); + let (at, _, start, step) = review_9086_valid_down(&mut app, &ctx, hit); + review_9086_assert_camera(&app, initial, "CONTROL: the regression starts from the ordinary camera"); + let state = review_gesture_state(&app); + frame_at(&mut app, &ctx, start + step, vec![review_596866_button(at, false), Event::Zoom(FACTOR)]); + assert!(!ctx.input(|i| i.pointer.primary_down())); + assert_eq!(app.session.tool_id(), "selection"); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert_eq!(review_gesture_state(&app), state, "the owned Up cannot select, isolate, paint or change document/history state"); + review_9086_assert_camera(&app, zoomed, "REGRESSION: sampler-owned Up still admits the same trackpad zoom as an ordinary frame"); + frame_at(&mut app, &ctx, start + 2.0 * step, vec![]); + review_9086_assert_camera(&app, zoomed, "later idle cannot replay navigation or revive primary ownership"); + assert_eq!(review_gesture_state(&app), state); + assert_eq!(app.session.tool_id(), "selection"); + click_control(&mut app, &ctx, "Trace"); + assert_eq!(settings(&app)["params"]["ignoreColor"], "#255395", "the navigation fix retains the actual accepted sample"); + assert_eq!(settings(&app)["params"]["ignoreWhite"], true); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a8e5bf9537..3fa45b012c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Image Trace Ignore Color: sampler-owned primary input retains independently admitted wheel and pinch navigation (#8068); scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -1817,7 +1817,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Pattern editing mode and opacity mask editing exclude each other, by a rule of VectorCraft itself: in pattern editing mode a click or Alt-click on the mask thumbnail does not edit the mask, and Make Mask is off for one object; while a mask is edited, Object › Pattern › Make and Edit Pattern are off. Disable, Enable, Unlink and Link Opacity Mask and Opacity Mask Options (`transparency.setOpacityMask`) record no undo step when every mask they act on already has the flags they set. - **Linked opacity masks follow geometry effects, the Free Transform distort and envelopes:** when masked art moves, a linked opacity mask moves with it and an unlinked one stays in place ([Transparency and blending modes](https://helpx.adobe.com/illustrator/using/transparency-blending-modes-alt.html)). Applying that rule when art is reshaped, as below, is VectorCraft's own rule. When a group's or layer's geometry effects (Transform, Free Distort, the Warp effects and the others) reshape its members, the linked masks of the paths, compound paths and groups inside it take the same effects, nested and inverted masks included, with the type and live objects in a mask's art outlined first. Each Transform copy of a masked path carries its own mask. An image or symbol instance that a group's Transform effect moves carries its linked mask too, and with Scale Strokes & Effects on, the mask's strokes scale as a path's mask's do. With Transform Objects off, a member's mask takes the effect's stroke and pattern changes as the member does. The linked masks in the art of a symbol instance in perspective are projected with that art. A Free Transform tool distort drag (`object.distort`) warps a linked mask with its object, in a group too, in the same undo step. An envelope bends only a linked mask. When a mask can't take an effect as the art it masks does (a path in either would pass the geometry budget, the mask would get fewer Transform copies, the mask's art holds an image or symbol instance and the effect is not Transform, a Warp effect would bend an image that has a linked mask, or the effect is a live-effect plug-in that paints its pieces), the art and its masks keep their shape under that effect. The copies of a masked path count the art of its mask against the budget. Existing documents draw differently in four cases: a geometry effect on a group whose members have linked masks moves those masks; an envelope no longer bends an unlinked mask; art with linked masks keeps its shape under an effect that its masks can't take; and a Transform effect can make fewer copies of a masked path near the budget (effects `group::tests::a_groups_geometry_effects_reshape_a_members_linked_mask_with_it`, `group::tests::a_groups_geometry_effects_reshape_nested_and_inverted_masks`, `group::tests::a_compound_paths_and_a_layers_members_masks_take_the_effects`, `group::tests::a_groups_effects_reshape_a_live_object_in_a_members_mask`, `group::tests::each_transform_copy_of_a_masked_member_carries_its_mask`, `group::tests::a_groups_transform_moves_an_image_members_linked_mask`, `group::tests::a_groups_transform_moves_a_symbol_instance_members_linked_mask`, `group::tests::a_groups_transform_moves_a_linked_mask_whose_art_is_an_image`, `group::tests::art_whose_mask_holds_an_image_keeps_its_shape_under_a_warp`, `group::tests::art_with_a_masked_image_keeps_its_shape_under_a_warp`, `group::tests::a_transform_with_scale_strokes_scales_the_masks_of_images_and_paths_alike`, `group::tests::a_transform_of_strokes_only_scales_a_members_mask_strokes`, `group::tests::perspective_projects_the_masks_in_a_symbols_art`, `group::tests::a_mask_whose_art_passes_the_budget_stays_whole`, `group::tests::art_whose_mask_would_take_fewer_copies_keeps_its_shape`, `group::tests::transform_copies_count_the_art_of_their_masks`, `group::tests::the_mask_of_a_masks_art_copied_whole_counts_against_the_budget`; engine `xform::distort_command_warps_a_linked_opacity_mask_with_its_object`, `xform::distort_command_warps_the_linked_mask_of_a_path_in_a_group`, `envelope_distort::an_envelope_bends_a_linked_opacity_mask_and_leaves_an_unlinked_one`, `plugins::a_painted_group_effect_leaves_art_with_a_linked_mask_as_it_is`). Scores and hours unchanged. -- **Image Trace, Ignore Color canvas sampling (#8068):** the panel eyedropper reads the selected placed image or the retained original image of a live trace without changing the canvas View. Outside and transparent pixels leave it armed; a valid pixel restores the previous tool. The manual picker, Preview-off drafts and Preview-on single-step retrace remain available. `tests/image_trace_ignore_sampler.rs` covers original-pixel sampling, the unchanged CPU canvas, missed-pick continuation, Preview/Undo, Escape, explicit tool choices, stale document/target/revision presses and cancellation while Selection borrows the Eyedropper; the restored lender is no longer armed. This is UI interaction evidence, not algorithm parity; scores, gaps and hours unchanged. +- **Image Trace, Ignore Color canvas sampling (#8068):** the panel eyedropper reads the selected placed image or the retained original image of a live trace without changing the canvas View. Outside and transparent pixels leave it armed; a valid pixel restores the previous tool. Sampler-owned primary input still allows otherwise-admitted wheel and pinch navigation; its release does not reach the restored tool. The manual picker, Preview-off drafts and Preview-on single-step retrace remain available. `tests/image_trace_ignore_sampler.rs` covers original-pixel sampling, the unchanged CPU canvas, missed-pick continuation, Preview/Undo, Escape, explicit tool choices, stale document/target/revision presses and cancellation while Selection borrows the Eyedropper; the restored lender is no longer armed. This is UI interaction evidence, not algorithm parity; scores, gaps and hours unchanged. - **Image Trace, thin closed outlines:** generated `fit::snap_area_tests` verify nonzero interiors after straightening, opposite closed-boundary winding and Noise controls; see [quality notes](image-trace-quality.md#thin-closed-outlines-with-snap-curves-to-lines). Scores and hours unchanged; open-piece fitting is unchanged. - **Image Trace, curve fitting tolerance:** the outline fitter keeps cutting a run while a point stays farther than the tolerance from its curve, so a run of fewer than six points or one cut 14 times no longer keeps a piece over the tolerance. Pieces already within the tolerance do not change, and noisy art can get more anchors. Tests: `logo::bezier::tests`, `logo::outline::tests`. Scores and hours unchanged. - **Image Trace, gray photos:** Color and Grayscale smooth a gray photo within its tones before choosing its colors, as they do a color photo. A picture with at least 95% of its opaque pixels within 8 levels across their channels counts as continuous tone when 8 colors leave an error of more than 6 levels and more than 0.065 of the error of one color, instead of 0.1, unless 16 colors leave at most a tenth of the error of 8 (VectorCraft's own values). That exception keeps gray flat art of up to 16 clean levels on its old route; anti-aliased or noisy gray flat art can now count as continuous tone too. Most gray photos the change reaches, and very noisy gray scans of flat art, trace with fewer specks and fewer staircase edges. Some 16 Colors and High Fidelity Photo palettes of gray photos grow toward the requested count, with more anchors and regions. Some gray illustrations and sketches get more anchors and staircase edges at 16 Colors and High Fidelity Photo, and some 6 Colors traces get more staircase edges. Tests: `tests::a_gray_photo_is_continuous_tone_as_its_color_original_is`, `tests::a_gray_photo_is_smoothed_before_it_is_traced`. Scores and hours unchanged. @@ -3103,6 +3103,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | Image Trace Ignore Color: a sampler-owned primary press or release retains otherwise-admitted wheel and pinch navigation without delivering the release to the restored tool; real-frame source regression and controls added (#8068). Scores, gaps and hours unchanged. | | 2026-11-19 | minor | Artboard tool: Shift held once a move or an Alt-drag copy of an artboard is under way keeps it to the level, upright or 45° line from General › Constrain Angle, and snaps slide it along that line; a Shift-press still draws an artboard inside another or marquee-selects (#2497), #8580. Scores and estimates unchanged. | | 2026-11-18 | minor | Layers panel: context menu on guide rows (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show) with one-step undo; regression tests in `crates/ui-egui/src/panels/layers/tests.rs`; scores and estimates unchanged. | | 2026-11-18 | minor | Type advanced: Retype phase 1 (`type.retype`, #4934), exact matches of available fonts become point text again; evidence added; near matches, the ranked font list and images remain; score and hours unchanged | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1418ed4cf8..1125957fa2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Image Trace Ignore Color: sampler-owned primary input retains independently admitted wheel and pinch navigation (#8068); scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -464,7 +464,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Window › Toolbars › Manage Toolbars… (also in the All Tools drawer's menu): the dialog lists the toolbars made with New Toolbar; a new name typed for the selected one renames it, + copies it (none selected: a blank toolbar) and the trash can deletes it; the changes stay in the workspace | done | #1759 in part; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete` | | Quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the editable controls | done | Per the public documentation, choosing a preset traces the image with it straight away, and the panel is opened with the Image Trace button in the Control panel or in Properties' Image Trace section (). The controls show Threshold, Paths, Corners and Noise with Advanced open; `panels/image_trace.rs` headless tests (`a_quick_trace_leaves_the_panel_as_it_was`, `sketch_quick_trace_reveals_all_adjustments_and_keeps_the_source` for the button's route). No algorithm parity claim. | | Image Trace panel: holding the eye button next to View down shows the selected Image Trace objects' source image on the canvas | done | Per the public documentation, the control next to View is pressed and held to compare the trace result with the source image (). On release the objects show their View again; the document, its View and the undo history are unchanged. `RenderOptions::trace_source`; `panels/image_trace.rs` headless test `holding_the_eye_button_shows_the_source_image_until_released`, render test `trace_source_draws_the_source_image_of_the_listed_objects`. The Control bar and Properties have no such button | -| Image Trace panel: Ignore Color has a canvas eyedropper beside its color picker | done | #8068. Samples original pixels of the selected placed image or the retained source of a live trace without changing the displayed canvas View. The existing color picker remains available. Preview off keeps a draft; Preview on retraces a live trace as one undo step. An outside or transparent miss leaves the pick armed; a valid sample or Escape restores the previous tool, and changing the target or explicitly choosing a tool cancels. Paint defaults and selection are retained. `tests/image_trace_ignore_sampler.rs`; no algorithm parity claim. | +| Image Trace panel: Ignore Color has a canvas eyedropper beside its color picker | done | #8068. Samples original pixels of the selected placed image or the retained source of a live trace without changing the displayed canvas View. The existing color picker remains available. Preview off keeps a draft; Preview on retraces a live trace as one undo step. An outside or transparent miss leaves the pick armed; a valid sample or Escape restores the previous tool, and changing the target or explicitly choosing a tool cancels. Paint defaults and selection are retained. Sampler-owned primary input retains otherwise-admitted wheel and pinch navigation without lending its release to the restored tool. `tests/image_trace_ignore_sampler.rs`; no algorithm parity claim. | | Live trace result bounds and selection highlights exclude the retained bitmap; source-image views retain it | done | All TraceView modes and rotated result bounds regression-covered; ordinary hidden group behavior retained | | Image Trace panel: the Preview checkbox before Trace chooses whether a setting change traces the selected Image Trace object again at once | done | Per the public documentation, Preview shows the result of the current settings and Trace traces with them (). Preview is on by default and kept with the UI preferences; Reset to Default leaves it. Off, changes wait in the panel until Trace applies them as one undo step, or until Preview is turned on again. Changes stay with the object they were made for while another object is selected, and come back when it is selected again. `imageTrace.preview {on?}`, `ui.set {imageTracePreview}`; `panels/image_trace.rs` headless tests (`with_preview_off_a_slider_change_waits_for_trace`, `turning_preview_on_traces_the_changes_that_waited`, `preview_turned_on_with_nothing_selected_traces_when_the_object_is_selected_again`, `settings_that_wait_stay_with_their_object`, `settings_that_wait_come_back_when_their_object_is_selected_again`, `settings_that_wait_are_dropped_when_their_object_changed_since`, `preview_is_kept_with_the_preferences_and_reset_to_default_leaves_it`) | | Toolbar without group labels by default, one or two columns; All Tools drawer by flyout group with shortcuts, its menu (Reset, Basic, Advanced) and Show section | done | #1751; a preference brings the labels back; `toolbar.show` sets the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls; Window > Toolbars > Compact Tools adds optional denser spacing for the main Tools panel while retaining the existing default (#7234) | @@ -620,6 +620,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | Image Trace Ignore Color: a sampler-owned primary press or release retains otherwise-admitted wheel and pinch navigation without delivering the release to the restored tool; real-frame source regression and controls added (#8068). Scores, gaps and hours unchanged. | | 2026-11-19 | minor | Artboard tool: Shift held once a move or an Alt-drag copy of an artboard is under way keeps it to the level, upright or 45° line from General › Constrain Angle, and snaps slide it along that line; a Shift-press still draws an artboard inside another or marquee-selects (#2497), #8580. Scores and estimates unchanged. | | 2026-11-19 | minor | Canvas context menu: a right-click on a path, a group of paths or a compound path offers Simplify… between Average… and Smooth…, in the Path menu's order, opening the Simplify slider at the Auto-Simplify level, or the Simplify dialog on its kept settings, as Object › Path › Simplify… does (#8344). Scores and estimates unchanged. | | 2026-11-19 | minor | G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s (part of #5930, `file.cancelPlace`); indeterminate moving bar, Cancel (Esc) leaves the document unmodified without undo steps; scores and estimates unchanged. | From 3b2208497caa8261fc94b63c0cbd58bfc391647e Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 19 Nov 2026 17:42:19 +0000 Subject: [PATCH 005/193] Record the Image Trace navigation follow-up in the roadmap --- docs/roadmap.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index 759baae5bd..286f1ab26e 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Image Trace Ignore Color: releasing a completed pick preserves otherwise allowed wheel/pinch navigation without handing the click to the restored tool (#8068 follow-up); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -188,7 +188,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fourteen generated libraries including Tech Circuit, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | -| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | +| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, sampling itself does not change the canvas View, missed pixels keep the pick armed, releasing a completed pick preserves otherwise allowed wheel/pinch navigation without handing the click to the restored tool, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | | M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | @@ -232,6 +232,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | M12/Image Trace Ignore Color: releasing a completed pick preserves otherwise allowed wheel/pinch navigation without handing the click to the restored tool (#8068 follow-up). Scores, gaps and estimates unchanged. | | 2026-11-18 | minor | M10/G5: Media Controls joins Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons as a seventh built-in symbol library (Play, Pause, Stop, Skip Next, Shuffle, Repeat; original procedural vector symbols generated in code, no default 9-slice); G5 estimate decremented to 2–12 h, milestone estimates unchanged | | 2026-11-18 | minor | M7/G4: Retype phase 1 (#4934): `type.retype` turns outlined text that exactly matches an available font back into point text. Scores and estimates unchanged | | 2026-11-18 | minor | M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538). Scores and estimates unchanged. | From 5027d01fbc6ae08a3b085a6c3a6a9bcf8728b6e1 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 19 Nov 2026 19:19:14 -0800 Subject: [PATCH 006/193] Color conversion: index global swatch bases (#8804) --- ROADMAP.md | 4 +- crates/engine/src/cmd/colormgmt.rs | 28 +++-- crates/engine/src/tests/colormgmt.rs | 171 +++++++++++++++++++++++++++ docs/gaps.md | 4 +- docs/roadmap.md | 5 +- docs/target-app-parity.md | 5 +- 6 files changed, 206 insertions(+), 11 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 90a6100167..0a08f7e0a7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G5: 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); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Color conversion indexes global swatch bases and linked paints (#8804); scores and estimates unchanged; previously: G5: 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); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -124,6 +124,7 @@ 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. @@ -249,6 +250,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-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. | | 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. | diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 1b394fa95c..583fd0b6e9 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/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 3e64f1557d..5de7f585f4 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)]; + 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)]; + 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![] }; + 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/docs/gaps.md b/docs/gaps.md index df988ebe81..236740683e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Color conversion indexes global swatch bases and linked paints (#8804); scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged. @@ -801,6 +801,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G15 Performance budgets and a GPU renderer +- **Color conversion (#8804):** Color conversion (#8804) builds one first-name index for the document's global swatch bases and uses indexed lookups for linked paints. Document Color Mode, new-art colors and text-style conversion keep first-record shadowing, spot handling, tint behavior and missing-link fallback. The base construction changes from quadratic name searches to O(N log N) index work; this is a source-complexity result, not a measured elapsed-time or budget improvement. Command-level semantic controls are in `crates/engine/src/tests/colormgmt.rs`; scores and estimates are unchanged. - **Improved (#6543):** text thread overlays share an index for repeated selection membership checks, keeping the first lookup and selections of one object direct. Four focused controls preserve thread order, links, ports and perspective exclusions. With 512 two-frame threads and 512 unrelated selected paths, @@ -965,6 +966,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | 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-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | | 2026-11-19 | minor | G12: Brushes panel item right-click context menu offering Brush Options…, Duplicate Brush, and Delete Brush (disabled if the last remaining brush); right-clicking an unselected brush selects it first, and right-clicking within a multi-selection preserves it offering Duplicate Brushes / Delete Brushes; headless tests in `crates/ui-egui/src/panels/brushes/tests.rs`; scores and estimates unchanged. | | 2026-11-19 | minor | G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…); right-clicking an unselected link row selects it first, and right-clicking within a multi-selection preserves it; headless tests in `crates/ui-egui/src/panels/tests_links.rs`; scores and estimates unchanged. | diff --git a/docs/roadmap.md b/docs/roadmap.md index a518e3a35a..19f43a3b54 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Color conversion indexes global swatch bases and linked paints (#8804); scores and estimates unchanged; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -26,6 +26,8 @@ ## Feature submission evidence +Color conversion (#8804) builds one first-name index for the document's global swatch bases and uses indexed lookups for linked paints. Document Color Mode, new-art colors and text-style conversion keep first-record shadowing, spot handling, tint behavior and missing-link fallback. The base construction changes from quadratic name searches to O(N log N) index work; this is a source-complexity result, not a measured elapsed-time or budget improvement. Command-level semantic controls are in `crates/engine/src/tests/colormgmt.rs`; scores and estimates are unchanged. + **Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. @@ -235,6 +237,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | 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-19 | minor | M1: Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | M11: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1d981428a..9a0c071bc9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Color conversion indexes global swatch bases and linked paints (#8804); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -30,6 +30,8 @@ ## Feature submission evidence +Color conversion (#8804) builds one first-name index for the document's global swatch bases and uses indexed lookups for linked paints. Document Color Mode, new-art colors and text-style conversion keep first-record shadowing, spot handling, tint behavior and missing-link fallback. The base construction changes from quadratic name searches to O(N log N) index work; this is a source-complexity result, not a measured elapsed-time or budget improvement. Command-level semantic controls are in `crates/engine/src/tests/colormgmt.rs`; scores and estimates are unchanged. + **Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. `window.panel.float` updates an existing native panel window's supplied position and size (#8391). Positions use the main window's content origin. Omitted coordinates and dimensions keep their current native values, including after an OS window move or resize. Evidence: `panel_docking::native_tests::an_explicit_float_command_updates_an_existing_native_windows_geometry` covers panel, group and column commands. Scores and estimates are unchanged. @@ -3144,6 +3146,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 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-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | Guides, grids, smart guides, snapping, rulers: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out their Show/Hide items; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | From a1e0be385771614f0693fe86862d1af37e53c76a Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 19 Nov 2026 19:33:41 -0800 Subject: [PATCH 007/193] Fix color-conversion fixture swatch storage (#8804) --- crates/engine/src/tests/colormgmt.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 5de7f585f4..c5a480323b 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -1200,7 +1200,7 @@ fn document_mode_index_keeps_ineligible_first_name_shadowing() { 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)]; + 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] }); @@ -1234,7 +1234,7 @@ fn document_mode_index_uses_the_first_global_base_across_groups() { 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)]; + 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] }); @@ -1321,7 +1321,7 @@ fn document_mode_index_keeps_registration_and_missing_link_fallbacks() { 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![] }; + 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)); From 5c32aadb801f27c05c1c3792baca31c7f967f546 Mon Sep 17 00:00:00 2001 From: Dmytro Chornyi Date: Fri, 20 Nov 2026 08:46:22 +0100 Subject: [PATCH 008/193] PDF export: the CMYK document warning says whether RGB images are converted (#1242) In a CMYK document exported with No conversion, RGB vector colours are separated into CMYK but placed RGB images are written as RGB. The export warning still said they "are converted to CMYK through the colour settings", so files reached printers with RGB images in them. The warning now counts RGB images by what actually happens to them: converted to CMYK with a CMYK destination (Convert to destination, or PDF/X-1a), else written in RGB, with the settings that write them in CMYK. Grey images stay grey either way and are no longer counted as RGB. RGB colours keep their wording. The written PDF is unchanged. --- crates/pdf/src/export/entry.rs | 49 ++++++++++++++++++---------- crates/pdf/src/export/images.rs | 8 +++-- crates/pdf/src/images.rs | 19 +++++++++-- crates/pdf/src/tests/output.rs | 58 +++++++++++++++++++++++++++++++++ 4 files changed, 112 insertions(+), 22 deletions(-) diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index fcdcd01f63..83ed7e07da 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -369,38 +369,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 3da2079b9b..763a8e2c1b 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -149,8 +149,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 eaff6c781f..7f6b721c7b 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 d9c2fedc1d..42a1dcafaa 100644 --- a/crates/pdf/src/tests/output.rs +++ b/crates/pdf/src/tests/output.rs @@ -705,3 +705,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}"); +} From 0721fa2982d4e63f212dc5cdaa793b52862caaf4 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 03:31:20 -0800 Subject: [PATCH 009/193] Document retained Image Trace sampling navigation in the area row --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f0751fafe3..8f86636ea6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -294,7 +294,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Ignore Color canvas sampling reads the original pixels without changing View, keeps a missed pick armed, and retains the manual picker and Preview controls (#8068; scores, gaps and hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged | +| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Ignore Color canvas sampling reads the original pixels without changing View, keeps a missed pick armed, and retains the manual picker and Preview controls (#8068; scores, gaps and hours unchanged); Ignore Color sampling retains wheel and pinch navigation over the canvas without forwarding its primary-button release to the restored tool (`image_trace_ignore_sampler` navigation regression; scores, gaps and hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | From 7991e55211ed7663308ece0d423e0d01667a8c72 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:28:38 -0800 Subject: [PATCH 010/193] i18n: the message scan reads raw string literals The untranslated-strings scan and the undo step-name check read only "..." literals. A message, a &str constant, a step name or a format! string written as r"..." or r#"..."# was skipped, and a raw string that was read went through escape decoding and ended at its first inner quote. The scan now reads a raw string up to the quote followed by the literal's own number of # and keeps its backslashes, as the Rust Reference defines raw strings (https://doc.rust-lang.org/reference/tokens.html#raw-string-literals). Byte strings and C strings, raw or not, are not read as text. The walkers that find an error helper's argument, a statement's end, a closure's returned values and a format!'s arguments now use the same literal boundaries, so a comma, semicolon, bracket or return inside a raw string or a character literal is no longer read as syntax. No current message or step name is a raw string, so no catalog row changes. --- crates/ui-egui/src/i18n/tests.rs | 322 ++++++++++++++++++++----------- docs/target-app-parity.md | 1 + 2 files changed, 215 insertions(+), 108 deletions(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 25e378a43a..b6200fb66a 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1915,7 +1915,7 @@ fn undo_scan() -> UndoScan { } for t in &files { let named = t.match_indices(NAMED_MARKER).filter_map(|(at, _)| arguments(&t[at + NAMED_MARKER.len()..]).first().copied()); - templates.extend(named.filter_map(|a| a.strip_prefix('"').and_then(string_literal))); + templates.extend(named.filter_map(leading_text)); } } UndoScan { labels: out, templates, formatted } @@ -1998,8 +1998,7 @@ fn quoted_end(text: &str, at: usize) -> Option { } return it.next().filter(|(_, c)| *c == '\'').map(|(n, _)| at + 1 + n + 1); } - let hashes = text[..at].chars().rev().take_while(|c| *c == '#').count(); - if text[..at - hashes].ends_with('r') { + if let Some(hashes) = raw_hashes(text, at) { let close = format!("\"{}", "#".repeat(hashes)); return rest.find(&close).map(|n| at + 1 + n + close.len()); } @@ -2016,6 +2015,46 @@ fn quoted_end(text: &str, at: usize) -> Option { None } +/// The number of `#` around the raw string literal whose opening `"` is at `text[quote]` (`r"…"`, +/// `r#"…"#`, `br#"…"#`); `None` when the literal is not raw. +fn raw_hashes(text: &str, quote: usize) -> Option { + let hashes = quote - text[..quote].trim_end_matches('#').len(); + text[..quote - hashes].ends_with('r').then_some(hashes) +} + +/// The string literal whose opening `"` is at `text[quote]`: where it starts, its prefix (`r`, +/// `r#`, `b`, `br`, `c`, `cr`) included, where it ends, and its text when it is a `&str` literal: +/// a `"…"` literal with its escapes resolved (see [`string_literal`]), or a raw `r"…"` or `r#"…"#` +/// literal as written, backslashes included (https://doc.rust-lang.org/reference/tokens.html#raw-string-literals). +/// A byte string or a C string has no text; `None` when the literal is not closed. +fn literal_at(text: &str, quote: usize) -> Option<(usize, usize, Option)> { + let end = quoted_end(text, quote)?; + let raw = raw_hashes(text, quote); + let mut start = quote - raw.map_or(0, |hashes| hashes + 1); + let not_text = text[..start].ends_with(['b', 'c']) && !text[..start - 1].ends_with(|c: char| c.is_alphanumeric() || c == '_'); + if not_text { + start -= 1; + return Some((start, end, None)); + } + let lit = match raw { + Some(hashes) => Some(text[quote + 1..end - 1 - hashes].to_string()), + None => string_literal(&text[quote + 1..]), + }; + Some((start, end, lit)) +} + +/// The text of the `&str` literal `s` starts with (`"…"`, `r"…"`, `r#"…"#`), as [`literal_at`] +/// reads it; `None` when `s` does not start with one. +fn leading_text(s: &str) -> Option { + let quote = s.find('"')?; + let prefix = &s[..quote]; + let raw_prefix = prefix.strip_prefix('r').is_some_and(|hashes| hashes.chars().all(|c| c == '#')); + if !prefix.is_empty() && !raw_prefix { + return None; + } + literal_at(s, quote)?.2 +} + /// In `s` (the text after an opening bracket), the offset of each top-level `,`, and where the /// list ends: at the bracket that closes it, a top-level `;`, or the end of `s`. fn top_level(s: &str) -> (Vec, usize) { @@ -2140,7 +2179,7 @@ fn label_literals( ) { let mut e = bare(e); if let Some(args) = e.strip_prefix("format!(") { - formatted.extend(args.trim_start().strip_prefix('"').and_then(string_literal)); + formatted.extend(leading_text(args.trim_start())); return; } if let Some(body) = e.strip_prefix('|').and_then(|r| r.find('|').map(|n| &r[n + 1..])) { @@ -2167,19 +2206,24 @@ fn label_literals( } } -/// The string literals in `e` that `keep` accepts, given the text before and after each. +/// The text of each `&str` literal in `e` (`"…"`, `r"…"`, `r#"…"#`, see [`literal_at`]) that `keep` +/// accepts, given the text before the literal and its prefix and the text after it. Byte strings and +/// C strings are not read. fn string_literals(e: &str, keep: impl Fn(&str, &str) -> bool) -> Vec { let mut out = vec![]; let mut i = 0; while let Some(c) = e[i..].chars().next() { - if let Some(end) = (c == '"' || c == '\'').then(|| quoted_end(e, i)).flatten() { - if c == '"' - && let Some(lit) = string_literal(&e[i + 1..]) - && keep(&e[..i], &e[end..]) + if c == '"' + && let Some((start, end, lit)) = literal_at(e, i) + { + if let Some(lit) = lit + && keep(&e[..start], &e[end..]) { out.push(lit); } i = end; + } else if let Some(end) = (c == '\'').then(|| quoted_end(e, i)).flatten() { + i = end; } else { i += c.len_utf8(); } @@ -4702,6 +4746,124 @@ fn message_scan_rejects_invalid_rust_escapes() { assert_eq!(source_messages(code, &[], &Default::default()), ["good value"]); } +/// The undo scan reads a step name or a `format!` template written as a raw string (`r"…"`, +/// `r#"…"#`, `r##"…"##`) as Rust reads it: up to the quote followed by the literal's own number of +/// `#`, with its backslashes kept (https://doc.rust-lang.org/reference/tokens.html#raw-string-literals). +/// `Session::edit_named` templates are read the same way. +#[test] +fn undo_scan_reads_raw_step_names() { + let (mut names, mut formatted) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + for e in [ + r#"r"Move path""#, + r##"r#"Move "named" path"#"##, + r###"r##"Move "#tag" path"##"###, + r#"r"Move\npath""#, + r##"if copy { r#"Copy "it""# } else { "Move it" }"##, + r##"format!(r#"Move "named" {n}"#, n = 2)"##, + ] { + label_literals(e, 0, &[], &mut names, &mut formatted); + } + let want = ["Copy \"it\"", "Move \"#tag\" path", "Move \"named\" path", "Move it", "Move path", "Move\\npath"]; + assert_eq!(names.iter().collect::>(), want); + assert_eq!(formatted.iter().collect::>(), ["Move \"named\" {n}"]); + assert_eq!(leading_text(r##"r#"Move "{0}" layers"#, count)"##).as_deref(), Some("Move \"{0}\" layers")); + assert_eq!(leading_text(r#""Move {0} layers", count)"#).as_deref(), Some("Move {0} layers")); + assert_eq!(leading_text(r#"br"Move", count)"#), None); +} + +/// The message scan reads a raw string where it reads a message: after `Err(`, as an error +/// variant's message and in `#[error(…)]`, as an error helper's argument, as a `&str` constant's +/// value, and as the `format!` string a `.map_err` closure returns. Its quotes and backslashes stay +/// as written, and only the `format!` string's `{e}` is a placeholder. +#[test] +fn message_scan_reads_raw_strings() { + let code = r####" +fn run() -> Result<()> { + let _ = Err(r"the file is missing"); + let _ = Err(r"the C:\temp folder is missing"); + let _ = Error::Manifest(r#"the "named" file is missing"#); + let _ = bad(cmd, r#"the file is missing, {really}"#); + let _ = Err(LOST); + let _ = Err(QUOTED); + load().map_err(|e| format!(r##"the "#tag" file failed: {e}"##))?; + Ok(()) +} +#[derive(Error)] +enum Failure { + #[error(r#"the "named" file is lost: {0}"#)] + Lost(String), +} +"####; + let declared = r##"const LOST: &str = r"the file is lost"; const QUOTED: &'static str = r#"the "named" file is lost"#;"##; + let consts = str_consts(declared); + let want = [("LOST", "the file is lost"), ("QUOTED", "the \"named\" file is lost")]; + assert_eq!(consts.iter().map(|(n, v)| (n.as_str(), v.as_str())).collect::>(), want); + let consts = std::collections::BTreeMap::from_iter(consts.into_iter().map(|(name, value)| (name, vec![value]))); + let found: std::collections::BTreeSet = source_messages(code, &[("bad(", 1)], &consts).into_iter().collect(); + let want = [ + "the \"#tag\" file failed: {e}", + "the \"named\" file is lost", + "the \"named\" file is lost: {0}", + "the \"named\" file is missing", + "the C:\\temp folder is missing", + "the file is lost", + "the file is missing", + "the file is missing, {{really}}", + ]; + assert_eq!(found.iter().collect::>(), want); +} + +/// Byte strings and C strings, raw or not, are not text: the scan reads none of them as a message +/// or a step name. +#[test] +fn message_scan_skips_byte_and_c_strings() { + let e = r##"(b"byte error", br#"byte "error""#, c"C error", cr"C error", "text error")"##; + assert_eq!(string_literals(e, |_, _| true), ["text error"]); + let code = r##"fn run() { let _ = Err(b"byte error"); let _ = Err(br#"byte "error""#); let _ = Err(c"C error"); }"##; + assert!(source_messages(code, &[], &Default::default()).is_empty()); + let (mut names, mut formatted) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + for e in [r#"b"Move""#, r##"br#"Move"#"##, r#"c"Move""#, r#"format!(b"Move {n}")"#] { + label_literals(e, 0, &[], &mut names, &mut formatted); + } + assert!(names.is_empty() && formatted.is_empty(), "{names:?} {formatted:?}"); +} + +/// A comma, bracket, semicolon, quote, `return` or backslash inside a raw string is text, not +/// syntax: an error helper's message is the argument after the raw one, a statement ends at the +/// `;` after a raw string, a closure's raw string holds no `return`, and the raw string is emptied +/// whole before the scan looks for a local's name. +#[test] +fn message_scan_reads_past_raw_strings() { + let code = r###"fn run() { let _ = bad(r#"command ", other"#, r"the second argument is the error"); }"###; + assert_eq!(source_messages(code, &[("bad(", 1)], &Default::default()), ["the second argument is the error"]); + assert_eq!(statement(r##"r#"note "; still text"#; tail"##), r##"r#"note "; still text"#"##); + assert_eq!(statement(r#"(';', ")") ; tail"#), r#"(';', ")") "#); + let code = r###" +fn run() -> Result<()> { + let fail = |e| { let note = r#"note "; still text"#; format!("the file failed: {e}") }; + load().map_err(fail)?; + open().map_err(|e| { + let note = r##"name"; return "fake" {x}"##; + format!("the file could not be opened: {e}") + })?; + Ok(()) +} +"###; + let found: std::collections::BTreeSet = source_messages(code, &[], &Default::default()).into_iter().collect(); + assert_eq!(found.iter().collect::>(), ["the file could not be opened: {e}", "the file failed: {e}"]); + assert_eq!(without_strings(r###"let note = r#"a "used_name" {x}"#; note"###), r##"let note = r#""#; note"##); + assert_eq!(without_strings(r###"x(r#"a\"#, "b\"c", y)"###), r##"x(r#""#, "", y)"##); + assert_eq!(without_strings(r#"f('"', "a")"#), r#"f('"', "")"#); +} + +/// A bracket in a character literal among a `format!`'s arguments does not end them: the scan +/// removes the arguments up to the `format!`'s own closing parenthesis. +#[test] +fn format_args_end_at_the_closing_parenthesis() { + assert_eq!(without_format_args(r#"format!("", ')', x) + why"#), "format!() + why"); + assert_eq!(without_format_args(r#"format!("", f(x)[0]) + why"#), "format!() + why"); +} + /// The scan reads the message of each of the plug-in host's [`ERROR_HELPERS`]: a literal, a /// `format!` string with or without a `&` before it, after the location of `out_err` (a /// `format!` string too), the number and range of `in_range`, the number and location of `unit`, @@ -7060,8 +7222,8 @@ fn scoped_consts<'a>( std::borrow::Cow::Owned(consts) } -/// The `&str` constants `code` declares outside its comments (`const NAME: &str = "…";`), with -/// their text, escapes resolved. +/// The `&str` constants `code` declares outside its comments (`const NAME: &str = "…";`, or a raw +/// `r#"…"#` value), with their text as [`leading_text`] reads it. fn str_consts(code: &str) -> Vec<(String, String)> { let code = &without_comments(code); code.match_indices("const ") @@ -7071,7 +7233,7 @@ fn str_consts(code: &str) -> Vec<(String, String)> { let (name, rest) = rest.split_at(rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_')?); let rest = rest.trim_start().strip_prefix(':')?.trim_start(); let rest = rest.strip_prefix("&'static str").or_else(|| rest.strip_prefix("&str"))?.trim_start(); - let value = string_literal(rest.strip_prefix('=')?.trim_start().strip_prefix('"')?)?; + let value = leading_text(rest.strip_prefix('=')?.trim_start())?; Some((name.to_string(), value)) }) .collect() @@ -7097,7 +7259,7 @@ fn named_const<'a>(rest: &str, consts: &'a std::collections::BTreeMap string_literal(quoted).into_iter().collect(), + let lits = match leading_text(rest) { + Some(lit) => vec![lit], None => named_const(rest, consts).to_vec(), }; for lit in lits { @@ -7164,35 +7326,14 @@ fn source_messages(code: &str, helpers: &[(&str, usize)], consts: &std::collecti } /// The arguments of a call whose opening parenthesis was just read, past the first `n` of them; -/// `None` when `n` is 1 or more and the call has `n` arguments or fewer. +/// `None` when `n` is 1 or more and the call has `n` arguments or fewer. A comma or bracket inside a +/// string literal, raw ones included, or a character literal does not count (see [`top_level`]). fn skip_args(args: &str, n: usize) -> Option<&str> { if n == 0 { return Some(args); } - let (mut left, mut depth, mut chars) = (n, 0usize, args.char_indices()); - while let Some((at, c)) = chars.next() { - match c { - '(' | '[' | '{' => depth += 1, - ')' | ']' | '}' => depth = depth.checked_sub(1)?, - '"' => loop { - match chars.next()?.1 { - '\\' => { - chars.next()?; - } - '"' => break, - _ => {} - } - }, - ',' if depth == 0 => { - left -= 1; - if left == 0 { - return Some(&args[at + 1..]); - } - } - _ => {} - } - } - None + let comma = *top_level(args).0.get(n - 1)?; + Some(&args[comma + 1..]) } /// Where each value the error handler `name` of a `.map_err(name)` in `code` can return starts: @@ -7219,30 +7360,11 @@ fn handler_returns<'a>(code: &'a str, name: &str) -> Vec<&'a str> { out } -/// The statement `code` starts with, up to its `;` or the bracket that closes the block it is in. +/// The statement `code` starts with, up to its `;` or the bracket that closes the block it is in; +/// a `;` or bracket inside a string literal, raw ones included, or a character literal does not +/// end it (see [`top_level`]). fn statement(code: &str) -> &str { - let (mut depth, mut chars) = (0usize, code.char_indices()); - while let Some((at, c)) = chars.next() { - match c { - '(' | '[' | '{' => depth += 1, - ')' | ']' | '}' => match depth.checked_sub(1) { - Some(d) => depth = d, - None => return &code[..at], - }, - ';' if depth == 0 => return &code[..at], - '"' => loop { - match chars.next() { - Some((_, '\\')) => { - chars.next(); - } - Some((_, '"')) | None => break, - _ => {} - } - }, - _ => {} - } - } - code + &code[..top_level(code).1] } /// Where each value a closure can return starts, `body` being the text after its parameters: the @@ -7269,10 +7391,15 @@ fn closure_returns(body: &str) -> Vec<&str> { // For each open bracket, the `quiet` and `in_let` of the text around it: `quiet` names the // `let` that a value inside the bracket belongs to, `in_let` the `let` the statement is. let mut outer = vec![]; - let (mut quiet, mut in_let, mut chars) = (None, let_at(0), body.char_indices()); + let (mut quiet, mut in_let) = (None, let_at(0)); // Where the innermost closure in the body that a `return` would leave ends. let mut inner_closure_end = 0; - while let Some((at, c)) = chars.next() { + // Where the string or character literal last read ends: nothing inside one is syntax. + let mut literal_end = 0; + for (at, c) in body.char_indices() { + if at < literal_end { + continue; + } match c { '|' if at >= inner_closure_end => { let before = body[..at].trim_end(); @@ -7313,15 +7440,8 @@ fn closure_returns(body: &str) -> Vec<&str> { { found.push((&body[at + "return".len()..], None, true)); } - '"' => loop { - match chars.next() { - Some((_, '\\')) => { - chars.next(); - } - Some((_, '"')) | None => break, - _ => {} - } - }, + '"' => literal_end = quoted_end(body, at).unwrap_or(body.len()), + '\'' => literal_end = quoted_end(body, at).unwrap_or(at), _ => {} } } @@ -7340,52 +7460,38 @@ fn closure_returns(body: &str) -> Vec<&str> { } /// `code`, its string literals already emptied, with the arguments of each `format!(…)` removed: -/// a value written into a format string is part of a message, not one of its own. +/// a value written into a format string is part of a message, not one of its own. A bracket in a +/// character literal (`')'`) does not end the arguments (see [`top_level`]). fn without_format_args(code: &str) -> String { let (mut out, mut rest) = (String::new(), code); while let Some(at) = rest.find("format!(") { out.push_str(&rest[..at + "format!(".len()]); rest = &rest[at + "format!(".len()..]; - let mut depth = 0usize; - let end = rest.char_indices().find_map(|(i, c)| match c { - '(' | '[' | '{' => { - depth += 1; - None - } - ')' | ']' | '}' => match depth.checked_sub(1) { - Some(d) => { - depth = d; - None - } - None => Some(i), - }, - _ => None, - }); - rest = &rest[end.unwrap_or(rest.len())..]; + let (_, end) = top_level(rest); + rest = &rest[end..]; } out.push_str(rest); out } -/// `code` with the text of its string literals removed, the quotes kept. +/// `code` with the text of its string literals removed, the quotes kept: a raw literal keeps its +/// prefix and its `#`s (`r#""#`). Character literals stay as they are. fn without_strings(code: &str) -> String { - let (mut out, mut chars) = (String::new(), code.chars()); - while let Some(c) = chars.next() { - out.push(c); + let (mut out, mut i) = (String::new(), 0); + while let Some(c) = code[i..].chars().next() { if c == '"' { - loop { - match chars.next() { - Some('\\') => { - chars.next(); - } - Some('"') => { - out.push('"'); - break; - } - Some(_) => {} - None => break, - } - } + let Some(end) = quoted_end(code, i) else { + out.push('"'); + break; + }; + let close = 1 + raw_hashes(code, i).unwrap_or(0); + out.push('"'); + out.push_str(&code[end - close..end]); + i = end; + } else { + let end = (c == '\'').then(|| quoted_end(code, i)).flatten().unwrap_or(i + c.len_utf8()); + out.push_str(&code[i..end]); + i = end; } } out diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 40e93c07ed..666fa5bc80 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1153,6 +1153,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`). - The untranslated-strings report reads a message written over two lines with a `\` at the end of the first as one line, the text the program shows, and the Georgian catalog's (`ka`) row for PDF export's warning about knockout groups with too many translucent elements matches that text (`message_scan_joins_a_literal_continued_on_the_next_line`, `untranslated_report`). - The untranslated-strings report reads the escapes in a message (`\r`, `\0`, `\x41`, `\u{e9}` and the others the Rust Reference lists at https://doc.rust-lang.org/reference/tokens.html#character-escapes) as the characters the program shows, and leaves out a literal with an escape Rust does not accept, such as `\q` or `\u{D800}` (`message_scan_decodes_rust_character_escapes`, `message_scan_rejects_invalid_rust_escapes`). + - The untranslated-strings report and the undo step-name check read a message, a `&str` constant, a step name or a `format!` string written as a raw string (`r"…"`, `r#"…"#`, `r##"…"##`) with its backslashes kept, up to the quote followed by the literal's own number of `#` (https://doc.rust-lang.org/reference/tokens.html#raw-string-literals). They read no byte string or C string as a message, and a comma, `;`, bracket or `return` inside a raw string or a character literal does not end an argument, a statement or a closure's value (`undo_scan_reads_raw_step_names`, `message_scan_reads_raw_strings`, `message_scan_skips_byte_and_c_strings`, `message_scan_reads_past_raw_strings`, `format_args_end_at_the_closing_parenthesis`). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). - The status bar translates `script.run`'s refusals of `answers` in every language that translates every message: a value that is not a list, more than 10,000 answers, more than 1 MiB, an answer at an index that is not an object, does not have exactly `kind` and `value`, has a `value` its kind of dialog does not take, holds a prompt's text longer than 16 KiB or has an unknown `kind`, and `answers` given to a run in the app. The index, the counts and the code names are shown as they are, and the command's error stays in English. The untranslated-strings report also lists the refusals of `script.run`'s parameters (`script_answers_errors_are_translated`, `message_scan_reads_script_run_param_refusals`). - The status bar also translates `script.run`'s other refusals of its parameters in every language that translates every message: a `maxFuel` outside 1 to 100,000,000,000, `args` nested more than 64 levels deep (with the place in `args`), `args` that is not an object or is larger than 1 MiB, an empty `path`, a `source` given with `installed`, a `path` that does not name a .js or .jsx file, and neither or both of `path` and `source`. The code names, the place in `args`, the file suffixes and the limits are shown as they are, and the command's error stays in English (`script_run_param_errors_are_translated`). From 8cc1bc85307c91d94d5ffcc76f8c90fd03fd0755 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:01:07 -0800 Subject: [PATCH 011/193] Scripts: ExternalObject loads the XMP objects XMPMeta, XMPFile and XMPConst new ExternalObject("lib:AdobeXMPScript") defines XMPMeta, XMPFile and XMPConst in the script engine; any other library name throws and no native library is loaded. - XMPMeta reads a packet string and serializes one, with or without the packet wrapper: simple properties, arrays of simple items, language alternatives and namespace registration and lookup. Structures and values with qualifiers are kept as they were written. - XMPFile reads and writes only where File may. A .xmp sidecar opened for update takes putXMP, and closeFile writes it through a temporary file in the same folder when the script may write there; other files are scanned for their packet and are read only. File's 8 MiB limit applies before reading. - Packets are parsed with craft-xml: a document type declaration, an undefined entity, nesting over 64 levels and a packet over 8 MiB are refused with an error. - Members not built yet (iterators, structure fields, qualifiers, aliases, sorting, byte-array packets, XMPFile.getFormatInfo) throw that they are not available yet. The XMPConst flag values follow the public XMP Toolkit SDK header XMP_Const.h. Tests: crates/js/src/xmp_tests.rs, with fuzz cases for the packet parser and scanner, and crates/engine/src/tests/script_xmp.rs. Docs: docs/mcp.md and docs/target-app-parity.md. --- Cargo.lock | 1 + crates/engine/src/script/files.rs | 169 +++- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_xmp.rs | 479 ++++++++++ crates/js/Cargo.toml | 2 + crates/js/src/file_classes.rs | 23 + crates/js/src/heap.rs | 5 +- crates/js/src/interp.rs | 5 + crates/js/src/lib.rs | 5 + crates/js/src/realm.rs | 12 + crates/js/src/xmp.rs | 762 +++++++++++++++ crates/js/src/xmp_classes.rs | 1224 +++++++++++++++++++++++++ crates/js/src/xmp_tests.rs | 322 +++++++ crates/ui-egui/src/i18n/ca.tsv | 15 + crates/ui-egui/src/i18n/cs.tsv | 15 + crates/ui-egui/src/i18n/da.tsv | 15 + crates/ui-egui/src/i18n/de.tsv | 15 + crates/ui-egui/src/i18n/el.tsv | 15 + crates/ui-egui/src/i18n/es.tsv | 15 + crates/ui-egui/src/i18n/fi.tsv | 15 + crates/ui-egui/src/i18n/fr.tsv | 15 + crates/ui-egui/src/i18n/hi.tsv | 15 + crates/ui-egui/src/i18n/hu.tsv | 15 + crates/ui-egui/src/i18n/id.tsv | 15 + crates/ui-egui/src/i18n/it.tsv | 15 + crates/ui-egui/src/i18n/ja.tsv | 15 + crates/ui-egui/src/i18n/ka.tsv | 15 + crates/ui-egui/src/i18n/ko.tsv | 15 + crates/ui-egui/src/i18n/nl.tsv | 15 + crates/ui-egui/src/i18n/pl.tsv | 15 + crates/ui-egui/src/i18n/pt-br.tsv | 15 + crates/ui-egui/src/i18n/ru.tsv | 15 + crates/ui-egui/src/i18n/sv.tsv | 15 + crates/ui-egui/src/i18n/tr.tsv | 15 + crates/ui-egui/src/i18n/uk.tsv | 15 + crates/ui-egui/src/i18n/vi.tsv | 15 + crates/ui-egui/src/i18n/zh-hans.tsv | 15 + crates/ui-egui/src/i18n/zh-hant.tsv | 15 + docs/mcp.md | 36 + docs/target-app-parity.md | 1 + 40 files changed, 3420 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/tests/script_xmp.rs create mode 100644 crates/js/src/xmp.rs create mode 100644 crates/js/src/xmp_classes.rs create mode 100644 crates/js/src/xmp_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 6a602ed891..69d5e6b6d9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7031,6 +7031,7 @@ name = "vectorcraft-js" version = "0.24.1" dependencies = [ "chrono", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", "getrandom 0.4.3", "proptest", "unicode-properties", diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 94ef3bdf9e..d22db3dc6a 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1850,6 +1850,168 @@ 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))), + ])) +} + +/// `xmpWrite(path, packet)`: 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. Open objects of the +/// file hold the new bytes. +fn xmp_write(host: &Host, a: &[Data]) -> Result { + let path = arg_text(a, 0); + let packet = arg_text(a, 1).into_bytes(); + 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 holders = disk.open.values().filter(|o| o.holds(&target)).count(); + disk.charge_write(packet.len().saturating_mul(holders.saturating_add(1)))?; + 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); + // `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| allowed(t).then(|| std::fs::OpenOptions::new().write(true).create_new(true).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")); + } + std::io::Write::write_all(&mut out, &packet) + }; + let r = write_temp(); + drop(out); + 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)) { + file.bytes.clone_from(&packet); + // The packet is UTF-8 without a byte order mark, so an object reading UTF-16 reads it as + // UTF-8 from the start. + if matches!(file.encoding, Encoding::Utf16Le | Encoding::Utf16Be) { + file.encoding = Encoding::Utf8; + file.name = Encoding::Utf8.name().to_string(); + file.pos = 0; + } + file.pos = file.pos.min(packet.len()); + file.dirty = false; + } + } + 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(); @@ -2455,8 +2617,11 @@ 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(), call(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 @@ -2476,6 +2641,8 @@ 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(test)] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e524d1c63c..48cca170c6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -177,6 +177,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_xmp; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs new file mode 100644 index 0000000000..a89efbc14f --- /dev/null +++ b/crates/engine/src/tests/script_xmp.rs @@ -0,0 +1,479 @@ +//! `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\ +"; + +/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real path. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-xmp-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +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 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", " 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)?; diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f612b00138..fc665342dc 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -246,6 +246,8 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// An `XMPMeta` object and its metadata ([`crate::xmp_classes`]). + Xmp(Box), } /// What an XML value is. @@ -309,7 +311,7 @@ impl Class { Class::XmlList(_) => "XMLList", Class::Namespace(_) => "Namespace", Class::QName { .. } => "QName", - Class::XmlFilter(_) => "Object", + Class::XmlFilter(_) | Class::Xmp(_) => "Object", Class::Math => "Math", Class::Json => "JSON", Class::Ordinary | Class::ForIn(_) => "Object", @@ -680,6 +682,7 @@ 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(), _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..4ef92c0ffd 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -253,6 +253,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 clock and time zone `Date` reads. pub(crate) date_host: crate::date_builtins::DateHost, /// The bytes native code holds outside the heap's cells through [`HeldBytes`]. @@ -518,6 +521,7 @@ impl Interp { held_bytes: 0, install_error: None, files: None, + xmp: None, date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), flattened: std::cell::Cell::new(0), @@ -774,6 +778,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.envs.push(self.global_env); self.heap.collect(&roots); // The collection counts the live total again, so bytes already released are not in it. diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..e2d9bddd6c 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -72,6 +72,8 @@ mod token; mod value; mod xml; mod xml_builtins; +mod xmp; +mod xmp_classes; mod xpath; pub use ast::{ @@ -85,6 +87,7 @@ pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, 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)] @@ -214,3 +217,5 @@ mod tests; mod text_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 ee2cd364f8..a9826703ed 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -504,6 +504,18 @@ 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. + 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), + } + } + /// Sets `Folder.current` back to the host's `current`, for the next run of a realm that has /// `File` and `Folder` ([`Realm::define_file_classes`]); a realm without them keeps its /// `Folder.current`. The files an earlier run opened are no longer open. The last run's uncaught diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs new file mode 100644 index 0000000000..e0a54bb30b --- /dev/null +++ b/crates/js/src/xmp.rs @@ -0,0 +1,762 @@ +//! 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. Namespaces a packet declares are added to +//! the realm's [`Registry`] with the prefix the packet gives them, or a new prefix when that one is +//! taken. +//! +//! VectorCraft's own rules: a packet or a written packet holds at most [`MAX_BYTES`] bytes, +//! elements nest at most 64 deep, a child of `rdf:RDF` other than `rdf:Description` makes the +//! packet malformed, a property given twice keeps its first value, and [`find_packet`] finds only a +//! UTF-8 packet. + +use std::collections::{HashMap, HashSet}; + +use craft_xml::{Doctype, El, Limits, Names, Node, Options, UnknownEntity, XML_NS}; + +/// 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 `id` of a packet wrapper (XMP Specification Part 1, 7.3.2). +const WRAPPER_ID: &str = "W5M0MpCehiHzreSzNTczkc9d"; + +/// 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`]. + TooLarge, + /// The realm already has [`MAX_NAMESPACES`] namespaces. + 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, + /// A path form not read yet: a structure field, a qualifier or a selector. + NotYet, +} + +/// 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(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Item { + pub(crate) text: String, + pub(crate) lang: Option, +} + +/// 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, + options: u32, + text: Option, + }, +} + +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(|i| i.lang.is_some()); + 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 { + pub(crate) ns: String, + 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, .. } => items.iter().map(|i| 48 + i.text.len() + i.lang.as_ref().map_or(0, String::len)).sum(), + Value::Other { xml, text, .. } => xml.len() + 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, +} + +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(), + } + } +} + +impl Registry { + /// 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. + pub(crate) fn register(&mut self, uri: &str, suggested: &str) -> Result { + if let Some(p) = self.prefix_of(uri) { + return Ok(p.to_string()); + } + let suggested = suggested.strip_suffix(':').unwrap_or(suggested); + // 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; + } + self.prefixes.insert(uri.to_string(), prefix.clone()); + self.uris.insert(prefix.clone(), uri.to_string()); + Ok(prefix) + } +} + +/// 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:") +} + +/// 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)> { + 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) -> Option<&'a El> { + let mark = scope.len(); + push_decls(el, scope); + if is_named(&el.name, scope, true, RDF, "RDF") { + return Some(el); + } + for c in el.elements() { + if let Some(found) = find_rdf(c, scope) { + return Some(found); + } + } + scope.truncate(mark); + None +} + +/// Reads the packet `text`, registering the namespaces it uses in `registry`. A packet that fails +/// to read leaves `registry` unchanged. +pub(crate) fn parse(text: &str, registry: &mut Registry) -> Result { + let mut staged = registry.clone(); + let meta = parse_into(text, &mut staged)?; + *registry = staged; + Ok(meta) +} + +fn parse_into(text: &str, registry: &mut Registry) -> 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: true, + limits, + ..Options::default() + } + .strict(); + let root = opts.parse(text.as_bytes()).map_err(|e| if e.is_limit() { XmpError::TooLarge } else { XmpError::Malformed })?; + let mut scope = Scope::new(); + let rdf = find_rdf(&root, &mut scope).ok_or(XmpError::Malformed)?; + let mut meta = Meta::default(); + let mut seen = HashSet::new(); + for d in rdf.elements() { + let mark = scope.len(); + push_decls(d, &mut scope); + if !is_named(&d.name, &scope, true, RDF, "Description") { + return Err(XmpError::Malformed); + } + 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" && meta.about.is_empty() { + meta.about = v.to_string(); + } + continue; + } + if ns.is_empty() || ns == XML { + continue; + } + let prefix = k.split_once(':').map_or("ns", |(p, _)| p); + registry.register(&ns, prefix)?; + add(&mut meta, &mut seen, 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)?; + add(&mut meta, &mut seen, prop); + } + scope.truncate(mark); + } + Ok(meta) +} + +/// Adds `prop` to `meta` unless it already has a property of that name; `seen` holds the names +/// `meta` has. +fn add(meta: &mut Meta, seen: &mut HashSet<(String, String)>, prop: Prop) { + if seen.insert((prop.ns.clone(), prop.name.clone())) { + meta.props.push(prop); + } +} + +fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry) -> 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 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().is_empty() + { + Value::Simple { text: (*v).to_string(), uri: true } + } else if let (Some(array), true) = (array_of(&children, scope), own.is_empty()) { + array + } else { + other(p, &own, &children, scope, mark) + }; + scope.truncate(mark); + Ok(Prop { ns, name: local.to_string(), value }) +} + +/// 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().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. +fn other(p: &El, own: &[(&str, &str)], children: &[&El], scope: &mut Scope, mark: usize) -> Value { + // The first child's name is read with the prefixes it declares itself. + let form = children.first().and_then(|c| { + let inner = scope.len(); + push_decls(c, scope); + let form = [Form::Bag, Form::Seq, Form::Alt].into_iter().find(|f| is_named(&c.name, scope, true, RDF, &f.element()[4..])); + scope.truncate(inner); + form + }); + 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")); + let (options, text) = 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), + _ => { + 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)))) + } + }; + let mut xml = String::new(); + write_fragment(p, scope.get(..mark).unwrap_or(&[]), &mut xml); + Value::Other { xml, options, text } +} + +/// Writes the element `p` as XML, declaring on it the prefixes from `outer` that it and the +/// elements inside it use and do not declare themselves. +fn write_fragment(p: &El, outer: &[(String, String)], out: &mut String) { + 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_str(&p.name); + for prefix in used.iter().filter(|u| !own.contains(&u.as_str())) { + if let Some((_, uri)) = outer.iter().rev().find(|(q, _)| q == prefix) { + if prefix.is_empty() { + out.push_str(" xmlns=\""); + } else { + out.push_str(" xmlns:"); + out.push_str(prefix); + out.push_str("=\""); + } + craft_xml::push_esc_attr(out, uri); + out.push('"'); + } + } + write_rest(p, out); +} + +/// 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 String) { + for (k, v) in &el.attrs { + out.push(' '); + out.push_str(k); + out.push_str("=\""); + craft_xml::push_esc_attr(out, v); + out.push('"'); + } + if el.children.is_empty() { + out.push_str("/>"); + return; + } + out.push('>'); + for n in &el.children { + match n { + Node::El(c) => { + out.push('<'); + out.push_str(&c.name); + write_rest(c, out); + } + Node::Text(t) | Node::CData(t) => craft_xml::push_esc(out, t), + Node::Pi { .. } | Node::Comment(_) => {} + } + } + out.push_str("'); +} + +/// 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.as_str()) { + continue; + } + let prefix = registry.prefix_of(&p.ns).ok_or(XmpError::BadName)?; + namespaces.push((prefix, &p.ns)); + } + 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 { + packet.rfind(" Option { + const BEGIN: &[u8] = b"") { + Some(close) => return Some(PacketSpan { start, end: close + 2, writeable: bytes.get(after + 1) == Some(&b'w') }), + None => start = next?, + } + } +} diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs new file mode 100644 index 0000000000..ab6c2a6174 --- /dev/null +++ b/crates/js/src/xmp_classes.rs @@ -0,0 +1,1224 @@ +//! `ExternalObject` and the XMP classes it loads, as the help pages +//! , +//! 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. +//! +//! `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; an +//! `XMPFile` is open only in the run that opened it, and a packet it kept and did not write is +//! dropped when the run ends. 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, data, method, native}; +use crate::heap::{Class, ENUMERABLE, HIDDEN, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, 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 { + /// 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 { + 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 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 { + 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), + } +} + +fn not_array(i: &mut Interp, what: &str, name: &str) -> Abrupt { + i.throw(ErrorType::Error, &format!("{what}: {name} is not an array")) +} + +fn not_simple(i: &mut Interp, what: &str, name: &str) -> Abrupt { + i.throw(ErrorType::Error, &format!("{what}: {name} is not a simple property")) +} + +fn not_alt_text(i: &mut Interp, what: &str, name: &str) -> Abrupt { + 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 { + 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 { + 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<()> { + 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: HIDDEN }) +} + +/// 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| { + i.reserve_heap(OBJECT_BYTES + PROP_BYTES * fields.len())?; + 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: String = name.chars().take(200).collect(); + 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; + data(i, global, "XMPMeta", Value::Object(ids.meta), HIDDEN)?; + data(i, global, "XMPFile", Value::Object(ids.file), HIDDEN)?; + data(i, global, "XMPConst", Value::Object(ids.constants), HIDDEN)?; + 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| set_slot(i, o, LIBRARY_SLOT, Value::str(LIBRARY)))?; + 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 { + 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 = m.heap_bytes(); + let r = f(m, &c.registry); + let after = m.heap_bytes(); + 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 { + spend(i, text.len())?; + let r = xmp::parse(text, registry(i)?); + r.map_err(|e| xmp_error(i, what, e, "")) +} + +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`: the namespace, the property name and its step. +fn target(i: &mut Interp, args: &[Value], at: usize, what: &str) -> JsResult<(String, String, Step)> { + let ns = namespace(i, &arg(args, at), what)?; + let path = text(i, &arg(args, at + 1))?; + let r = xmp::parse_path(&path, &ns, registry(i)?); + match r { + Ok((name, step)) => Ok((ns, name, step)), + 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 (ns, name, step) = 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 path = text(i, &arg(args, 1))?; + let found = { + let m = meta_of(i, o)?; + m.find(&ns, &name).map(|at| m.props[at].value.clone()) + }; + let Some(value) = found else { return Ok(Value::Undefined) }; + match step { + Step::Whole => property(i, &ns, &path, value.text(), value.options(), ""), + Step::Item(index) => match value { + xmp::Value::Array { items, .. } => match position(index, items.len()).and_then(|p| items.get(p)) { + Some(item) => property(i, &ns, &path, Some(&item.text), 0, item.lang.as_deref().unwrap_or("")), + None => Ok(Value::Undefined), + }, + _ => Err(not_array(i, what, &name)), + }, + } +} + +fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let what = "XMPMeta.setProperty"; + let o = this_meta(i, &this, what)?; + let (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 { + 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, 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, 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 (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 (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 array name argument at `at` after the namespace: a whole property. +fn array_target(i: &mut Interp, args: &[Value], what: &str) -> JsResult<(String, String)> { + let (ns, name, step) = target(i, args, 0, what)?; + if step != Step::Whole { + let path = text(i, &arg(args, 1))?; + return Err(not_handled(i, what, &path)); + } + Ok((ns, name)) +} + +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 (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 (ns, name) = 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!("{}[{}]", text(i, &arg(args, 1))?, p + 1); + property(i, &ns, &path, Some(&item.text), 0, 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 (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) => len, + 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(); + match found { + Some((at, _, _)) => change(i, o, 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.to_string(), + 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 (ns, name) = array_target(i, args, what)?; + // `itemOptions` may be left out: a string or `null` third argument is the item's value. + let (value, array_options) = match arg(args, 2) { + Value::Number(_) => { + item_options(i, &arg(args, 2), what)?; + (arg(args, 3), arg(args, 4)) + } + v => (v, 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 (ns, name) = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + let value = xml_text(i, &arg(args, 3), 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 (ns, name) = array_target(i, args, what)?; + let index = item_index(i, &arg(args, 2), what)?; + let value = xml_text(i, &arg(args, 3), 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 (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)) +} + +/// 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> { + let generic_match = |i: &&Item| { + !generic.is_empty() + && i.lang.as_deref().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'-') + }) + }; + items + .iter() + .find(|i| same_lang(i.lang.as_deref(), specific)) + .or_else(|| items.iter().find(generic_match)) + .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) } +} + +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 (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, form, _)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; + if form != Form::Alt { + 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).map(|i| i.text.clone()), + _ => None, + }; + match found { + Some(t) => string(i, &t), + 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 (ns, name) = array_target(i, args, 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)?; + let at = match found { + Some((_, form, _)) if form != Form::Alt => return Err(not_alt_text(i, what, &name)), + Some((at, _, _)) => at, + None => { + let prop = xmp::Prop { ns: ns.clone(), name: name.clone(), value: xmp::Value::Array { form: Form::Alt, items: Vec::new() } }; + change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop))?; + meta_of(i, o)?.find(&ns, &name).unwrap_or(0) + } + }; + let grow = 2 * (64 + value.len() + specific.len()); + change(i, o, grow, |m, _| { + let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|p| &mut p.value) else { return }; + set_lang(items, &specific, value); + })?; + Ok(Value::Undefined) +} + +/// Sets the item of `items` in `specific` to `value`. 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. +fn set_lang(items: &mut Vec, specific: &str, value: String) { + let default = items.iter().position(|i| same_lang(i.lang.as_deref(), "x-default")); + if specific.eq_ignore_ascii_case("x-default") { + match default { + Some(d) => { + if let Some(item) = items.get_mut(d) { + item.text = 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)); + 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 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, ""))?; + spend(i, s.len())?; + 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 r = registry(i)?.register(&uri, &prefix); + match r { + Ok(p) => 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 it is not one. +fn this_file(i: &mut Interp, this: &Value, what: &str) -> JsResult { + if let Some(o) = this.as_object() + && 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)?; + 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; + i.reserve_heap(OBJECT_BYTES + 12 * PROP_BYTES)?; + let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(file_proto))); + 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")?), + ]; + 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().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 pad = crate::xmp::pad_size(&text(i, &packet)?) * 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())?; + xmp::parse(&s, &mut scratch).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 { + Ok(_) => Ok(Value::Bool(true)), + 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)?; + let v = string(i, &packet)?; + i.rooted(std::slice::from_ref(&v), |i| set_slot(i, o, PENDING, v.clone()))?; + 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 r = i.rooted(&[path.clone(), pending.clone()], |i| crate::file_classes::call_host(i, "xmpWrite", &[path.clone(), pending.clone()]))?; + 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, OPEN, Value::Bool(false))?; + Ok(Value::Undefined) +} + +// ---- install ---- + +/// 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 { + 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 { + constant(i, o, name, Value::str(uri))?; + } + 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`]). +pub(crate) fn install(i: &mut Interp) -> JsResult<()> { + 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); + 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)?; + i.xmp = Some(Classes { + ids: Ids { external_proto, meta, meta_proto, file, file_proto, constants, property_proto }, + registry: Registry::default(), + }); + 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)?; + crate::builtins::constructor(i, "ExternalObject", external, external_proto)?; + method(i, external, "search", external_search, 1)?; + method(i, external_proto, "terminate", external_terminate, 0) + }) + }) + }) +} diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs new file mode 100644 index 0000000000..5641ff77d7 --- /dev/null +++ b/crates/js/src/xmp_tests.rs @@ -0,0 +1,322 @@ +use proptest::prelude::*; + +use crate::xmp::{self, Form, Registry, XmpError}; +use crate::{JsValue, 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 + + + +"#; + +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')")), "Bonjour"); + assert_eq!(string(&with_packet("m.getLocalizedText(XMPConst.NS_DC, 'title', null, 'de-DE')")), "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:"); +} + +#[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/"); +} + +/// 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("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 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); + 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!(" junk {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!(" junk ", + "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"); +} + +#[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;", + "]]>", + "", + "", + "", + "", + "", + "", +]; + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + /// 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/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..a931d02068 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6573,6 +6573,21 @@ liquify-list-end {0}, {1} {0} i {1} @msg the script passed more data to and from commands than one run may pass l'script ha passat més dades a les ordres i des de les ordres de les que pot passar una execució @msg the script added more objects and data to the documents than one run may add l'script ha afegit als documents més objectes i dades dels que pot afegir una execució @msg {what}: the object is not a File or a Folder {what}: l'objecte no és un File ni un Folder +@msg {what}: the library {name} is not available {what}: la biblioteca {name} no està disponible +@msg {what} is not available yet {what} encara no està disponible +@msg {what}: the value {value} is not available yet {what}: el valor {value} encara no està disponible +@msg {what}: the object is not an {class} object {what}: l'objecte no és un objecte {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: el paquet XMP no és XMP ben format +@msg {what}: the XMP data is too large {what}: les dades XMP són massa grans +@msg {what}: {name} is not a valid property name {what}: {name} no és un nom de propietat vàlid +@msg {what}: the text holds a character XML does not allow {what}: el text conté un caràcter que XML no permet +@msg {what}: {name} is not an array {what}: {name} no és una matriu +@msg {what}: {name} is not a simple property {what}: {name} no és una propietat simple +@msg {what}: {name} is not a language alternative array {what}: {name} no és una matriu d'alternatives d'idioma +@msg {what}: the array index {index} is out of range {what}: l'índex de matriu {index} és fora de l'interval +@msg {what}: the namespace {uri} is not registered {what}: l'espai de noms {uri} no està registrat +@msg {what}: the file is closed {what}: el fitxer està tancat +@msg {what}: the file cannot be updated {what}: el fitxer no es pot actualitzar @msg {what}: the count must be a finite number, 0 or more {what}: el recompte ha de ser un nombre finit, 0 o més @msg File.seek: the position must be a finite number File.seek: la posició ha de ser un nombre finit @msg File.seek: the mode must be 0, 1 or 2 File.seek: el mode ha de ser 0, 1 o 2 diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..e4c6c614ad 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5368,6 +5368,21 @@ liquify-list-end {0}, {1} {0} a {1} @msg the script passed more data to and from commands than one run may pass skript předal příkazům a z příkazů více dat, než smí předat jeden běh @msg the script added more objects and data to the documents than one run may add skript přidal do dokumentů více objektů a dat, než smí přidat jeden běh @msg {what}: the object is not a File or a Folder {what}: objekt není File ani Folder +@msg {what}: the library {name} is not available {what}: knihovna {name} není k dispozici +@msg {what} is not available yet {what} zatím není k dispozici +@msg {what}: the value {value} is not available yet {what}: hodnota {value} zatím není k dispozici +@msg {what}: the object is not an {class} object {what}: objekt není objekt {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: paket XMP není správně utvořené XMP +@msg {what}: the XMP data is too large {what}: data XMP jsou příliš velká +@msg {what}: {name} is not a valid property name {what}: {name} není platný název vlastnosti +@msg {what}: the text holds a character XML does not allow {what}: text obsahuje znak, který XML nepovoluje +@msg {what}: {name} is not an array {what}: {name} není pole +@msg {what}: {name} is not a simple property {what}: {name} není jednoduchá vlastnost +@msg {what}: {name} is not a language alternative array {what}: {name} není pole jazykových alternativ +@msg {what}: the array index {index} is out of range {what}: index pole {index} je mimo rozsah +@msg {what}: the namespace {uri} is not registered {what}: obor názvů {uri} není registrován +@msg {what}: the file is closed {what}: soubor je zavřený +@msg {what}: the file cannot be updated {what}: soubor nelze aktualizovat @msg {what}: the count must be a finite number, 0 or more {what}: počet musí být konečné číslo, 0 nebo více @msg File.seek: the position must be a finite number File.seek: pozice musí být konečné číslo @msg File.seek: the mode must be 0, 1 or 2 File.seek: režim musí být 0, 1 nebo 2 diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..7c2c34978b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -216,6 +216,21 @@ liquify-list-end {0}, {1} {0} og {1} @msg the script passed more data to and from commands than one run may pass scriptet sendte flere data til og fra kommandoer, end én kørsel må sende @msg the script added more objects and data to the documents than one run may add scriptet tilføjede flere objekter og data til dokumenterne, end én kørsel må tilføje @msg {what}: the object is not a File or a Folder {what}: objektet er ikke en File eller en Folder +@msg {what}: the library {name} is not available {what}: biblioteket {name} er ikke tilgængeligt +@msg {what} is not available yet {what} er endnu ikke tilgængelig +@msg {what}: the value {value} is not available yet {what}: værdien {value} er endnu ikke tilgængelig +@msg {what}: the object is not an {class} object {what}: objektet er ikke et {class}-objekt +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP-pakken er ikke velformet XMP +@msg {what}: the XMP data is too large {what}: XMP-dataene er for store +@msg {what}: {name} is not a valid property name {what}: {name} er ikke et gyldigt egenskabsnavn +@msg {what}: the text holds a character XML does not allow {what}: teksten indeholder et tegn, som XML ikke tillader +@msg {what}: {name} is not an array {what}: {name} er ikke en matrix +@msg {what}: {name} is not a simple property {what}: {name} er ikke en simpel egenskab +@msg {what}: {name} is not a language alternative array {what}: {name} er ikke en matrix af sprogalternativer +@msg {what}: the array index {index} is out of range {what}: matrixindekset {index} er uden for området +@msg {what}: the namespace {uri} is not registered {what}: navnerummet {uri} er ikke registreret +@msg {what}: the file is closed {what}: filen er lukket +@msg {what}: the file cannot be updated {what}: filen kan ikke opdateres @msg {what}: the count must be a finite number, 0 or more {what}: antallet skal være et endeligt tal, 0 eller mere @msg File.seek: the position must be a finite number File.seek: positionen skal være et endeligt tal @msg File.seek: the mode must be 0, 1 or 2 File.seek: tilstanden skal være 0, 1 eller 2 diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..d36b965b27 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4953,6 +4953,21 @@ liquify-list-end {0}, {1} {0} und {1} @msg the script passed more data to and from commands than one run may pass das Skript hat mehr Daten an Befehle und von Befehlen übergeben, als ein Lauf übergeben darf @msg the script added more objects and data to the documents than one run may add das Skript hat den Dokumenten mehr Objekte und Daten hinzugefügt, als ein Lauf hinzufügen darf @msg {what}: the object is not a File or a Folder {what}: Das Objekt ist weder ein File noch ein Folder +@msg {what}: the library {name} is not available {what}: Die Bibliothek {name} ist nicht verfügbar +@msg {what} is not available yet {what} ist noch nicht verfügbar +@msg {what}: the value {value} is not available yet {what}: Der Wert {value} ist noch nicht verfügbar +@msg {what}: the object is not an {class} object {what}: Das Objekt ist kein {class}-Objekt +@msg {what}: the XMP packet is not well-formed XMP {what}: Das XMP-Paket ist kein wohlgeformtes XMP +@msg {what}: the XMP data is too large {what}: Die XMP-Daten sind zu groß +@msg {what}: {name} is not a valid property name {what}: {name} ist kein gültiger Eigenschaftsname +@msg {what}: the text holds a character XML does not allow {what}: Der Text enthält ein Zeichen, das XML nicht zulässt +@msg {what}: {name} is not an array {what}: {name} ist kein Array +@msg {what}: {name} is not a simple property {what}: {name} ist keine einfache Eigenschaft +@msg {what}: {name} is not a language alternative array {what}: {name} ist kein Array mit Sprachalternativen +@msg {what}: the array index {index} is out of range {what}: Der Array-Index {index} liegt außerhalb des Bereichs +@msg {what}: the namespace {uri} is not registered {what}: Der Namensraum {uri} ist nicht registriert +@msg {what}: the file is closed {what}: Die Datei ist geschlossen +@msg {what}: the file cannot be updated {what}: Die Datei kann nicht aktualisiert werden @msg {what}: the count must be a finite number, 0 or more {what}: Die Anzahl muss eine endliche Zahl sein, 0 oder mehr @msg File.seek: the position must be a finite number File.seek: Die Position muss eine endliche Zahl sein @msg File.seek: the mode must be 0, 1 or 2 File.seek: Der Modus muss 0, 1 oder 2 sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..ac46fef527 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2770,6 +2770,21 @@ liquify-list-end {0}, {1} {0} και {1} @msg the script passed more data to and from commands than one run may pass το σενάριο μετέφερε περισσότερα δεδομένα προς και από εντολές από όσα επιτρέπονται σε μία εκτέλεση @msg the script added more objects and data to the documents than one run may add το σενάριο πρόσθεσε στα έγγραφα περισσότερα αντικείμενα και δεδομένα από όσα επιτρέπονται σε μία εκτέλεση @msg {what}: the object is not a File or a Folder {what}: το αντικείμενο δεν είναι File ούτε Folder +@msg {what}: the library {name} is not available {what}: η βιβλιοθήκη {name} δεν είναι διαθέσιμη +@msg {what} is not available yet {what} δεν είναι ακόμη διαθέσιμο +@msg {what}: the value {value} is not available yet {what}: η τιμή {value} δεν είναι ακόμη διαθέσιμη +@msg {what}: the object is not an {class} object {what}: το αντικείμενο δεν είναι αντικείμενο {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: το πακέτο XMP δεν είναι σωστά διαμορφωμένο XMP +@msg {what}: the XMP data is too large {what}: τα δεδομένα XMP είναι πολύ μεγάλα +@msg {what}: {name} is not a valid property name {what}: το {name} δεν είναι έγκυρο όνομα ιδιότητας +@msg {what}: the text holds a character XML does not allow {what}: το κείμενο περιέχει χαρακτήρα που η XML δεν επιτρέπει +@msg {what}: {name} is not an array {what}: το {name} δεν είναι πίνακας +@msg {what}: {name} is not a simple property {what}: το {name} δεν είναι απλή ιδιότητα +@msg {what}: {name} is not a language alternative array {what}: το {name} δεν είναι πίνακας γλωσσικών εναλλακτικών +@msg {what}: the array index {index} is out of range {what}: ο δείκτης πίνακα {index} είναι εκτός εύρους +@msg {what}: the namespace {uri} is not registered {what}: ο χώρος ονομάτων {uri} δεν είναι καταχωρισμένος +@msg {what}: the file is closed {what}: το αρχείο είναι κλειστό +@msg {what}: the file cannot be updated {what}: το αρχείο δεν μπορεί να ενημερωθεί @msg {what}: the count must be a finite number, 0 or more {what}: το πλήθος πρέπει να είναι πεπερασμένος αριθμός, 0 ή περισσότερο @msg File.seek: the position must be a finite number File.seek: η θέση πρέπει να είναι πεπερασμένος αριθμός @msg File.seek: the mode must be 0, 1 or 2 File.seek: ο τρόπος πρέπει να είναι 0, 1 ή 2 diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..415b46a8b0 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5045,6 +5045,21 @@ liquify-list-end {0}, {1} {0}, {1} @msg the script passed more data to and from commands than one run may pass el script pasó más datos a los comandos y desde ellos de los que puede pasar una ejecución @msg the script added more objects and data to the documents than one run may add el script añadió a los documentos más objetos y datos de los que puede añadir una ejecución @msg {what}: the object is not a File or a Folder {what}: el objeto no es un File ni un Folder +@msg {what}: the library {name} is not available {what}: la biblioteca {name} no está disponible +@msg {what} is not available yet {what} aún no está disponible +@msg {what}: the value {value} is not available yet {what}: el valor {value} aún no está disponible +@msg {what}: the object is not an {class} object {what}: el objeto no es un objeto {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: el paquete XMP no es XMP bien formado +@msg {what}: the XMP data is too large {what}: los datos XMP son demasiado grandes +@msg {what}: {name} is not a valid property name {what}: {name} no es un nombre de propiedad válido +@msg {what}: the text holds a character XML does not allow {what}: el texto contiene un carácter que XML no permite +@msg {what}: {name} is not an array {what}: {name} no es una matriz +@msg {what}: {name} is not a simple property {what}: {name} no es una propiedad simple +@msg {what}: {name} is not a language alternative array {what}: {name} no es una matriz de alternativas de idioma +@msg {what}: the array index {index} is out of range {what}: el índice de matriz {index} está fuera de rango +@msg {what}: the namespace {uri} is not registered {what}: el espacio de nombres {uri} no está registrado +@msg {what}: the file is closed {what}: el archivo está cerrado +@msg {what}: the file cannot be updated {what}: el archivo no se puede actualizar @msg {what}: the count must be a finite number, 0 or more {what}: la cantidad debe ser un número finito, 0 o más @msg File.seek: the position must be a finite number File.seek: la posición debe ser un número finito @msg File.seek: the mode must be 0, 1 or 2 File.seek: el modo debe ser 0, 1 o 2 diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..ad7e813fe5 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5286,6 +5286,21 @@ liquify-list-end {0}, {1} {0} ja {1} @msg the script passed more data to and from commands than one run may pass skripti välitti komennoille ja komennoilta enemmän tietoa kuin yksi ajo saa välittää @msg the script added more objects and data to the documents than one run may add skripti lisäsi asiakirjoihin enemmän objekteja ja tietoja kuin yksi ajo saa lisätä @msg {what}: the object is not a File or a Folder {what}: objekti ei ole File eikä Folder +@msg {what}: the library {name} is not available {what}: kirjasto {name} ei ole käytettävissä +@msg {what} is not available yet {what} ei ole vielä käytettävissä +@msg {what}: the value {value} is not available yet {what}: arvo {value} ei ole vielä käytettävissä +@msg {what}: the object is not an {class} object {what}: objekti ei ole {class}-objekti +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP-paketti ei ole hyvin muodostettua XMP:tä +@msg {what}: the XMP data is too large {what}: XMP-tiedot ovat liian suuret +@msg {what}: {name} is not a valid property name {what}: {name} ei ole kelvollinen ominaisuuden nimi +@msg {what}: the text holds a character XML does not allow {what}: teksti sisältää merkin, jota XML ei salli +@msg {what}: {name} is not an array {what}: {name} ei ole taulukko +@msg {what}: {name} is not a simple property {what}: {name} ei ole yksinkertainen ominaisuus +@msg {what}: {name} is not a language alternative array {what}: {name} ei ole kielivaihtoehtojen taulukko +@msg {what}: the array index {index} is out of range {what}: taulukon indeksi {index} on alueen ulkopuolella +@msg {what}: the namespace {uri} is not registered {what}: nimiavaruutta {uri} ei ole rekisteröity +@msg {what}: the file is closed {what}: tiedosto on suljettu +@msg {what}: the file cannot be updated {what}: tiedostoa ei voi päivittää @msg {what}: the count must be a finite number, 0 or more {what}: määrän on oltava äärellinen luku, 0 tai enemmän @msg File.seek: the position must be a finite number File.seek: sijainnin on oltava äärellinen luku @msg File.seek: the mode must be 0, 1 or 2 File.seek: tilan on oltava 0, 1 tai 2 diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..40cd203c0e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5013,6 +5013,21 @@ liquify-list-end {0}, {1} {0} et {1} @msg the script made more host calls than one run may make le script a fait plus d’appels à l’hôte qu’une exécution ne peut en faire @msg the script passed more data to and from commands than one run may pass le script a transmis plus de données vers et depuis les commandes qu’une exécution ne peut en transmettre @msg the script added more objects and data to the documents than one run may add le script a ajouté aux documents plus d’objets et de données qu’une exécution ne peut en ajouter +@msg {what}: the library {name} is not available {what} : la bibliothèque {name} n’est pas disponible +@msg {what} is not available yet {what} n’est pas encore disponible +@msg {what}: the value {value} is not available yet {what} : la valeur {value} n’est pas encore disponible +@msg {what}: the object is not an {class} object {what} : l’objet n’est pas un objet {class} +@msg {what}: the XMP packet is not well-formed XMP {what} : le paquet XMP n’est pas du XMP bien formé +@msg {what}: the XMP data is too large {what} : les données XMP sont trop volumineuses +@msg {what}: {name} is not a valid property name {what} : {name} n’est pas un nom de propriété valide +@msg {what}: the text holds a character XML does not allow {what} : le texte contient un caractère que XML n’autorise pas +@msg {what}: {name} is not an array {what} : {name} n’est pas un tableau +@msg {what}: {name} is not a simple property {what} : {name} n’est pas une propriété simple +@msg {what}: {name} is not a language alternative array {what} : {name} n’est pas un tableau d’alternatives linguistiques +@msg {what}: the array index {index} is out of range {what} : l’index de tableau {index} est hors limites +@msg {what}: the namespace {uri} is not registered {what} : l’espace de noms {uri} n’est pas enregistré +@msg {what}: the file is closed {what} : le fichier est fermé +@msg {what}: the file cannot be updated {what} : le fichier ne peut pas être mis à jour @msg {what}: the object is not a File or a Folder {what} : l’objet n’est ni un File ni un Folder @msg {what}: the count must be a finite number, 0 or more {what} : le nombre doit être un nombre fini, 0 ou plus @msg File.seek: the position must be a finite number File.seek : la position doit être un nombre fini diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..331aa30575 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7719,6 +7719,21 @@ liquify-list-end {0}, {1} {0} और {1} @msg the script passed more data to and from commands than one run may pass स्क्रिप्ट ने कमांड को और कमांड से एक रन में अनुमत से अधिक डेटा भेजा @msg the script added more objects and data to the documents than one run may add स्क्रिप्ट ने दस्तावेज़ों में एक रन में अनुमत से अधिक ऑब्जेक्ट और डेटा जोड़े @msg {what}: the object is not a File or a Folder {what}: ऑब्जेक्ट न File है न Folder +@msg {what}: the library {name} is not available {what}: लाइब्रेरी {name} उपलब्ध नहीं है +@msg {what} is not available yet {what} अभी उपलब्ध नहीं है +@msg {what}: the value {value} is not available yet {what}: मान {value} अभी उपलब्ध नहीं है +@msg {what}: the object is not an {class} object {what}: ऑब्जेक्ट {class} ऑब्जेक्ट नहीं है +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP पैकेट सही ढंग से बना XMP नहीं है +@msg {what}: the XMP data is too large {what}: XMP डेटा बहुत बड़ा है +@msg {what}: {name} is not a valid property name {what}: {name} मान्य प्रॉपर्टी नाम नहीं है +@msg {what}: the text holds a character XML does not allow {what}: टेक्स्ट में ऐसा वर्ण है जिसकी XML अनुमति नहीं देता +@msg {what}: {name} is not an array {what}: {name} ऐरे नहीं है +@msg {what}: {name} is not a simple property {what}: {name} सरल प्रॉपर्टी नहीं है +@msg {what}: {name} is not a language alternative array {what}: {name} भाषा विकल्पों का ऐरे नहीं है +@msg {what}: the array index {index} is out of range {what}: ऐरे इंडेक्स {index} सीमा से बाहर है +@msg {what}: the namespace {uri} is not registered {what}: नेमस्पेस {uri} पंजीकृत नहीं है +@msg {what}: the file is closed {what}: फ़ाइल बंद है +@msg {what}: the file cannot be updated {what}: फ़ाइल अपडेट नहीं की जा सकती @msg {what}: the count must be a finite number, 0 or more {what}: गिनती एक सीमित संख्या होनी चाहिए, 0 या अधिक @msg File.seek: the position must be a finite number File.seek: स्थिति एक सीमित संख्या होनी चाहिए @msg File.seek: the mode must be 0, 1 or 2 File.seek: मोड 0, 1 या 2 होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..8171b8d3f6 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5885,6 +5885,21 @@ liquify-list-end {0}, {1} {0} és {1} @msg the script passed more data to and from commands than one run may pass a parancsfájl több adatot adott át a parancsoknak és a parancsoktól, mint amennyit egy futás átadhat @msg the script added more objects and data to the documents than one run may add a parancsfájl több objektumot és adatot adott a dokumentumokhoz, mint amennyit egy futás hozzáadhat @msg {what}: the object is not a File or a Folder {what}: az objektum nem File és nem Folder +@msg {what}: the library {name} is not available {what}: a(z) {name} könyvtár nem érhető el +@msg {what} is not available yet {what} még nem érhető el +@msg {what}: the value {value} is not available yet {what}: a(z) {value} érték még nem érhető el +@msg {what}: the object is not an {class} object {what}: az objektum nem {class} objektum +@msg {what}: the XMP packet is not well-formed XMP {what}: az XMP-csomag nem jól formázott XMP +@msg {what}: the XMP data is too large {what}: az XMP-adatok túl nagyok +@msg {what}: {name} is not a valid property name {what}: a(z) {name} nem érvényes tulajdonságnév +@msg {what}: the text holds a character XML does not allow {what}: a szöveg olyan karaktert tartalmaz, amelyet az XML nem enged meg +@msg {what}: {name} is not an array {what}: a(z) {name} nem tömb +@msg {what}: {name} is not a simple property {what}: a(z) {name} nem egyszerű tulajdonság +@msg {what}: {name} is not a language alternative array {what}: a(z) {name} nem nyelvi alternatívák tömbje +@msg {what}: the array index {index} is out of range {what}: a(z) {index} tömbindex a tartományon kívül esik +@msg {what}: the namespace {uri} is not registered {what}: a(z) {uri} névtér nincs regisztrálva +@msg {what}: the file is closed {what}: a fájl be van zárva +@msg {what}: the file cannot be updated {what}: a fájl nem frissíthető @msg {what}: the count must be a finite number, 0 or more {what}: a darabszámnak véges számnak kell lennie, 0 vagy több @msg File.seek: the position must be a finite number File.seek: a pozíciónak véges számnak kell lennie @msg File.seek: the mode must be 0, 1 or 2 File.seek: a mód csak 0, 1 vagy 2 lehet diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..4e1170ad31 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -159,6 +159,21 @@ @msg the script passed more data to and from commands than one run may pass skrip mengirim lebih banyak data ke dan dari perintah daripada yang boleh dikirim satu proses @msg the script added more objects and data to the documents than one run may add skrip menambahkan lebih banyak objek dan data ke dokumen daripada yang boleh ditambahkan satu proses @msg {what}: the object is not a File or a Folder {what}: objek bukan File atau Folder +@msg {what}: the library {name} is not available {what}: pustaka {name} tidak tersedia +@msg {what} is not available yet {what} belum tersedia +@msg {what}: the value {value} is not available yet {what}: nilai {value} belum tersedia +@msg {what}: the object is not an {class} object {what}: objek bukan objek {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: paket XMP bukan XMP yang tersusun dengan benar +@msg {what}: the XMP data is too large {what}: data XMP terlalu besar +@msg {what}: {name} is not a valid property name {what}: {name} bukan nama properti yang valid +@msg {what}: the text holds a character XML does not allow {what}: teks berisi karakter yang tidak diizinkan XML +@msg {what}: {name} is not an array {what}: {name} bukan larik +@msg {what}: {name} is not a simple property {what}: {name} bukan properti sederhana +@msg {what}: {name} is not a language alternative array {what}: {name} bukan larik alternatif bahasa +@msg {what}: the array index {index} is out of range {what}: indeks larik {index} di luar rentang +@msg {what}: the namespace {uri} is not registered {what}: ruang nama {uri} tidak terdaftar +@msg {what}: the file is closed {what}: berkas tertutup +@msg {what}: the file cannot be updated {what}: berkas tidak dapat diperbarui @msg {what}: the count must be a finite number, 0 or more {what}: jumlah harus berupa angka berhingga, 0 atau lebih @msg File.seek: the position must be a finite number File.seek: posisi harus berupa angka berhingga @msg File.seek: the mode must be 0, 1 or 2 File.seek: mode harus 0, 1 atau 2 diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..3638fab939 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5091,6 +5091,21 @@ liquify-list-end {0}, {1} {0} e {1} @msg the script passed more data to and from commands than one run may pass lo script ha passato ai comandi e dai comandi più dati di quanti ne possa passare un'esecuzione @msg the script added more objects and data to the documents than one run may add lo script ha aggiunto ai documenti più oggetti e dati di quanti ne possa aggiungere un'esecuzione @msg {what}: the object is not a File or a Folder {what}: l'oggetto non è un File né un Folder +@msg {what}: the library {name} is not available {what}: la libreria {name} non è disponibile +@msg {what} is not available yet {what} non è ancora disponibile +@msg {what}: the value {value} is not available yet {what}: il valore {value} non è ancora disponibile +@msg {what}: the object is not an {class} object {what}: l'oggetto non è un oggetto {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: il pacchetto XMP non è XMP ben formato +@msg {what}: the XMP data is too large {what}: i dati XMP sono troppo grandi +@msg {what}: {name} is not a valid property name {what}: {name} non è un nome di proprietà valido +@msg {what}: the text holds a character XML does not allow {what}: il testo contiene un carattere che XML non consente +@msg {what}: {name} is not an array {what}: {name} non è un array +@msg {what}: {name} is not a simple property {what}: {name} non è una proprietà semplice +@msg {what}: {name} is not a language alternative array {what}: {name} non è un array di alternative di lingua +@msg {what}: the array index {index} is out of range {what}: l'indice di array {index} è fuori intervallo +@msg {what}: the namespace {uri} is not registered {what}: lo spazio dei nomi {uri} non è registrato +@msg {what}: the file is closed {what}: il file è chiuso +@msg {what}: the file cannot be updated {what}: il file non può essere aggiornato @msg {what}: the count must be a finite number, 0 or more {what}: il conteggio deve essere un numero finito, 0 o più @msg File.seek: the position must be a finite number File.seek: la posizione deve essere un numero finito @msg File.seek: the mode must be 0, 1 or 2 File.seek: la modalità deve essere 0, 1 o 2 diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..d40d4202d1 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5917,6 +5917,21 @@ liquify-list-end {0}, {1} {0}、{1} @msg the script passed more data to and from commands than one run may pass スクリプトが 1 回の実行で許されるより多くのデータをコマンドとやり取りしました @msg the script added more objects and data to the documents than one run may add スクリプトが 1 回の実行で許されるより多くのオブジェクトとデータをドキュメントに追加しました @msg {what}: the object is not a File or a Folder {what}: オブジェクトは File でも Folder でもありません +@msg {what}: the library {name} is not available {what}: ライブラリ {name} は利用できません +@msg {what} is not available yet {what} はまだ利用できません +@msg {what}: the value {value} is not available yet {what}: 値 {value} はまだ利用できません +@msg {what}: the object is not an {class} object {what}: オブジェクトは {class} オブジェクトではありません +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP パケットが整形式の XMP ではありません +@msg {what}: the XMP data is too large {what}: XMP データが大きすぎます +@msg {what}: {name} is not a valid property name {what}: {name} は有効なプロパティ名ではありません +@msg {what}: the text holds a character XML does not allow {what}: テキストに XML で使えない文字が含まれています +@msg {what}: {name} is not an array {what}: {name} は配列ではありません +@msg {what}: {name} is not a simple property {what}: {name} は単純なプロパティではありません +@msg {what}: {name} is not a language alternative array {what}: {name} は言語の代替配列ではありません +@msg {what}: the array index {index} is out of range {what}: 配列のインデックス {index} が範囲外です +@msg {what}: the namespace {uri} is not registered {what}: 名前空間 {uri} は登録されていません +@msg {what}: the file is closed {what}: ファイルは閉じています +@msg {what}: the file cannot be updated {what}: ファイルを更新できません @msg {what}: the count must be a finite number, 0 or more {what}: 数は 0 以上の有限の数値にしてください @msg File.seek: the position must be a finite number File.seek: 位置は有限の数値にしてください @msg File.seek: the mode must be 0, 1 or 2 File.seek: モードは 0, 1 または 2 にしてください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..48372764c1 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8586,6 +8586,21 @@ liquify-list-end {0}, {1} {0} და {1} @msg the script passed more data to and from commands than one run may pass სკრიპტმა ბრძანებებს და ბრძანებებიდან იმაზე მეტი მონაცემი გადასცა, ვიდრე ერთ გაშვებას შეუძლია @msg the script added more objects and data to the documents than one run may add სკრიპტმა დოკუმენტებს იმაზე მეტი ობიექტი და მონაცემი დაამატა, ვიდრე ერთ გაშვებას შეუძლია @msg {what}: the object is not a File or a Folder {what}: ობიექტი არც File-ია და არც Folder +@msg {what}: the library {name} is not available {what}: ბიბლიოთეკა {name} მიუწვდომელია +@msg {what} is not available yet {what} ჯერ მიუწვდომელია +@msg {what}: the value {value} is not available yet {what}: მნიშვნელობა {value} ჯერ მიუწვდომელია +@msg {what}: the object is not an {class} object {what}: ობიექტი არ არის {class} ობიექტი +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP პაკეტი არ არის სწორად აგებული XMP +@msg {what}: the XMP data is too large {what}: XMP მონაცემები ზედმეტად დიდია +@msg {what}: {name} is not a valid property name {what}: {name} არ არის თვისების სწორი სახელი +@msg {what}: the text holds a character XML does not allow {what}: ტექსტი შეიცავს სიმბოლოს, რომელსაც XML არ უშვებს +@msg {what}: {name} is not an array {what}: {name} არ არის მასივი +@msg {what}: {name} is not a simple property {what}: {name} არ არის მარტივი თვისება +@msg {what}: {name} is not a language alternative array {what}: {name} არ არის ენობრივი ალტერნატივების მასივი +@msg {what}: the array index {index} is out of range {what}: მასივის ინდექსი {index} დიაპაზონს გარეთაა +@msg {what}: the namespace {uri} is not registered {what}: სახელთა სივრცე {uri} არ არის რეგისტრირებული +@msg {what}: the file is closed {what}: ფაილი დახურულია +@msg {what}: the file cannot be updated {what}: ფაილის განახლება შეუძლებელია @msg {what}: the count must be a finite number, 0 or more {what}: რაოდენობა უნდა იყოს სასრული რიცხვი, 0 ან მეტი @msg File.seek: the position must be a finite number File.seek: პოზიცია უნდა იყოს სასრული რიცხვი @msg File.seek: the mode must be 0, 1 or 2 File.seek: რეჟიმი უნდა იყოს 0, 1 ან 2 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..3e85928817 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5846,6 +5846,21 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg the script passed more data to and from commands than one run may pass 스크립트가 한 번의 실행에 허용된 것보다 많은 데이터를 명령과 주고받았습니다 @msg the script added more objects and data to the documents than one run may add 스크립트가 한 번의 실행에 허용된 것보다 많은 객체와 데이터를 문서에 추가했습니다 @msg {what}: the object is not a File or a Folder {what}: 객체가 File도 Folder도 아닙니다 +@msg {what}: the library {name} is not available {what}: 라이브러리 {name}을(를) 사용할 수 없습니다 +@msg {what} is not available yet {what}은(는) 아직 사용할 수 없습니다 +@msg {what}: the value {value} is not available yet {what}: 값 {value}은(는) 아직 사용할 수 없습니다 +@msg {what}: the object is not an {class} object {what}: 객체가 {class} 객체가 아닙니다 +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP 패킷이 올바른 형식의 XMP가 아닙니다 +@msg {what}: the XMP data is too large {what}: XMP 데이터가 너무 큽니다 +@msg {what}: {name} is not a valid property name {what}: {name}은(는) 올바른 속성 이름이 아닙니다 +@msg {what}: the text holds a character XML does not allow {what}: 텍스트에 XML이 허용하지 않는 문자가 있습니다 +@msg {what}: {name} is not an array {what}: {name}은(는) 배열이 아닙니다 +@msg {what}: {name} is not a simple property {what}: {name}은(는) 단순 속성이 아닙니다 +@msg {what}: {name} is not a language alternative array {what}: {name}은(는) 언어 대체 배열이 아닙니다 +@msg {what}: the array index {index} is out of range {what}: 배열 인덱스 {index}이(가) 범위를 벗어났습니다 +@msg {what}: the namespace {uri} is not registered {what}: 네임스페이스 {uri}이(가) 등록되지 않았습니다 +@msg {what}: the file is closed {what}: 파일이 닫혀 있습니다 +@msg {what}: the file cannot be updated {what}: 파일을 업데이트할 수 없습니다 @msg {what}: the count must be a finite number, 0 or more {what}: 개수는 0 이상의 유한한 숫자여야 합니다 @msg File.seek: the position must be a finite number File.seek: 위치는 유한한 숫자여야 합니다 @msg File.seek: the mode must be 0, 1 or 2 File.seek: 모드는 0, 1 또는 2여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..b23412f1ec 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -205,6 +205,21 @@ liquify-list-end {0}, {1} {0} en {1} @msg the script passed more data to and from commands than one run may pass het script heeft meer gegevens van en naar opdrachten doorgegeven dan één uitvoering mag doorgeven @msg the script added more objects and data to the documents than one run may add het script heeft meer objecten en gegevens aan de documenten toegevoegd dan één uitvoering mag toevoegen @msg {what}: the object is not a File or a Folder {what}: het object is geen File of Folder +@msg {what}: the library {name} is not available {what}: de bibliotheek {name} is niet beschikbaar +@msg {what} is not available yet {what} is nog niet beschikbaar +@msg {what}: the value {value} is not available yet {what}: de waarde {value} is nog niet beschikbaar +@msg {what}: the object is not an {class} object {what}: het object is geen {class}-object +@msg {what}: the XMP packet is not well-formed XMP {what}: het XMP-pakket is geen goed gevormde XMP +@msg {what}: the XMP data is too large {what}: de XMP-gegevens zijn te groot +@msg {what}: {name} is not a valid property name {what}: {name} is geen geldige eigenschapsnaam +@msg {what}: the text holds a character XML does not allow {what}: de tekst bevat een teken dat XML niet toestaat +@msg {what}: {name} is not an array {what}: {name} is geen array +@msg {what}: {name} is not a simple property {what}: {name} is geen eenvoudige eigenschap +@msg {what}: {name} is not a language alternative array {what}: {name} is geen array van taalalternatieven +@msg {what}: the array index {index} is out of range {what}: de array-index {index} valt buiten het bereik +@msg {what}: the namespace {uri} is not registered {what}: de naamruimte {uri} is niet geregistreerd +@msg {what}: the file is closed {what}: het bestand is gesloten +@msg {what}: the file cannot be updated {what}: het bestand kan niet worden bijgewerkt @msg {what}: the count must be a finite number, 0 or more {what}: het aantal moet een eindig getal zijn, 0 of meer @msg File.seek: the position must be a finite number File.seek: de positie moet een eindig getal zijn @msg File.seek: the mode must be 0, 1 or 2 File.seek: de modus moet 0, 1 of 2 zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..d12a0430d9 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5196,6 +5196,21 @@ liquify-list-end {0}, {1} {0} i {1} @msg the script passed more data to and from commands than one run may pass skrypt przekazał do poleceń i z poleceń więcej danych, niż może przekazać jedno uruchomienie @msg the script added more objects and data to the documents than one run may add skrypt dodał do dokumentów więcej obiektów i danych, niż może dodać jedno uruchomienie @msg {what}: the object is not a File or a Folder {what}: obiekt nie jest ani File, ani Folder +@msg {what}: the library {name} is not available {what}: biblioteka {name} jest niedostępna +@msg {what} is not available yet {what} nie jest jeszcze dostępne +@msg {what}: the value {value} is not available yet {what}: wartość {value} nie jest jeszcze dostępna +@msg {what}: the object is not an {class} object {what}: obiekt nie jest obiektem {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: pakiet XMP nie jest poprawnie zbudowanym XMP +@msg {what}: the XMP data is too large {what}: dane XMP są za duże +@msg {what}: {name} is not a valid property name {what}: {name} nie jest prawidłową nazwą właściwości +@msg {what}: the text holds a character XML does not allow {what}: tekst zawiera znak niedozwolony w XML +@msg {what}: {name} is not an array {what}: {name} nie jest tablicą +@msg {what}: {name} is not a simple property {what}: {name} nie jest prostą właściwością +@msg {what}: {name} is not a language alternative array {what}: {name} nie jest tablicą alternatyw językowych +@msg {what}: the array index {index} is out of range {what}: indeks tablicy {index} jest poza zakresem +@msg {what}: the namespace {uri} is not registered {what}: przestrzeń nazw {uri} nie jest zarejestrowana +@msg {what}: the file is closed {what}: plik jest zamknięty +@msg {what}: the file cannot be updated {what}: nie można zaktualizować pliku @msg {what}: the count must be a finite number, 0 or more {what}: liczba musi być liczbą skończoną, 0 lub większą @msg File.seek: the position must be a finite number File.seek: pozycja musi być liczbą skończoną @msg File.seek: the mode must be 0, 1 or 2 File.seek: tryb musi wynosić 0, 1 lub 2 diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..868a243cef 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6235,6 +6235,21 @@ liquify-list-end {0}, {1} {0} e {1} @msg the script passed more data to and from commands than one run may pass o script passou mais dados para os comandos e a partir deles do que uma execução pode passar @msg the script added more objects and data to the documents than one run may add o script adicionou aos documentos mais objetos e dados do que uma execução pode adicionar @msg {what}: the object is not a File or a Folder {what}: o objeto não é um File nem um Folder +@msg {what}: the library {name} is not available {what}: a biblioteca {name} não está disponível +@msg {what} is not available yet {what} ainda não está disponível +@msg {what}: the value {value} is not available yet {what}: o valor {value} ainda não está disponível +@msg {what}: the object is not an {class} object {what}: o objeto não é um objeto {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: o pacote XMP não é um XMP bem formado +@msg {what}: the XMP data is too large {what}: os dados XMP são grandes demais +@msg {what}: {name} is not a valid property name {what}: {name} não é um nome de propriedade válido +@msg {what}: the text holds a character XML does not allow {what}: o texto contém um caractere que o XML não permite +@msg {what}: {name} is not an array {what}: {name} não é uma matriz +@msg {what}: {name} is not a simple property {what}: {name} não é uma propriedade simples +@msg {what}: {name} is not a language alternative array {what}: {name} não é uma matriz de alternativas de idioma +@msg {what}: the array index {index} is out of range {what}: o índice de matriz {index} está fora do intervalo +@msg {what}: the namespace {uri} is not registered {what}: o namespace {uri} não está registrado +@msg {what}: the file is closed {what}: o arquivo está fechado +@msg {what}: the file cannot be updated {what}: o arquivo não pode ser atualizado @msg {what}: the count must be a finite number, 0 or more {what}: a contagem deve ser um número finito, 0 ou mais @msg File.seek: the position must be a finite number File.seek: a posição deve ser um número finito @msg File.seek: the mode must be 0, 1 or 2 File.seek: o modo deve ser 0, 1 ou 2 diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..9af201db91 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5067,6 +5067,21 @@ liquify-list-end {0}, {1} {0} и {1} @msg the script passed more data to and from commands than one run may pass скрипт передал командам и получил от них больше данных, чем разрешено одному запуску @msg the script added more objects and data to the documents than one run may add скрипт добавил в документы больше объектов и данных, чем разрешено одному запуску @msg {what}: the object is not a File or a Folder {what}: объект не является ни File, ни Folder +@msg {what}: the library {name} is not available {what}: библиотека {name} недоступна +@msg {what} is not available yet {what} пока недоступно +@msg {what}: the value {value} is not available yet {what}: значение {value} пока недоступно +@msg {what}: the object is not an {class} object {what}: объект не является объектом {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: пакет XMP не является правильно построенным XMP +@msg {what}: the XMP data is too large {what}: данные XMP слишком велики +@msg {what}: {name} is not a valid property name {what}: {name} не является допустимым именем свойства +@msg {what}: the text holds a character XML does not allow {what}: текст содержит символ, недопустимый в XML +@msg {what}: {name} is not an array {what}: {name} не является массивом +@msg {what}: {name} is not a simple property {what}: {name} не является простым свойством +@msg {what}: {name} is not a language alternative array {what}: {name} не является массивом языковых вариантов +@msg {what}: the array index {index} is out of range {what}: индекс массива {index} вне диапазона +@msg {what}: the namespace {uri} is not registered {what}: пространство имен {uri} не зарегистрировано +@msg {what}: the file is closed {what}: файл закрыт +@msg {what}: the file cannot be updated {what}: файл нельзя обновить @msg {what}: the count must be a finite number, 0 or more {what}: количество должно быть конечным числом, 0 или больше @msg File.seek: the position must be a finite number File.seek: позиция должна быть конечным числом @msg File.seek: the mode must be 0, 1 or 2 File.seek: режим должен быть 0, 1 или 2 diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..c69017b569 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4942,6 +4942,21 @@ liquify-list-end {0}, {1} {0} och {1} @msg the script passed more data to and from commands than one run may pass skriptet skickade mer data till och från kommandon än en körning får skicka @msg the script added more objects and data to the documents than one run may add skriptet lade till fler objekt och mer data i dokumenten än en körning får lägga till @msg {what}: the object is not a File or a Folder {what}: objektet är varken en File eller en Folder +@msg {what}: the library {name} is not available {what}: biblioteket {name} är inte tillgängligt +@msg {what} is not available yet {what} är inte tillgängligt än +@msg {what}: the value {value} is not available yet {what}: värdet {value} är inte tillgängligt än +@msg {what}: the object is not an {class} object {what}: objektet är inte ett {class}-objekt +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP-paketet är inte välformad XMP +@msg {what}: the XMP data is too large {what}: XMP-data är för stora +@msg {what}: {name} is not a valid property name {what}: {name} är inte ett giltigt egenskapsnamn +@msg {what}: the text holds a character XML does not allow {what}: texten innehåller ett tecken som XML inte tillåter +@msg {what}: {name} is not an array {what}: {name} är inte en matris +@msg {what}: {name} is not a simple property {what}: {name} är inte en enkel egenskap +@msg {what}: {name} is not a language alternative array {what}: {name} är inte en matris med språkalternativ +@msg {what}: the array index {index} is out of range {what}: matrisindexet {index} ligger utanför intervallet +@msg {what}: the namespace {uri} is not registered {what}: namnrymden {uri} är inte registrerad +@msg {what}: the file is closed {what}: filen är stängd +@msg {what}: the file cannot be updated {what}: filen kan inte uppdateras @msg {what}: the count must be a finite number, 0 or more {what}: antalet måste vara ett ändligt tal, 0 eller mer @msg File.seek: the position must be a finite number File.seek: positionen måste vara ett ändligt tal @msg File.seek: the mode must be 0, 1 or 2 File.seek: läget måste vara 0, 1 eller 2 diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..59fa066b58 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4789,6 +4789,21 @@ liquify-list-end {0}, {1} {0} ve {1} @msg the script passed more data to and from commands than one run may pass betik, komutlara ve komutlardan bir çalıştırmanın aktarabileceğinden daha fazla veri aktardı @msg the script added more objects and data to the documents than one run may add betik, belgelere bir çalıştırmanın ekleyebileceğinden daha fazla nesne ve veri ekledi @msg {what}: the object is not a File or a Folder {what}: nesne ne File ne de Folder +@msg {what}: the library {name} is not available {what}: {name} kitaplığı kullanılamıyor +@msg {what} is not available yet {what} henüz kullanılamıyor +@msg {what}: the value {value} is not available yet {what}: {value} değeri henüz kullanılamıyor +@msg {what}: the object is not an {class} object {what}: nesne bir {class} nesnesi değil +@msg {what}: the XMP packet is not well-formed XMP {what}: XMP paketi düzgün biçimli XMP değil +@msg {what}: the XMP data is too large {what}: XMP verileri çok büyük +@msg {what}: {name} is not a valid property name {what}: {name} geçerli bir özellik adı değil +@msg {what}: the text holds a character XML does not allow {what}: metin XML'in izin vermediği bir karakter içeriyor +@msg {what}: {name} is not an array {what}: {name} bir dizi değil +@msg {what}: {name} is not a simple property {what}: {name} basit bir özellik değil +@msg {what}: {name} is not a language alternative array {what}: {name} bir dil alternatifleri dizisi değil +@msg {what}: the array index {index} is out of range {what}: {index} dizi dizini aralık dışında +@msg {what}: the namespace {uri} is not registered {what}: {uri} ad alanı kayıtlı değil +@msg {what}: the file is closed {what}: dosya kapalı +@msg {what}: the file cannot be updated {what}: dosya güncellenemiyor @msg {what}: the count must be a finite number, 0 or more {what}: sayı 0 veya daha büyük, sonlu bir sayı olmalıdır @msg File.seek: the position must be a finite number File.seek: konum sonlu bir sayı olmalıdır @msg File.seek: the mode must be 0, 1 or 2 File.seek: mod 0, 1 veya 2 olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..dcde17615c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5075,6 +5075,21 @@ liquify-list-end {0}, {1} {0} і {1} @msg the script passed more data to and from commands than one run may pass скрипт передав командам і отримав від них більше даних, ніж дозволено одному запуску @msg the script added more objects and data to the documents than one run may add скрипт додав до документів більше об'єктів і даних, ніж дозволено одному запуску @msg {what}: the object is not a File or a Folder {what}: об'єкт не є ні File, ні Folder +@msg {what}: the library {name} is not available {what}: бібліотека {name} недоступна +@msg {what} is not available yet {what} поки що недоступне +@msg {what}: the value {value} is not available yet {what}: значення {value} поки що недоступне +@msg {what}: the object is not an {class} object {what}: об'єкт не є об'єктом {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: пакет XMP не є правильно побудованим XMP +@msg {what}: the XMP data is too large {what}: дані XMP завеликі +@msg {what}: {name} is not a valid property name {what}: {name} не є допустимою назвою властивості +@msg {what}: the text holds a character XML does not allow {what}: текст містить символ, який XML не дозволяє +@msg {what}: {name} is not an array {what}: {name} не є масивом +@msg {what}: {name} is not a simple property {what}: {name} не є простою властивістю +@msg {what}: {name} is not a language alternative array {what}: {name} не є масивом мовних варіантів +@msg {what}: the array index {index} is out of range {what}: індекс масиву {index} поза діапазоном +@msg {what}: the namespace {uri} is not registered {what}: простір імен {uri} не зареєстровано +@msg {what}: the file is closed {what}: файл закрито +@msg {what}: the file cannot be updated {what}: файл неможливо оновити @msg {what}: the count must be a finite number, 0 or more {what}: кількість має бути скінченним числом, 0 або більше @msg File.seek: the position must be a finite number File.seek: позиція має бути скінченним числом @msg File.seek: the mode must be 0, 1 or 2 File.seek: режим має бути 0, 1 або 2 diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..02d2aa1ff4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5566,6 +5566,21 @@ liquify-list-end {0}, {1} {0} và {1} @msg the script passed more data to and from commands than one run may pass tập lệnh đã truyền đến và từ các lệnh nhiều dữ liệu hơn mức một lần chạy được phép @msg the script added more objects and data to the documents than one run may add tập lệnh đã thêm vào tài liệu nhiều đối tượng và dữ liệu hơn mức một lần chạy được phép @msg {what}: the object is not a File or a Folder {what}: đối tượng không phải File cũng không phải Folder +@msg {what}: the library {name} is not available {what}: thư viện {name} không khả dụng +@msg {what} is not available yet {what} chưa khả dụng +@msg {what}: the value {value} is not available yet {what}: giá trị {value} chưa khả dụng +@msg {what}: the object is not an {class} object {what}: đối tượng không phải đối tượng {class} +@msg {what}: the XMP packet is not well-formed XMP {what}: gói XMP không phải XMP đúng định dạng +@msg {what}: the XMP data is too large {what}: dữ liệu XMP quá lớn +@msg {what}: {name} is not a valid property name {what}: {name} không phải tên thuộc tính hợp lệ +@msg {what}: the text holds a character XML does not allow {what}: văn bản chứa ký tự mà XML không cho phép +@msg {what}: {name} is not an array {what}: {name} không phải mảng +@msg {what}: {name} is not a simple property {what}: {name} không phải thuộc tính đơn +@msg {what}: {name} is not a language alternative array {what}: {name} không phải mảng phương án ngôn ngữ +@msg {what}: the array index {index} is out of range {what}: chỉ số mảng {index} nằm ngoài phạm vi +@msg {what}: the namespace {uri} is not registered {what}: không gian tên {uri} chưa được đăng ký +@msg {what}: the file is closed {what}: tệp đã đóng +@msg {what}: the file cannot be updated {what}: không thể cập nhật tệp @msg {what}: the count must be a finite number, 0 or more {what}: số lượng phải là một số hữu hạn, 0 trở lên @msg File.seek: the position must be a finite number File.seek: vị trí phải là một số hữu hạn @msg File.seek: the mode must be 0, 1 or 2 File.seek: chế độ phải là 0, 1 hoặc 2 diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..e20c89b2f1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5582,6 +5582,21 @@ liquify-list-end {0}, {1} {0}和{1} @msg the script passed more data to and from commands than one run may pass 脚本与命令之间传递的数据超过了一次运行允许的数量 @msg the script added more objects and data to the documents than one run may add 脚本向文档添加的对象和数据超过了一次运行允许的数量 @msg {what}: the object is not a File or a Folder {what}:该对象既不是 File 也不是 Folder +@msg {what}: the library {name} is not available {what}:库 {name} 不可用 +@msg {what} is not available yet {what} 尚不可用 +@msg {what}: the value {value} is not available yet {what}:值 {value} 尚不可用 +@msg {what}: the object is not an {class} object {what}:该对象不是 {class} 对象 +@msg {what}: the XMP packet is not well-formed XMP {what}:XMP 数据包不是格式正确的 XMP +@msg {what}: the XMP data is too large {what}:XMP 数据过大 +@msg {what}: {name} is not a valid property name {what}:{name} 不是有效的属性名称 +@msg {what}: the text holds a character XML does not allow {what}:文本包含 XML 不允许的字符 +@msg {what}: {name} is not an array {what}:{name} 不是数组 +@msg {what}: {name} is not a simple property {what}:{name} 不是简单属性 +@msg {what}: {name} is not a language alternative array {what}:{name} 不是语言替代数组 +@msg {what}: the array index {index} is out of range {what}:数组索引 {index} 超出范围 +@msg {what}: the namespace {uri} is not registered {what}:命名空间 {uri} 未注册 +@msg {what}: the file is closed {what}:文件已关闭 +@msg {what}: the file cannot be updated {what}:文件无法更新 @msg {what}: the count must be a finite number, 0 or more {what}:数量必须是 0 或更大的有限数 @msg File.seek: the position must be a finite number File.seek:位置必须是有限数 @msg File.seek: the mode must be 0, 1 or 2 File.seek:模式必须是 0, 1 或 2 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..c18488af0e 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2928,6 +2928,21 @@ liquify-list-end {0}, {1} {0}和{1} @msg the script passed more data to and from commands than one run may pass 指令碼與命令之間傳遞的資料超過一次執行允許的數量 @msg the script added more objects and data to the documents than one run may add 指令碼加入文件的物件和資料超過一次執行允許的數量 @msg {what}: the object is not a File or a Folder {what}:此物件既不是 File 也不是 Folder +@msg {what}: the library {name} is not available {what}:程式庫 {name} 無法使用 +@msg {what} is not available yet {what} 尚無法使用 +@msg {what}: the value {value} is not available yet {what}:值 {value} 尚無法使用 +@msg {what}: the object is not an {class} object {what}:此物件不是 {class} 物件 +@msg {what}: the XMP packet is not well-formed XMP {what}:XMP 封包不是格式正確的 XMP +@msg {what}: the XMP data is too large {what}:XMP 資料過大 +@msg {what}: {name} is not a valid property name {what}:{name} 不是有效的屬性名稱 +@msg {what}: the text holds a character XML does not allow {what}:文字含有 XML 不允許的字元 +@msg {what}: {name} is not an array {what}:{name} 不是陣列 +@msg {what}: {name} is not a simple property {what}:{name} 不是簡單屬性 +@msg {what}: {name} is not a language alternative array {what}:{name} 不是語言替代陣列 +@msg {what}: the array index {index} is out of range {what}:陣列索引 {index} 超出範圍 +@msg {what}: the namespace {uri} is not registered {what}:命名空間 {uri} 未註冊 +@msg {what}: the file is closed {what}:檔案已關閉 +@msg {what}: the file cannot be updated {what}:檔案無法更新 @msg {what}: the count must be a finite number, 0 or more {what}:數量必須是 0 或更大的有限數 @msg File.seek: the position must be a finite number File.seek:位置必須是有限數 @msg File.seek: the mode must be 0, 1 or 2 File.seek:模式必須是 0, 1 或 2 diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..c4a5f73998 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3051,6 +3051,42 @@ VectorCraft writes files by these rules of its own: `Script file dialogs need a person to answer them`, and takes no kept grant. In the app, a file dialog inside a built-in's callback, a getter, a conversion or a file `$.evalFile` runs throws an error. +`new ExternalObject("lib:AdobeXMPScript")` defines the globals `XMPMeta`, `XMPFile` and `XMPConst` +([the help page](https://extendscript.docsforadobe.dev/scripting-xmp/xmpscript-object-reference/)); any other library +name throws `ExternalObject: the library … is not available`, and no native library is loaded. VectorCraft's own +rules for these objects: + +- `XMPMeta` reads a packet given as a string (`new XMPMeta(packet)`) and writes one with `serialize(options?)`, with + the packet wrapper unless `XMPConst.SERIALIZE_OMIT_PACKET_WRAPPER` is given. It has `getProperty`, `setProperty`, + `deleteProperty`, `doesPropertyExist`, `countArrayItems`, `getArrayItem`, `appendArrayItem`, `insertArrayItem`, + `setArrayItem`, `deleteArrayItem`, `doesArrayItemExist`, `getLocalizedText` and `setLocalizedText`, and the + functions `XMPMeta.registerNamespace`, `getNamespacePrefix` and `getNamespaceURI`. A path is a property name, + `prefix:name`, or either with `[n]` (from 1) or `[last()]` for an array item. Arrays hold simple items; a structure + or a value with qualifiers that a packet holds is kept as it was written, and `getProperty` gives its options. + Namespaces a packet declares are registered with the prefix it gives them, or `prefix_1_` when that prefix names + another namespace. +- `XMPFile(path, format, openFlags)` reads a file through the same places as `File`, so a path outside them, a + missing file and a file over 8 MiB throw the `File` messages (`Script file access denied`, `Script file does not + exist`, `Script file exceeds 8 MiB`). A `.xmp` file is read whole as its packet (a link counts by the file it leads to, + when it is opened and again when it is written); any other file, and any file with + `XMPConst.OPEN_USE_PACKET_SCANNING`, is scanned for its first UTF-8 packet and is read only. Only a `.xmp` file + opened with `XMPConst.OPEN_FOR_UPDATE`, without packet scanning, takes `putXMP`, and opening one that way where + the script may not write throws `Script file access denied`; other files open read only with that flag. + After `putXMP`, `closeFile()` writes the packet in + UTF-8 through a temporary file in the same folder when the script may write there, otherwise straight to the file; + when no temporary name is free, nothing is written. A failed write throws and keeps the file open with its + packet. While an open `File` of the same file holds changes it has not written, `closeFile()` throws + `Script file could not be written` and the `File` keeps its changes. `getXMP`, `getPacketInfo`, `getFileInfo` and `canPutXMP` are available. An `XMPFile` is open only in the + run that opened it. +- A packet over 8 MiB, one that is not well-formed XML, one with a document type declaration or an undefined entity, + and one nested more than 64 elements deep throws. Members of the help page that are not built yet (iterators, + structure fields, qualifiers, aliases, sorting, byte-array packets and `XMPFile.getFormatInfo`) throw + `… is not available yet`, and so does a flag, format or path form that is not handled yet. + +```json +{"name":"run_command","arguments":{"command":"script.run","params":{"source":"new ExternalObject('lib:AdobeXMPScript'); var m = new XMPMeta(); m.setProperty(XMPConst.NS_DC, 'format', 'image/svg+xml'); vc.log(m.serialize());"}}} +``` + `script.grants {}` lists the kept grants: `{grants: [{script, sha256, code, path, write, folder}], file}`, with `code` the SHA-256 of each evaluated source (of its UTF-16 code units in little-endian order), `folder` true for a folder's grant, which covers everything in the folder (a file's grant covers its own path only, also when a folder later diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..60fb057207 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1044,6 +1044,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - Scripts: the `hidden` setter and `createAlias(target)` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/)), with setting `hidden`, `rename` and `remove` acting on an alias itself ([Using File and Folder objects](https://extendscript.docsforadobe.dev/file-system-access/using-file-and-folder-objects/)). VectorCraft's own rules: on Unix a name that starts with a dot is hidden, so setting `hidden` renames the file with one dot added or its leading dots taken off, and both names must be places the script may write; `createAlias` makes a symbolic link to the real path of a file the script may read, in a place it may write where nothing is, a link that leads nowhere included; a link is checked again each time it is used; on Windows both set `error` and change nothing. `crates/engine/src/tests/script_io.rs`. + - Scripts: `new ExternalObject("lib:AdobeXMPScript")` gives `XMPMeta`, `XMPFile` and `XMPConst` ([the help page](https://extendscript.docsforadobe.dev/scripting-xmp/xmpscript-object-reference/)): properties, arrays, language alternatives and namespaces read from a packet, changed and serialized, and a `.xmp` sidecar read and written with `getXMP`, `putXMP` and `closeFile`. VectorCraft's own rules: `XMPFile` reads and writes only where `File` may; other files are scanned for their packet and read only; a packet over 8 MiB or not well-formed throws; members not built yet (iterators, structure fields, qualifiers, aliases) throw that they are not available yet. `crates/js/src/xmp_tests.rs`, `crates/engine/src/tests/script_xmp.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. From 7fb823a4622f5a84b71e5ed392c23f5085baf761 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:40:13 -0800 Subject: [PATCH 012/193] Scripts: XMP namespaces have length limits and a byte budget XMPMeta.registerNamespace and packets that declare namespaces could add up to 4,096 namespaces of any length, held outside the script heap. - A namespace URI over 1,024 bytes and a prefix over 128 bytes, the `_n_` suffix included, throw "the XMP data is too large". - The registered namespaces hold at most 1 MiB together; a namespace past that throws the same error and is not registered. - Reading a packet takes fuel for the namespaces it copies. - Error messages hold at most the first 200 characters of a name, path, value or namespace the script gave. Tests: namespace_lengths_and_the_registry_budget_are_bounded, long_namespaces_from_scripts_and_packets_are_refused and error_messages_hold_a_bounded_part_of_the_script_text in crates/js/src/xmp_tests.rs. Docs: docs/mcp.md. --- crates/js/src/xmp.rs | 46 +++++++++++++++++++++--- crates/js/src/xmp_classes.rs | 21 ++++++++--- crates/js/src/xmp_tests.rs | 68 ++++++++++++++++++++++++++++++++++++ docs/mcp.md | 4 ++- 4 files changed, 130 insertions(+), 9 deletions(-) diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index e0a54bb30b..60d07d4cce 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -17,7 +17,9 @@ //! VectorCraft's own rules: a packet or a written packet holds at most [`MAX_BYTES`] bytes, //! elements nest at most 64 deep, a child of `rdf:RDF` other than `rdf:Description` makes the //! packet malformed, a property given twice keeps its first value, and [`find_packet`] finds only a -//! UTF-8 packet. +//! 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}; @@ -49,6 +51,14 @@ 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"; @@ -74,9 +84,11 @@ pub(crate) const ARRAY_IS_ALTTEXT: u32 = 0x1000; 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`]. + /// 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. + /// 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, @@ -228,6 +240,13 @@ pub(crate) struct Registry { /// 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 { @@ -237,11 +256,17 @@ impl Default for Registry { 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) @@ -254,12 +279,17 @@ impl Registry { /// 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. + /// 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 { if let Some(p) = self.prefix_of(uri) { return Ok(p.to_string()); } 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); @@ -273,6 +303,14 @@ impl Registry { 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); + } + self.bytes = bytes; self.prefixes.insert(uri.to_string(), prefix.clone()); self.uris.insert(prefix.clone(), uri.to_string()); Ok(prefix) diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index ab6c2a6174..0efd7fb53b 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -103,6 +103,7 @@ fn not_yet(i: &mut Interp, what: &str) -> Abrupt { } 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")) } @@ -110,26 +111,35 @@ 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::NotYet => not_handled(i, what, &name), } } 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")) } @@ -138,6 +148,7 @@ fn out_of_range(i: &mut Interp, what: &str, index: i64) -> Abrupt { } 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")) } @@ -224,7 +235,7 @@ fn record(i: &mut Interp, proto: Option, fields: Vec<(&'static str, Value fn external_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let name = text(i, &arg(args, 0))?; if name != LIBRARY { - let name: String = name.chars().take(200).collect(); + let name = shown(&name); let what = "ExternalObject"; return Err(i.throw(ErrorType::Error, &format!("{what}: the library {name} is not available"))); } @@ -297,7 +308,9 @@ fn new_meta(i: &mut Interp, meta: Meta) -> JsResult { /// The metadata of the packet `text`, read for `what`. fn parse_packet(i: &mut Interp, what: &str, text: &str) -> JsResult { - spend(i, text.len())?; + // Reading copies the realm's namespaces. + let copied = registry(i)?.bytes(); + spend(i, text.len().saturating_add(copied))?; let r = xmp::parse(text, registry(i)?); r.map_err(|e| xmp_error(i, what, e, "")) } @@ -1036,7 +1049,7 @@ fn packet_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { // 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())?; + spend(i, s.len().saturating_add(2 * scratch.bytes()))?; xmp::parse(&s, &mut scratch).map_err(|e| xmp_error(i, what, e, ""))?; Ok(s) } diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 5641ff77d7..653cd913e4 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -247,6 +247,74 @@ fn blank_values_and_failed_packets_keep_their_state() { 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()); + } +} + #[test] fn array_forms_follow_their_options() { assert_eq!(Form::from_options(0x200), Form::Bag); diff --git a/docs/mcp.md b/docs/mcp.md index c4a5f73998..a1c0de7c34 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3064,7 +3064,9 @@ rules for these objects: `prefix:name`, or either with `[n]` (from 1) or `[last()]` for an array item. Arrays hold simple items; a structure or a value with qualifiers that a packet holds is kept as it was written, and `getProperty` gives its options. Namespaces a packet declares are registered with the prefix it gives them, or `prefix_1_` when that prefix names - another namespace. + another namespace. At most 4,096 namespaces, holding at most 1 MiB together, are registered. A namespace URI over + 1,024 bytes, a prefix over 128 bytes, and a namespace past either limit throw `… the XMP data is too large`, both + from `registerNamespace` and from a packet that declares the namespace. - `XMPFile(path, format, openFlags)` reads a file through the same places as `File`, so a path outside them, a missing file and a file over 8 MiB throw the `File` messages (`Script file access denied`, `Script file does not exist`, `Script file exceeds 8 MiB`). A `.xmp` file is read whole as its packet (a link counts by the file it leads to, From 1a33ff7326f3a1354260d45feb04f3d66bdf4341 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:54:42 -0800 Subject: [PATCH 013/193] Scripts: XMP generic-language updates and packets that serialize too deep - setLocalizedText reads its generic language argument. With no item in the specific language and exactly one item in the generic language or a variant of it, that item changes, as the XMP Toolkit SDK's SetLocalizedText does (XMPCore/source/XMPMeta-GetSet.cpp); with several, the specific language is added. - A packet read from rdf:RDF alone could hold a value nested 64 elements deep that serialize() then wrote under x:xmpmeta, 65 deep, so the written packet did not read back. A value is now measured as deep as serialize() writes it, and one past 64 elements throws when the packet is read. Tests: localized_text_updates_a_single_generic_language_item and deeply_nested_values_read_back_after_serializing in crates/js/src/xmp_tests.rs. Docs: docs/mcp.md. --- crates/js/src/xmp.rs | 13 +++++++++++ crates/js/src/xmp_classes.rs | 44 +++++++++++++++++++++++------------- crates/js/src/xmp_tests.rs | 34 ++++++++++++++++++++++++++++ docs/mcp.md | 3 ++- 4 files changed, 77 insertions(+), 17 deletions(-) diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index 60d07d4cce..c81533b1f5 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -529,12 +529,25 @@ fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry) -> Result

MAX_DEPTH { + return Err(XmpError::TooLarge); + } other(p, &own, &children, scope, mark) }; scope.truncate(mark); Ok(Prop { ns, name: local.to_string(), value }) } +/// 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 }; diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 0efd7fb53b..0987011607 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -696,22 +696,25 @@ 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> { - let generic_match = |i: &&Item| { - !generic.is_empty() - && i.lang.as_deref().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'-') - }) - }; items .iter() .find(|i| same_lang(i.lang.as_deref(), specific)) - .or_else(|| items.iter().find(generic_match)) + .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()) } @@ -745,6 +748,7 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J let what = "XMPMeta.setLocalizedText"; let o = this_meta(i, &this, what)?; let (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)); @@ -763,15 +767,16 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J let grow = 2 * (64 + value.len() + specific.len()); change(i, o, grow, |m, _| { let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|p| &mut p.value) else { return }; - set_lang(items, &specific, value); + set_lang(items, &generic, &specific, value); })?; Ok(Value::Undefined) } -/// Sets the item of `items` in `specific` to `value`. 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. -fn set_lang(items: &mut Vec, specific: &str, value: String) { +/// 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. +fn set_lang(items: &mut Vec, generic: &str, specific: &str, value: String) { let default = items.iter().position(|i| same_lang(i.lang.as_deref(), "x-default")); if specific.eq_ignore_ascii_case("x-default") { match default { @@ -784,7 +789,14 @@ fn set_lang(items: &mut Vec, specific: &str, value: String) { } return; } - let old = items.iter().position(|i| same_lang(i.lang.as_deref(), specific)); + 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, diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 653cd913e4..872f338cab 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -315,6 +315,40 @@ fn error_messages_hold_a_bounded_part_of_the_script_text() { } } +/// 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 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"); +} + #[test] fn array_forms_follow_their_options() { assert_eq!(Form::from_options(0x200), Form::Bag); diff --git a/docs/mcp.md b/docs/mcp.md index a1c0de7c34..b61b5471ef 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3081,7 +3081,8 @@ rules for these objects: `Script file could not be written` and the `File` keeps its changes. `getXMP`, `getPacketInfo`, `getFileInfo` and `canPutXMP` are available. An `XMPFile` is open only in the run that opened it. - A packet over 8 MiB, one that is not well-formed XML, one with a document type declaration or an undefined entity, - and one nested more than 64 elements deep throws. Members of the help page that are not built yet (iterators, + and one nested more than 64 elements deep throws; a value is counted as deep as `serialize()` would write it, + under `x:xmpmeta`, `rdf:RDF` and `rdf:Description`. Members of the help page that are not built yet (iterators, structure fields, qualifiers, aliases, sorting, byte-array packets and `XMPFile.getFormatInfo`) throw `… is not available yet`, and so does a flag, format or path form that is not handled yet. From cac32433a99ef5aadaeb0a17b8f67e09292462f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:08:10 -0800 Subject: [PATCH 014/193] Scripts: XMP packets register the namespaces inside kept values A namespace declared only inside a structure, an array of structures or on a qualifier was not registered when the packet was read, so XMPMeta.getNamespacePrefix gave undefined for it. Reading a value that is kept as it was written now registers the namespaces its element and attribute names use, other than RDF and XML. Test: namespaces_inside_kept_values_are_registered in crates/js/src/xmp_tests.rs. --- crates/js/src/xmp.rs | 27 +++++++++++++++++++++++++++ crates/js/src/xmp_tests.rs | 13 +++++++++++++ 2 files changed, 40 insertions(+) diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index c81533b1f5..88663527c2 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -534,12 +534,39 @@ fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry) -> Result

MAX_DEPTH { return Err(XmpError::TooLarge); } + register_names(p, scope, registry)?; + register_nested(p, scope, registry)?; other(p, &own, &children, scope, mark) }; 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. +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 Some((ns, _)) = resolve(name, scope, element) else { continue }; + 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; diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 872f338cab..a6438aaf39 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -349,6 +349,19 @@ fn deeply_nested_values_read_back_after_serializing() { 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:"); +} + #[test] fn array_forms_follow_their_options() { assert_eq!(Form::from_options(0x200), Form::Bag); From b8bf41b7a93419541dc008a17f85649de587ce11 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:20:30 -0800 Subject: [PATCH 015/193] Scripts: an undeclared prefix inside a kept XMP value is malformed A structure or qualifier whose element or attribute used a prefix that nothing declared was read and then serialized with the prefix unbound. Such a packet is now refused as not well-formed XMP. Test: namespaces_inside_kept_values_are_registered in crates/js/src/xmp_tests.rs. --- crates/js/src/xmp.rs | 5 +++-- crates/js/src/xmp_classes.rs | 1 + crates/js/src/xmp_tests.rs | 6 ++++++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index 88663527c2..497cc7ca61 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -543,11 +543,12 @@ fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry) -> Result

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 Some((ns, _)) = resolve(name, scope, element) else { continue }; + 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))?; } diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 0987011607..11e2414d68 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -944,6 +944,7 @@ fn file_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult1", "x"] { + let packet = format!( + "{value}" + ); + assert_eq!(xmp::parse(&packet, &mut Registry::default()), Err(XmpError::Malformed), "an undeclared prefix in {value}"); + } } #[test] From 84acd52710ff9df56c24e64c5ba85378c01bdd3a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:36:05 -0800 Subject: [PATCH 016/193] Scripts: text beside an XMP array keeps the property as written A property holding text next to its rdf:Bag, rdf:Seq or rdf:Alt was read as an array of simple items, and serialize() dropped the text. Such a property is now kept as the XML it was written in. Test: text_beside_an_array_is_kept in crates/js/src/xmp_tests.rs. --- crates/js/src/xmp.rs | 2 +- crates/js/src/xmp_tests.rs | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index 497cc7ca61..d4973603d5 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -526,7 +526,7 @@ fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry) -> Result

Date: Sun, 22 Nov 2026 08:11:31 -0800 Subject: [PATCH 017/193] Scripts: a sidecar XMPFile replaces keeps its Unix permission bits closeFile() writes a sidecar through a new temporary file and renames it over the sidecar, so a 0600 sidecar became 0644 under a 022 umask. The temporary file now takes the sidecar's permission bits before the rename, as File.copy does for its target. Test: a_replaced_sidecar_keeps_its_permissions (Unix only) in crates/engine/src/tests/script_xmp.rs. --- crates/engine/src/script/files.rs | 13 ++++++++++--- crates/engine/src/tests/script_xmp.rs | 25 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index d22db3dc6a..e556449148 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1981,9 +1981,16 @@ fn xmp_write(host: &Host, a: &[Data]) -> Result { }; let r = write_temp(); drop(out); - let r = r.and_then(|()| std::fs::rename(&temp, &target)).inspect_err(|_| { - let _ = std::fs::remove_file(&temp); - }); + // The replacement keeps the sidecar's permission bits. On Windows the only permission is the + // read-only attribute, and a read-only temporary file could not be removed after a failed + // rename. + let permissions = if cfg!(unix) { std::fs::metadata(&target).map(|m| m.permissions()).ok() } else { None }; + let r = r + .and_then(|()| permissions.map_or(Ok(()), |p| std::fs::set_permissions(&temp, p))) + .and_then(|()| std::fs::rename(&temp, &target)) + .inspect_err(|_| { + let _ = std::fs::remove_file(&temp); + }); let changed = r.is_ok(); (r, changed) } else { diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs index a89efbc14f..b2c68e2b95 100644 --- a/crates/engine/src/tests/script_xmp.rs +++ b/crates/engine/src/tests/script_xmp.rs @@ -356,6 +356,31 @@ fn a_link_to_another_kind_of_file_is_not_written() { 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() { From 4a51aa4d4893b321861c0f1a569207b473f86868 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:24:53 -0800 Subject: [PATCH 018/193] Scripts: XMP properties in the RDF or XML namespace are refused setProperty and the other property members took a path in the RDF or XML namespace, and serialize() wrote a packet that XMPMeta could not read back. Such a path now throws "... is not a valid property name". Test: rdf_and_xml_namespaces_hold_no_properties in crates/js/src/xmp_tests.rs. --- crates/js/src/xmp_classes.rs | 4 ++++ crates/js/src/xmp_tests.rs | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 11e2414d68..aadfb83fcb 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -342,6 +342,10 @@ fn namespace(i: &mut Interp, v: &Value, what: &str) -> JsResult { fn target(i: &mut Interp, args: &[Value], at: usize, what: &str) -> JsResult<(String, String, Step)> { 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((ns, name, step)), diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 7995905dc8..9a821f7f3a 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -380,6 +380,22 @@ fn text_beside_an_array_is_kept() { 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"] { + assert_eq!( + thrown(&format!("new XMPMeta().setProperty({ns:?}, 'foo', 'x')")), + "Error: XMPMeta.setProperty: foo 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" + ); + } +} + #[test] fn array_forms_follow_their_options() { assert_eq!(Form::from_options(0x200), Form::Bag); From 72c4875990a8b01d04d147c7fccc2a7a95a5f4ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 10:44:46 -0800 Subject: [PATCH 019/193] Scripts: a script cannot change the state an XMPFile keeps An XMPFile kept its path, open flags and pending packet in writable, configurable properties, so a script could assign a packet to a file opened for reading and closeFile wrote it without checking the update flag or reading the packet. - The properties holding an XMPFile's state are not writable, enumerable or configurable, and the pending packet is one of them from the start. - The XMPMeta docs say that only the namespaces a packet's names use are registered, which is what reading a packet does. Test: a_script_cannot_change_the_state_of_an_xmp_file in crates/engine/src/tests/script_xmp.rs. Docs: docs/mcp.md. --- crates/engine/src/tests/script_xmp.rs | 25 +++++++++++++++++++++++++ crates/js/src/xmp.rs | 7 ++++--- crates/js/src/xmp_classes.rs | 5 ++++- docs/mcp.md | 9 +++++---- 4 files changed, 38 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs index b2c68e2b95..b839da8893 100644 --- a/crates/engine/src/tests/script_xmp.rs +++ b/crates/engine/src/tests/script_xmp.rs @@ -161,6 +161,31 @@ fn a_scanned_sidecar_is_read_only() { let _ = std::fs::remove_dir_all(base); } +/// The state an `XMPFile` keeps cannot be changed by the script: a sidecar opened for reading is +/// not written by `closeFile` after the script assigns, defines or deletes the properties that +/// hold the packet, the path and the open flags. +#[test] +fn a_script_cannot_change_the_state_of_an_xmp_file() { + let base = folder("state"); + 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\ + var x = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ); var out = [];\n\ + x.__vcXmpPending = 'not a packet'; x.__vcXmpFlags = XMPConst.OPEN_FOR_UPDATE;\n\ + try {{ Object.defineProperty(x, '__vcXmpPending', {{ value: 'not a packet' }}); out.push('defined'); }} catch (e) {{ out.push(e.name); }}\n\ + out.push(typeof x.__vcXmpPending, x.getFileInfo().openFlags == XMPConst.OPEN_FOR_READ);\n\ + x.closeFile(); out.push(delete x.__vcXmpPath); vc.log(out); vc.log(p);" + ), + ); + assert_eq!(log[0], json!(["TypeError", "undefined", true, false])); + let text = std::fs::read_to_string(log[1].as_str().unwrap()).unwrap(); + assert_eq!(text, PACKET); + let _ = std::fs::remove_dir_all(base); +} + /// A path outside the script's places, a missing file and a file opened for update where the run /// may not write are refused with the file access errors, and a malformed or huge packet with an /// error, never a fault. diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index d4973603d5..0348da2e16 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -10,9 +10,10 @@ //! 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. Namespaces a packet declares are added to -//! the realm's [`Registry`] with the prefix the packet gives them, or a new prefix when that one is -//! taken. +//! written back with the namespace declarations it uses. 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, a child of `rdf:RDF` other than `rdf:Description` makes the diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index aadfb83fcb..5733d28e9a 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -203,11 +203,13 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { }) } +/// Sets the slot `name` of `o` as a property that is not writable, enumerable or configurable, so +/// a script cannot assign, redefine or delete it. fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { 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: HIDDEN }) + i.define(o, key(name), Prop::Data { value, flags: 0 }) } /// A string value, charged to the heap. @@ -983,6 +985,7 @@ fn file_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult Date: Sun, 22 Nov 2026 11:09:01 -0800 Subject: [PATCH 020/193] Scripts: XMPFile methods take only XMPFile objects, and x-default updates its matches - XMPFile's methods refuse an object the XMPFile constructor did not make, so a plain object or one made from XMPFile.prototype with properties of the same names is not read or written as a file. - setLocalizedText for x-default also changes the items that had the text of the x-default item. Tests: a_script_cannot_change_the_state_of_an_xmp_file in crates/engine/src/tests/script_xmp.rs and localized_text_for_x_default_changes_the_items_that_matched_it in crates/js/src/xmp_tests.rs. --- crates/engine/src/tests/script_xmp.rs | 9 +++++++-- crates/js/src/heap.rs | 4 +++- crates/js/src/xmp_classes.rs | 25 +++++++++++++++++-------- crates/js/src/xmp_tests.rs | 11 +++++++++++ 4 files changed, 38 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs index b839da8893..6c68cadcff 100644 --- a/crates/engine/src/tests/script_xmp.rs +++ b/crates/engine/src/tests/script_xmp.rs @@ -163,7 +163,8 @@ fn a_scanned_sidecar_is_read_only() { /// The state an `XMPFile` keeps cannot be changed by the script: a sidecar opened for reading is /// not written by `closeFile` after the script assigns, defines or deletes the properties that -/// hold the packet, the path and the open flags. +/// hold the packet, the path and the open flags, or calls `closeFile` on another object that holds +/// properties of the same names, plain or made from `XMPFile.prototype`. #[test] fn a_script_cannot_change_the_state_of_an_xmp_file() { let base = folder("state"); @@ -177,10 +178,14 @@ fn a_script_cannot_change_the_state_of_an_xmp_file() { x.__vcXmpPending = 'not a packet'; x.__vcXmpFlags = XMPConst.OPEN_FOR_UPDATE;\n\ try {{ Object.defineProperty(x, '__vcXmpPending', {{ value: 'not a packet' }}); out.push('defined'); }} catch (e) {{ out.push(e.name); }}\n\ out.push(typeof x.__vcXmpPending, x.getFileInfo().openFlags == XMPConst.OPEN_FOR_READ);\n\ + [{{}}, Object.create(XMPFile.prototype)].forEach(function (fake) {{\n\ + fake.__vcXmpPath = p; fake.__vcXmpRun = x.__vcXmpRun; fake.__vcXmpOpen = true; fake.__vcXmpPending = 'not a packet';\n\ + try {{ XMPFile.prototype.closeFile.call(fake); out.push('closed'); }} catch (e) {{ out.push(e.name); }}\n\ + }});\n\ x.closeFile(); out.push(delete x.__vcXmpPath); vc.log(out); vc.log(p);" ), ); - assert_eq!(log[0], json!(["TypeError", "undefined", true, false])); + assert_eq!(log[0], json!(["TypeError", "undefined", true, "TypeError", "TypeError", false])); let text = std::fs::read_to_string(log[1].as_str().unwrap()).unwrap(); assert_eq!(text, PACKET); let _ = std::fs::remove_dir_all(base); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index fc665342dc..4e3cf3dd87 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -248,6 +248,8 @@ pub(crate) enum Class { XmlFilter(Box), /// An `XMPMeta` object and its metadata ([`crate::xmp_classes`]). Xmp(Box), + /// An object the `XMPFile` constructor made ([`crate::xmp_classes`]). + XmpFile, } /// What an XML value is. @@ -311,7 +313,7 @@ impl Class { Class::XmlList(_) => "XMLList", Class::Namespace(_) => "Namespace", Class::QName { .. } => "QName", - Class::XmlFilter(_) | Class::Xmp(_) => "Object", + Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile => "Object", Class::Math => "Math", Class::Json => "JSON", Class::Ordinary | Class::ForIn(_) => "Object", diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 5733d28e9a..3357336a5f 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -770,7 +770,15 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J meta_of(i, o)?.find(&ns, &name).unwrap_or(0) } }; - let grow = 2 * (64 + value.len() + specific.len()); + // An item and the `x-default` item change, or every item with the text of the `x-default` one. + let changed = match meta_of(i, o)?.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()); change(i, o, grow, |m, _| { let Some(xmp::Value::Array { items, .. }) = m.props.get_mut(at).map(|p| &mut p.value) else { return }; set_lang(items, &generic, &specific, value); @@ -781,14 +789,14 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J /// 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. +/// 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) { let default = items.iter().position(|i| same_lang(i.lang.as_deref(), "x-default")); if specific.eq_ignore_ascii_case("x-default") { - match default { - Some(d) => { - if let Some(item) = items.get_mut(d) { - item.text = value; + 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()) }), @@ -917,9 +925,10 @@ not_yet_fns! { // ---- XMPFile ---- -/// The `XMPFile` `this`, refused when it is not one. +/// 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); @@ -970,7 +979,7 @@ fn file_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult Date: Sun, 22 Nov 2026 11:15:46 -0800 Subject: [PATCH 021/193] Scripts: XMP item paths take no options, and alt-text needs a language on each item - setProperty with an array item path, such as list[1], and any option throws that the value is not available yet instead of setting the item and leaving the option out. - getLocalizedText and setLocalizedText throw that the array is not a language alternative array for an rdf:Alt with an item that has no xml:lang. Tests: bad_arguments_and_unbuilt_members_throw in crates/js/src/xmp_tests.rs. --- crates/js/src/xmp_classes.rs | 17 ++++++++++++++--- crates/js/src/xmp_tests.rs | 15 +++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 3357336a5f..964e9acf89 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -430,6 +430,8 @@ fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul } 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); } @@ -730,14 +732,23 @@ 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? +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| item.lang.is_some()), + _ => 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 (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, form, _)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; - if form != Form::Alt { + let Some((at, _, _)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; + 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 { @@ -762,7 +773,7 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J let value = xml_text(i, &arg(args, 4), what)?; let found = array_items(i, o, &ns, &name, what)?; let at = match found { - Some((_, form, _)) if form != Form::Alt => return Err(not_alt_text(i, what, &name)), + Some((at, _, _)) if !is_alt_text(i, o, at)? => return Err(not_alt_text(i, what, &name)), Some((at, _, _)) => at, None => { let prop = xmp::Prop { ns: ns.clone(), name: name.clone(), value: xmp::Value::Array { form: Form::Alt, items: Vec::new() } }; diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 96e864bec8..de94872808 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -141,6 +141,21 @@ fn bad_arguments_and_unbuilt_members_throw() { 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" From 7a96c6c0916c0dde6e2ffc74e1d4094599be6d87 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:44:03 -0800 Subject: [PATCH 022/193] Scripts: XMP packet scanning needs the wrapper id, and failed alt-text sets add nothing - A packet starts at a `. +const MAX_HEADER: usize = 256; /// The property is a URI (`rdf:resource`). pub(crate) const PROP_VALUE_IS_URI: u32 = 0x2; @@ -819,21 +822,36 @@ pub(crate) fn pad_size(packet: &str) -> usize { } /// The first UTF-8 packet in `bytes` that has both ends of its wrapper (XMP Specification Part 1, -/// 7.3), or `None`. A start with no end before the next start is skipped, and so is a trailer that -/// does not close before the next start. +/// 7.3), or `None`. A start is a ` Option { const BEGIN: &[u8] = b"").and_then(|close| head.get(..close)).unwrap_or_default(); + ids.iter().any(|id| head.windows(id.len()).any(|w| w == id.as_bytes())) + }; + // The first start from `from` that begins before `to`. + let start_in = |mut from: usize, to: usize| loop { + let at = find(from, to, BEGIN)?; + if is_header(at) { + return Some(at); + } + from = at + BEGIN.len(); + }; + let mut start = start_in(0, len)?; loop { let end_tag = find(start + BEGIN.len(), len, END)?; - while let Some(next) = find(start + BEGIN.len(), end_tag, BEGIN) { + while let Some(next) = start_in(start + BEGIN.len(), end_tag) { start = next; } let after = end_tag + END.len(); - let next = find(after, len, BEGIN); + let next = start_in(after, len); match find(after, next.unwrap_or(len), b"?>") { Some(close) => return Some(PacketSpan { start, end: close + 2, writeable: bytes.get(after + 1) == Some(&b'w') }), None => start = next?, diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 964e9acf89..9d7db14901 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -772,25 +772,29 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J } let value = xml_text(i, &arg(args, 4), what)?; let found = array_items(i, o, &ns, &name, what)?; - let at = match found { + // 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, _, _)) => at, - None => { - let prop = xmp::Prop { ns: ns.clone(), name: name.clone(), value: xmp::Value::Array { form: Form::Alt, items: Vec::new() } }; - change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop))?; - meta_of(i, o)?.find(&ns, &name).unwrap_or(0) - } + Some((at, _, _)) => (Some(at), None), + None => (None, Some(xmp::Prop { ns, 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 meta_of(i, o)?.props.get(at).map(|p| &p.value) { + 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()); + 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); })?; diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index de94872808..293b4d3157 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -211,6 +211,11 @@ fn packets_are_found_in_file_bytes() { let open_end = format!(" 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 @@ -344,6 +349,35 @@ fn localized_text_updates_a_single_generic_language_item() { 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 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; + } + if r.run("m.setLocalizedText(XMPConst.NS_DC, 'title', null, s, s);").is_ok() { + seen.push(format!("{step} set")); + break; + } + stopped += 1; + match r.run("m.doesPropertyExist(XMPConst.NS_DC, 'title')") { + Ok(v) => assert_eq!(v, JsValue::Bool(false), "heap step {step}"), + Err(e) => panic!("{e:?}"), + } + } + assert!(stopped > 0, "no heap limit stopped the change: {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() { diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a931d02068..e4271f7926 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6573,21 +6573,6 @@ liquify-list-end {0}, {1} {0} i {1} @msg the script passed more data to and from commands than one run may pass l'script ha passat més dades a les ordres i des de les ordres de les que pot passar una execució @msg the script added more objects and data to the documents than one run may add l'script ha afegit als documents més objectes i dades dels que pot afegir una execució @msg {what}: the object is not a File or a Folder {what}: l'objecte no és un File ni un Folder -@msg {what}: the library {name} is not available {what}: la biblioteca {name} no està disponible -@msg {what} is not available yet {what} encara no està disponible -@msg {what}: the value {value} is not available yet {what}: el valor {value} encara no està disponible -@msg {what}: the object is not an {class} object {what}: l'objecte no és un objecte {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: el paquet XMP no és XMP ben format -@msg {what}: the XMP data is too large {what}: les dades XMP són massa grans -@msg {what}: {name} is not a valid property name {what}: {name} no és un nom de propietat vàlid -@msg {what}: the text holds a character XML does not allow {what}: el text conté un caràcter que XML no permet -@msg {what}: {name} is not an array {what}: {name} no és una matriu -@msg {what}: {name} is not a simple property {what}: {name} no és una propietat simple -@msg {what}: {name} is not a language alternative array {what}: {name} no és una matriu d'alternatives d'idioma -@msg {what}: the array index {index} is out of range {what}: l'índex de matriu {index} és fora de l'interval -@msg {what}: the namespace {uri} is not registered {what}: l'espai de noms {uri} no està registrat -@msg {what}: the file is closed {what}: el fitxer està tancat -@msg {what}: the file cannot be updated {what}: el fitxer no es pot actualitzar @msg {what}: the count must be a finite number, 0 or more {what}: el recompte ha de ser un nombre finit, 0 o més @msg File.seek: the position must be a finite number File.seek: la posició ha de ser un nombre finit @msg File.seek: the mode must be 0, 1 or 2 File.seek: el mode ha de ser 0, 1 o 2 diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index e4c6c614ad..488df173c3 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5368,21 +5368,6 @@ liquify-list-end {0}, {1} {0} a {1} @msg the script passed more data to and from commands than one run may pass skript předal příkazům a z příkazů více dat, než smí předat jeden běh @msg the script added more objects and data to the documents than one run may add skript přidal do dokumentů více objektů a dat, než smí přidat jeden běh @msg {what}: the object is not a File or a Folder {what}: objekt není File ani Folder -@msg {what}: the library {name} is not available {what}: knihovna {name} není k dispozici -@msg {what} is not available yet {what} zatím není k dispozici -@msg {what}: the value {value} is not available yet {what}: hodnota {value} zatím není k dispozici -@msg {what}: the object is not an {class} object {what}: objekt není objekt {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: paket XMP není správně utvořené XMP -@msg {what}: the XMP data is too large {what}: data XMP jsou příliš velká -@msg {what}: {name} is not a valid property name {what}: {name} není platný název vlastnosti -@msg {what}: the text holds a character XML does not allow {what}: text obsahuje znak, který XML nepovoluje -@msg {what}: {name} is not an array {what}: {name} není pole -@msg {what}: {name} is not a simple property {what}: {name} není jednoduchá vlastnost -@msg {what}: {name} is not a language alternative array {what}: {name} není pole jazykových alternativ -@msg {what}: the array index {index} is out of range {what}: index pole {index} je mimo rozsah -@msg {what}: the namespace {uri} is not registered {what}: obor názvů {uri} není registrován -@msg {what}: the file is closed {what}: soubor je zavřený -@msg {what}: the file cannot be updated {what}: soubor nelze aktualizovat @msg {what}: the count must be a finite number, 0 or more {what}: počet musí být konečné číslo, 0 nebo více @msg File.seek: the position must be a finite number File.seek: pozice musí být konečné číslo @msg File.seek: the mode must be 0, 1 or 2 File.seek: režim musí být 0, 1 nebo 2 diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 7c2c34978b..302ab6aa69 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -216,21 +216,6 @@ liquify-list-end {0}, {1} {0} og {1} @msg the script passed more data to and from commands than one run may pass scriptet sendte flere data til og fra kommandoer, end én kørsel må sende @msg the script added more objects and data to the documents than one run may add scriptet tilføjede flere objekter og data til dokumenterne, end én kørsel må tilføje @msg {what}: the object is not a File or a Folder {what}: objektet er ikke en File eller en Folder -@msg {what}: the library {name} is not available {what}: biblioteket {name} er ikke tilgængeligt -@msg {what} is not available yet {what} er endnu ikke tilgængelig -@msg {what}: the value {value} is not available yet {what}: værdien {value} er endnu ikke tilgængelig -@msg {what}: the object is not an {class} object {what}: objektet er ikke et {class}-objekt -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP-pakken er ikke velformet XMP -@msg {what}: the XMP data is too large {what}: XMP-dataene er for store -@msg {what}: {name} is not a valid property name {what}: {name} er ikke et gyldigt egenskabsnavn -@msg {what}: the text holds a character XML does not allow {what}: teksten indeholder et tegn, som XML ikke tillader -@msg {what}: {name} is not an array {what}: {name} er ikke en matrix -@msg {what}: {name} is not a simple property {what}: {name} er ikke en simpel egenskab -@msg {what}: {name} is not a language alternative array {what}: {name} er ikke en matrix af sprogalternativer -@msg {what}: the array index {index} is out of range {what}: matrixindekset {index} er uden for området -@msg {what}: the namespace {uri} is not registered {what}: navnerummet {uri} er ikke registreret -@msg {what}: the file is closed {what}: filen er lukket -@msg {what}: the file cannot be updated {what}: filen kan ikke opdateres @msg {what}: the count must be a finite number, 0 or more {what}: antallet skal være et endeligt tal, 0 eller mere @msg File.seek: the position must be a finite number File.seek: positionen skal være et endeligt tal @msg File.seek: the mode must be 0, 1 or 2 File.seek: tilstanden skal være 0, 1 eller 2 diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d36b965b27..9482345f18 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4953,21 +4953,6 @@ liquify-list-end {0}, {1} {0} und {1} @msg the script passed more data to and from commands than one run may pass das Skript hat mehr Daten an Befehle und von Befehlen übergeben, als ein Lauf übergeben darf @msg the script added more objects and data to the documents than one run may add das Skript hat den Dokumenten mehr Objekte und Daten hinzugefügt, als ein Lauf hinzufügen darf @msg {what}: the object is not a File or a Folder {what}: Das Objekt ist weder ein File noch ein Folder -@msg {what}: the library {name} is not available {what}: Die Bibliothek {name} ist nicht verfügbar -@msg {what} is not available yet {what} ist noch nicht verfügbar -@msg {what}: the value {value} is not available yet {what}: Der Wert {value} ist noch nicht verfügbar -@msg {what}: the object is not an {class} object {what}: Das Objekt ist kein {class}-Objekt -@msg {what}: the XMP packet is not well-formed XMP {what}: Das XMP-Paket ist kein wohlgeformtes XMP -@msg {what}: the XMP data is too large {what}: Die XMP-Daten sind zu groß -@msg {what}: {name} is not a valid property name {what}: {name} ist kein gültiger Eigenschaftsname -@msg {what}: the text holds a character XML does not allow {what}: Der Text enthält ein Zeichen, das XML nicht zulässt -@msg {what}: {name} is not an array {what}: {name} ist kein Array -@msg {what}: {name} is not a simple property {what}: {name} ist keine einfache Eigenschaft -@msg {what}: {name} is not a language alternative array {what}: {name} ist kein Array mit Sprachalternativen -@msg {what}: the array index {index} is out of range {what}: Der Array-Index {index} liegt außerhalb des Bereichs -@msg {what}: the namespace {uri} is not registered {what}: Der Namensraum {uri} ist nicht registriert -@msg {what}: the file is closed {what}: Die Datei ist geschlossen -@msg {what}: the file cannot be updated {what}: Die Datei kann nicht aktualisiert werden @msg {what}: the count must be a finite number, 0 or more {what}: Die Anzahl muss eine endliche Zahl sein, 0 oder mehr @msg File.seek: the position must be a finite number File.seek: Die Position muss eine endliche Zahl sein @msg File.seek: the mode must be 0, 1 or 2 File.seek: Der Modus muss 0, 1 oder 2 sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ac46fef527..434d0cc0b8 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2770,21 +2770,6 @@ liquify-list-end {0}, {1} {0} και {1} @msg the script passed more data to and from commands than one run may pass το σενάριο μετέφερε περισσότερα δεδομένα προς και από εντολές από όσα επιτρέπονται σε μία εκτέλεση @msg the script added more objects and data to the documents than one run may add το σενάριο πρόσθεσε στα έγγραφα περισσότερα αντικείμενα και δεδομένα από όσα επιτρέπονται σε μία εκτέλεση @msg {what}: the object is not a File or a Folder {what}: το αντικείμενο δεν είναι File ούτε Folder -@msg {what}: the library {name} is not available {what}: η βιβλιοθήκη {name} δεν είναι διαθέσιμη -@msg {what} is not available yet {what} δεν είναι ακόμη διαθέσιμο -@msg {what}: the value {value} is not available yet {what}: η τιμή {value} δεν είναι ακόμη διαθέσιμη -@msg {what}: the object is not an {class} object {what}: το αντικείμενο δεν είναι αντικείμενο {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: το πακέτο XMP δεν είναι σωστά διαμορφωμένο XMP -@msg {what}: the XMP data is too large {what}: τα δεδομένα XMP είναι πολύ μεγάλα -@msg {what}: {name} is not a valid property name {what}: το {name} δεν είναι έγκυρο όνομα ιδιότητας -@msg {what}: the text holds a character XML does not allow {what}: το κείμενο περιέχει χαρακτήρα που η XML δεν επιτρέπει -@msg {what}: {name} is not an array {what}: το {name} δεν είναι πίνακας -@msg {what}: {name} is not a simple property {what}: το {name} δεν είναι απλή ιδιότητα -@msg {what}: {name} is not a language alternative array {what}: το {name} δεν είναι πίνακας γλωσσικών εναλλακτικών -@msg {what}: the array index {index} is out of range {what}: ο δείκτης πίνακα {index} είναι εκτός εύρους -@msg {what}: the namespace {uri} is not registered {what}: ο χώρος ονομάτων {uri} δεν είναι καταχωρισμένος -@msg {what}: the file is closed {what}: το αρχείο είναι κλειστό -@msg {what}: the file cannot be updated {what}: το αρχείο δεν μπορεί να ενημερωθεί @msg {what}: the count must be a finite number, 0 or more {what}: το πλήθος πρέπει να είναι πεπερασμένος αριθμός, 0 ή περισσότερο @msg File.seek: the position must be a finite number File.seek: η θέση πρέπει να είναι πεπερασμένος αριθμός @msg File.seek: the mode must be 0, 1 or 2 File.seek: ο τρόπος πρέπει να είναι 0, 1 ή 2 diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 415b46a8b0..3f83e928e4 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5045,21 +5045,6 @@ liquify-list-end {0}, {1} {0}, {1} @msg the script passed more data to and from commands than one run may pass el script pasó más datos a los comandos y desde ellos de los que puede pasar una ejecución @msg the script added more objects and data to the documents than one run may add el script añadió a los documentos más objetos y datos de los que puede añadir una ejecución @msg {what}: the object is not a File or a Folder {what}: el objeto no es un File ni un Folder -@msg {what}: the library {name} is not available {what}: la biblioteca {name} no está disponible -@msg {what} is not available yet {what} aún no está disponible -@msg {what}: the value {value} is not available yet {what}: el valor {value} aún no está disponible -@msg {what}: the object is not an {class} object {what}: el objeto no es un objeto {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: el paquete XMP no es XMP bien formado -@msg {what}: the XMP data is too large {what}: los datos XMP son demasiado grandes -@msg {what}: {name} is not a valid property name {what}: {name} no es un nombre de propiedad válido -@msg {what}: the text holds a character XML does not allow {what}: el texto contiene un carácter que XML no permite -@msg {what}: {name} is not an array {what}: {name} no es una matriz -@msg {what}: {name} is not a simple property {what}: {name} no es una propiedad simple -@msg {what}: {name} is not a language alternative array {what}: {name} no es una matriz de alternativas de idioma -@msg {what}: the array index {index} is out of range {what}: el índice de matriz {index} está fuera de rango -@msg {what}: the namespace {uri} is not registered {what}: el espacio de nombres {uri} no está registrado -@msg {what}: the file is closed {what}: el archivo está cerrado -@msg {what}: the file cannot be updated {what}: el archivo no se puede actualizar @msg {what}: the count must be a finite number, 0 or more {what}: la cantidad debe ser un número finito, 0 o más @msg File.seek: the position must be a finite number File.seek: la posición debe ser un número finito @msg File.seek: the mode must be 0, 1 or 2 File.seek: el modo debe ser 0, 1 o 2 diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index ad7e813fe5..a4d85b23e8 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5286,21 +5286,6 @@ liquify-list-end {0}, {1} {0} ja {1} @msg the script passed more data to and from commands than one run may pass skripti välitti komennoille ja komennoilta enemmän tietoa kuin yksi ajo saa välittää @msg the script added more objects and data to the documents than one run may add skripti lisäsi asiakirjoihin enemmän objekteja ja tietoja kuin yksi ajo saa lisätä @msg {what}: the object is not a File or a Folder {what}: objekti ei ole File eikä Folder -@msg {what}: the library {name} is not available {what}: kirjasto {name} ei ole käytettävissä -@msg {what} is not available yet {what} ei ole vielä käytettävissä -@msg {what}: the value {value} is not available yet {what}: arvo {value} ei ole vielä käytettävissä -@msg {what}: the object is not an {class} object {what}: objekti ei ole {class}-objekti -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP-paketti ei ole hyvin muodostettua XMP:tä -@msg {what}: the XMP data is too large {what}: XMP-tiedot ovat liian suuret -@msg {what}: {name} is not a valid property name {what}: {name} ei ole kelvollinen ominaisuuden nimi -@msg {what}: the text holds a character XML does not allow {what}: teksti sisältää merkin, jota XML ei salli -@msg {what}: {name} is not an array {what}: {name} ei ole taulukko -@msg {what}: {name} is not a simple property {what}: {name} ei ole yksinkertainen ominaisuus -@msg {what}: {name} is not a language alternative array {what}: {name} ei ole kielivaihtoehtojen taulukko -@msg {what}: the array index {index} is out of range {what}: taulukon indeksi {index} on alueen ulkopuolella -@msg {what}: the namespace {uri} is not registered {what}: nimiavaruutta {uri} ei ole rekisteröity -@msg {what}: the file is closed {what}: tiedosto on suljettu -@msg {what}: the file cannot be updated {what}: tiedostoa ei voi päivittää @msg {what}: the count must be a finite number, 0 or more {what}: määrän on oltava äärellinen luku, 0 tai enemmän @msg File.seek: the position must be a finite number File.seek: sijainnin on oltava äärellinen luku @msg File.seek: the mode must be 0, 1 or 2 File.seek: tilan on oltava 0, 1 tai 2 diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 40cd203c0e..8f56486157 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5013,21 +5013,6 @@ liquify-list-end {0}, {1} {0} et {1} @msg the script made more host calls than one run may make le script a fait plus d’appels à l’hôte qu’une exécution ne peut en faire @msg the script passed more data to and from commands than one run may pass le script a transmis plus de données vers et depuis les commandes qu’une exécution ne peut en transmettre @msg the script added more objects and data to the documents than one run may add le script a ajouté aux documents plus d’objets et de données qu’une exécution ne peut en ajouter -@msg {what}: the library {name} is not available {what} : la bibliothèque {name} n’est pas disponible -@msg {what} is not available yet {what} n’est pas encore disponible -@msg {what}: the value {value} is not available yet {what} : la valeur {value} n’est pas encore disponible -@msg {what}: the object is not an {class} object {what} : l’objet n’est pas un objet {class} -@msg {what}: the XMP packet is not well-formed XMP {what} : le paquet XMP n’est pas du XMP bien formé -@msg {what}: the XMP data is too large {what} : les données XMP sont trop volumineuses -@msg {what}: {name} is not a valid property name {what} : {name} n’est pas un nom de propriété valide -@msg {what}: the text holds a character XML does not allow {what} : le texte contient un caractère que XML n’autorise pas -@msg {what}: {name} is not an array {what} : {name} n’est pas un tableau -@msg {what}: {name} is not a simple property {what} : {name} n’est pas une propriété simple -@msg {what}: {name} is not a language alternative array {what} : {name} n’est pas un tableau d’alternatives linguistiques -@msg {what}: the array index {index} is out of range {what} : l’index de tableau {index} est hors limites -@msg {what}: the namespace {uri} is not registered {what} : l’espace de noms {uri} n’est pas enregistré -@msg {what}: the file is closed {what} : le fichier est fermé -@msg {what}: the file cannot be updated {what} : le fichier ne peut pas être mis à jour @msg {what}: the object is not a File or a Folder {what} : l’objet n’est ni un File ni un Folder @msg {what}: the count must be a finite number, 0 or more {what} : le nombre doit être un nombre fini, 0 ou plus @msg File.seek: the position must be a finite number File.seek : la position doit être un nombre fini diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 331aa30575..e9509d9202 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7719,21 +7719,6 @@ liquify-list-end {0}, {1} {0} और {1} @msg the script passed more data to and from commands than one run may pass स्क्रिप्ट ने कमांड को और कमांड से एक रन में अनुमत से अधिक डेटा भेजा @msg the script added more objects and data to the documents than one run may add स्क्रिप्ट ने दस्तावेज़ों में एक रन में अनुमत से अधिक ऑब्जेक्ट और डेटा जोड़े @msg {what}: the object is not a File or a Folder {what}: ऑब्जेक्ट न File है न Folder -@msg {what}: the library {name} is not available {what}: लाइब्रेरी {name} उपलब्ध नहीं है -@msg {what} is not available yet {what} अभी उपलब्ध नहीं है -@msg {what}: the value {value} is not available yet {what}: मान {value} अभी उपलब्ध नहीं है -@msg {what}: the object is not an {class} object {what}: ऑब्जेक्ट {class} ऑब्जेक्ट नहीं है -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP पैकेट सही ढंग से बना XMP नहीं है -@msg {what}: the XMP data is too large {what}: XMP डेटा बहुत बड़ा है -@msg {what}: {name} is not a valid property name {what}: {name} मान्य प्रॉपर्टी नाम नहीं है -@msg {what}: the text holds a character XML does not allow {what}: टेक्स्ट में ऐसा वर्ण है जिसकी XML अनुमति नहीं देता -@msg {what}: {name} is not an array {what}: {name} ऐरे नहीं है -@msg {what}: {name} is not a simple property {what}: {name} सरल प्रॉपर्टी नहीं है -@msg {what}: {name} is not a language alternative array {what}: {name} भाषा विकल्पों का ऐरे नहीं है -@msg {what}: the array index {index} is out of range {what}: ऐरे इंडेक्स {index} सीमा से बाहर है -@msg {what}: the namespace {uri} is not registered {what}: नेमस्पेस {uri} पंजीकृत नहीं है -@msg {what}: the file is closed {what}: फ़ाइल बंद है -@msg {what}: the file cannot be updated {what}: फ़ाइल अपडेट नहीं की जा सकती @msg {what}: the count must be a finite number, 0 or more {what}: गिनती एक सीमित संख्या होनी चाहिए, 0 या अधिक @msg File.seek: the position must be a finite number File.seek: स्थिति एक सीमित संख्या होनी चाहिए @msg File.seek: the mode must be 0, 1 or 2 File.seek: मोड 0, 1 या 2 होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 8171b8d3f6..87f050ef0d 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5885,21 +5885,6 @@ liquify-list-end {0}, {1} {0} és {1} @msg the script passed more data to and from commands than one run may pass a parancsfájl több adatot adott át a parancsoknak és a parancsoktól, mint amennyit egy futás átadhat @msg the script added more objects and data to the documents than one run may add a parancsfájl több objektumot és adatot adott a dokumentumokhoz, mint amennyit egy futás hozzáadhat @msg {what}: the object is not a File or a Folder {what}: az objektum nem File és nem Folder -@msg {what}: the library {name} is not available {what}: a(z) {name} könyvtár nem érhető el -@msg {what} is not available yet {what} még nem érhető el -@msg {what}: the value {value} is not available yet {what}: a(z) {value} érték még nem érhető el -@msg {what}: the object is not an {class} object {what}: az objektum nem {class} objektum -@msg {what}: the XMP packet is not well-formed XMP {what}: az XMP-csomag nem jól formázott XMP -@msg {what}: the XMP data is too large {what}: az XMP-adatok túl nagyok -@msg {what}: {name} is not a valid property name {what}: a(z) {name} nem érvényes tulajdonságnév -@msg {what}: the text holds a character XML does not allow {what}: a szöveg olyan karaktert tartalmaz, amelyet az XML nem enged meg -@msg {what}: {name} is not an array {what}: a(z) {name} nem tömb -@msg {what}: {name} is not a simple property {what}: a(z) {name} nem egyszerű tulajdonság -@msg {what}: {name} is not a language alternative array {what}: a(z) {name} nem nyelvi alternatívák tömbje -@msg {what}: the array index {index} is out of range {what}: a(z) {index} tömbindex a tartományon kívül esik -@msg {what}: the namespace {uri} is not registered {what}: a(z) {uri} névtér nincs regisztrálva -@msg {what}: the file is closed {what}: a fájl be van zárva -@msg {what}: the file cannot be updated {what}: a fájl nem frissíthető @msg {what}: the count must be a finite number, 0 or more {what}: a darabszámnak véges számnak kell lennie, 0 vagy több @msg File.seek: the position must be a finite number File.seek: a pozíciónak véges számnak kell lennie @msg File.seek: the mode must be 0, 1 or 2 File.seek: a mód csak 0, 1 vagy 2 lehet diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 4e1170ad31..924d3d80b5 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -159,21 +159,6 @@ @msg the script passed more data to and from commands than one run may pass skrip mengirim lebih banyak data ke dan dari perintah daripada yang boleh dikirim satu proses @msg the script added more objects and data to the documents than one run may add skrip menambahkan lebih banyak objek dan data ke dokumen daripada yang boleh ditambahkan satu proses @msg {what}: the object is not a File or a Folder {what}: objek bukan File atau Folder -@msg {what}: the library {name} is not available {what}: pustaka {name} tidak tersedia -@msg {what} is not available yet {what} belum tersedia -@msg {what}: the value {value} is not available yet {what}: nilai {value} belum tersedia -@msg {what}: the object is not an {class} object {what}: objek bukan objek {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: paket XMP bukan XMP yang tersusun dengan benar -@msg {what}: the XMP data is too large {what}: data XMP terlalu besar -@msg {what}: {name} is not a valid property name {what}: {name} bukan nama properti yang valid -@msg {what}: the text holds a character XML does not allow {what}: teks berisi karakter yang tidak diizinkan XML -@msg {what}: {name} is not an array {what}: {name} bukan larik -@msg {what}: {name} is not a simple property {what}: {name} bukan properti sederhana -@msg {what}: {name} is not a language alternative array {what}: {name} bukan larik alternatif bahasa -@msg {what}: the array index {index} is out of range {what}: indeks larik {index} di luar rentang -@msg {what}: the namespace {uri} is not registered {what}: ruang nama {uri} tidak terdaftar -@msg {what}: the file is closed {what}: berkas tertutup -@msg {what}: the file cannot be updated {what}: berkas tidak dapat diperbarui @msg {what}: the count must be a finite number, 0 or more {what}: jumlah harus berupa angka berhingga, 0 atau lebih @msg File.seek: the position must be a finite number File.seek: posisi harus berupa angka berhingga @msg File.seek: the mode must be 0, 1 or 2 File.seek: mode harus 0, 1 atau 2 diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 3638fab939..5f47e3f117 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5091,21 +5091,6 @@ liquify-list-end {0}, {1} {0} e {1} @msg the script passed more data to and from commands than one run may pass lo script ha passato ai comandi e dai comandi più dati di quanti ne possa passare un'esecuzione @msg the script added more objects and data to the documents than one run may add lo script ha aggiunto ai documenti più oggetti e dati di quanti ne possa aggiungere un'esecuzione @msg {what}: the object is not a File or a Folder {what}: l'oggetto non è un File né un Folder -@msg {what}: the library {name} is not available {what}: la libreria {name} non è disponibile -@msg {what} is not available yet {what} non è ancora disponibile -@msg {what}: the value {value} is not available yet {what}: il valore {value} non è ancora disponibile -@msg {what}: the object is not an {class} object {what}: l'oggetto non è un oggetto {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: il pacchetto XMP non è XMP ben formato -@msg {what}: the XMP data is too large {what}: i dati XMP sono troppo grandi -@msg {what}: {name} is not a valid property name {what}: {name} non è un nome di proprietà valido -@msg {what}: the text holds a character XML does not allow {what}: il testo contiene un carattere che XML non consente -@msg {what}: {name} is not an array {what}: {name} non è un array -@msg {what}: {name} is not a simple property {what}: {name} non è una proprietà semplice -@msg {what}: {name} is not a language alternative array {what}: {name} non è un array di alternative di lingua -@msg {what}: the array index {index} is out of range {what}: l'indice di array {index} è fuori intervallo -@msg {what}: the namespace {uri} is not registered {what}: lo spazio dei nomi {uri} non è registrato -@msg {what}: the file is closed {what}: il file è chiuso -@msg {what}: the file cannot be updated {what}: il file non può essere aggiornato @msg {what}: the count must be a finite number, 0 or more {what}: il conteggio deve essere un numero finito, 0 o più @msg File.seek: the position must be a finite number File.seek: la posizione deve essere un numero finito @msg File.seek: the mode must be 0, 1 or 2 File.seek: la modalità deve essere 0, 1 o 2 diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d40d4202d1..9a1b5f6354 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5917,21 +5917,6 @@ liquify-list-end {0}, {1} {0}、{1} @msg the script passed more data to and from commands than one run may pass スクリプトが 1 回の実行で許されるより多くのデータをコマンドとやり取りしました @msg the script added more objects and data to the documents than one run may add スクリプトが 1 回の実行で許されるより多くのオブジェクトとデータをドキュメントに追加しました @msg {what}: the object is not a File or a Folder {what}: オブジェクトは File でも Folder でもありません -@msg {what}: the library {name} is not available {what}: ライブラリ {name} は利用できません -@msg {what} is not available yet {what} はまだ利用できません -@msg {what}: the value {value} is not available yet {what}: 値 {value} はまだ利用できません -@msg {what}: the object is not an {class} object {what}: オブジェクトは {class} オブジェクトではありません -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP パケットが整形式の XMP ではありません -@msg {what}: the XMP data is too large {what}: XMP データが大きすぎます -@msg {what}: {name} is not a valid property name {what}: {name} は有効なプロパティ名ではありません -@msg {what}: the text holds a character XML does not allow {what}: テキストに XML で使えない文字が含まれています -@msg {what}: {name} is not an array {what}: {name} は配列ではありません -@msg {what}: {name} is not a simple property {what}: {name} は単純なプロパティではありません -@msg {what}: {name} is not a language alternative array {what}: {name} は言語の代替配列ではありません -@msg {what}: the array index {index} is out of range {what}: 配列のインデックス {index} が範囲外です -@msg {what}: the namespace {uri} is not registered {what}: 名前空間 {uri} は登録されていません -@msg {what}: the file is closed {what}: ファイルは閉じています -@msg {what}: the file cannot be updated {what}: ファイルを更新できません @msg {what}: the count must be a finite number, 0 or more {what}: 数は 0 以上の有限の数値にしてください @msg File.seek: the position must be a finite number File.seek: 位置は有限の数値にしてください @msg File.seek: the mode must be 0, 1 or 2 File.seek: モードは 0, 1 または 2 にしてください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 48372764c1..8eeacee621 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8586,21 +8586,6 @@ liquify-list-end {0}, {1} {0} და {1} @msg the script passed more data to and from commands than one run may pass სკრიპტმა ბრძანებებს და ბრძანებებიდან იმაზე მეტი მონაცემი გადასცა, ვიდრე ერთ გაშვებას შეუძლია @msg the script added more objects and data to the documents than one run may add სკრიპტმა დოკუმენტებს იმაზე მეტი ობიექტი და მონაცემი დაამატა, ვიდრე ერთ გაშვებას შეუძლია @msg {what}: the object is not a File or a Folder {what}: ობიექტი არც File-ია და არც Folder -@msg {what}: the library {name} is not available {what}: ბიბლიოთეკა {name} მიუწვდომელია -@msg {what} is not available yet {what} ჯერ მიუწვდომელია -@msg {what}: the value {value} is not available yet {what}: მნიშვნელობა {value} ჯერ მიუწვდომელია -@msg {what}: the object is not an {class} object {what}: ობიექტი არ არის {class} ობიექტი -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP პაკეტი არ არის სწორად აგებული XMP -@msg {what}: the XMP data is too large {what}: XMP მონაცემები ზედმეტად დიდია -@msg {what}: {name} is not a valid property name {what}: {name} არ არის თვისების სწორი სახელი -@msg {what}: the text holds a character XML does not allow {what}: ტექსტი შეიცავს სიმბოლოს, რომელსაც XML არ უშვებს -@msg {what}: {name} is not an array {what}: {name} არ არის მასივი -@msg {what}: {name} is not a simple property {what}: {name} არ არის მარტივი თვისება -@msg {what}: {name} is not a language alternative array {what}: {name} არ არის ენობრივი ალტერნატივების მასივი -@msg {what}: the array index {index} is out of range {what}: მასივის ინდექსი {index} დიაპაზონს გარეთაა -@msg {what}: the namespace {uri} is not registered {what}: სახელთა სივრცე {uri} არ არის რეგისტრირებული -@msg {what}: the file is closed {what}: ფაილი დახურულია -@msg {what}: the file cannot be updated {what}: ფაილის განახლება შეუძლებელია @msg {what}: the count must be a finite number, 0 or more {what}: რაოდენობა უნდა იყოს სასრული რიცხვი, 0 ან მეტი @msg File.seek: the position must be a finite number File.seek: პოზიცია უნდა იყოს სასრული რიცხვი @msg File.seek: the mode must be 0, 1 or 2 File.seek: რეჟიმი უნდა იყოს 0, 1 ან 2 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 3e85928817..57e0b8be10 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5846,21 +5846,6 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg the script passed more data to and from commands than one run may pass 스크립트가 한 번의 실행에 허용된 것보다 많은 데이터를 명령과 주고받았습니다 @msg the script added more objects and data to the documents than one run may add 스크립트가 한 번의 실행에 허용된 것보다 많은 객체와 데이터를 문서에 추가했습니다 @msg {what}: the object is not a File or a Folder {what}: 객체가 File도 Folder도 아닙니다 -@msg {what}: the library {name} is not available {what}: 라이브러리 {name}을(를) 사용할 수 없습니다 -@msg {what} is not available yet {what}은(는) 아직 사용할 수 없습니다 -@msg {what}: the value {value} is not available yet {what}: 값 {value}은(는) 아직 사용할 수 없습니다 -@msg {what}: the object is not an {class} object {what}: 객체가 {class} 객체가 아닙니다 -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP 패킷이 올바른 형식의 XMP가 아닙니다 -@msg {what}: the XMP data is too large {what}: XMP 데이터가 너무 큽니다 -@msg {what}: {name} is not a valid property name {what}: {name}은(는) 올바른 속성 이름이 아닙니다 -@msg {what}: the text holds a character XML does not allow {what}: 텍스트에 XML이 허용하지 않는 문자가 있습니다 -@msg {what}: {name} is not an array {what}: {name}은(는) 배열이 아닙니다 -@msg {what}: {name} is not a simple property {what}: {name}은(는) 단순 속성이 아닙니다 -@msg {what}: {name} is not a language alternative array {what}: {name}은(는) 언어 대체 배열이 아닙니다 -@msg {what}: the array index {index} is out of range {what}: 배열 인덱스 {index}이(가) 범위를 벗어났습니다 -@msg {what}: the namespace {uri} is not registered {what}: 네임스페이스 {uri}이(가) 등록되지 않았습니다 -@msg {what}: the file is closed {what}: 파일이 닫혀 있습니다 -@msg {what}: the file cannot be updated {what}: 파일을 업데이트할 수 없습니다 @msg {what}: the count must be a finite number, 0 or more {what}: 개수는 0 이상의 유한한 숫자여야 합니다 @msg File.seek: the position must be a finite number File.seek: 위치는 유한한 숫자여야 합니다 @msg File.seek: the mode must be 0, 1 or 2 File.seek: 모드는 0, 1 또는 2여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b23412f1ec..5ed5cdc3e0 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -205,21 +205,6 @@ liquify-list-end {0}, {1} {0} en {1} @msg the script passed more data to and from commands than one run may pass het script heeft meer gegevens van en naar opdrachten doorgegeven dan één uitvoering mag doorgeven @msg the script added more objects and data to the documents than one run may add het script heeft meer objecten en gegevens aan de documenten toegevoegd dan één uitvoering mag toevoegen @msg {what}: the object is not a File or a Folder {what}: het object is geen File of Folder -@msg {what}: the library {name} is not available {what}: de bibliotheek {name} is niet beschikbaar -@msg {what} is not available yet {what} is nog niet beschikbaar -@msg {what}: the value {value} is not available yet {what}: de waarde {value} is nog niet beschikbaar -@msg {what}: the object is not an {class} object {what}: het object is geen {class}-object -@msg {what}: the XMP packet is not well-formed XMP {what}: het XMP-pakket is geen goed gevormde XMP -@msg {what}: the XMP data is too large {what}: de XMP-gegevens zijn te groot -@msg {what}: {name} is not a valid property name {what}: {name} is geen geldige eigenschapsnaam -@msg {what}: the text holds a character XML does not allow {what}: de tekst bevat een teken dat XML niet toestaat -@msg {what}: {name} is not an array {what}: {name} is geen array -@msg {what}: {name} is not a simple property {what}: {name} is geen eenvoudige eigenschap -@msg {what}: {name} is not a language alternative array {what}: {name} is geen array van taalalternatieven -@msg {what}: the array index {index} is out of range {what}: de array-index {index} valt buiten het bereik -@msg {what}: the namespace {uri} is not registered {what}: de naamruimte {uri} is niet geregistreerd -@msg {what}: the file is closed {what}: het bestand is gesloten -@msg {what}: the file cannot be updated {what}: het bestand kan niet worden bijgewerkt @msg {what}: the count must be a finite number, 0 or more {what}: het aantal moet een eindig getal zijn, 0 of meer @msg File.seek: the position must be a finite number File.seek: de positie moet een eindig getal zijn @msg File.seek: the mode must be 0, 1 or 2 File.seek: de modus moet 0, 1 of 2 zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index d12a0430d9..74029133dc 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5196,21 +5196,6 @@ liquify-list-end {0}, {1} {0} i {1} @msg the script passed more data to and from commands than one run may pass skrypt przekazał do poleceń i z poleceń więcej danych, niż może przekazać jedno uruchomienie @msg the script added more objects and data to the documents than one run may add skrypt dodał do dokumentów więcej obiektów i danych, niż może dodać jedno uruchomienie @msg {what}: the object is not a File or a Folder {what}: obiekt nie jest ani File, ani Folder -@msg {what}: the library {name} is not available {what}: biblioteka {name} jest niedostępna -@msg {what} is not available yet {what} nie jest jeszcze dostępne -@msg {what}: the value {value} is not available yet {what}: wartość {value} nie jest jeszcze dostępna -@msg {what}: the object is not an {class} object {what}: obiekt nie jest obiektem {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: pakiet XMP nie jest poprawnie zbudowanym XMP -@msg {what}: the XMP data is too large {what}: dane XMP są za duże -@msg {what}: {name} is not a valid property name {what}: {name} nie jest prawidłową nazwą właściwości -@msg {what}: the text holds a character XML does not allow {what}: tekst zawiera znak niedozwolony w XML -@msg {what}: {name} is not an array {what}: {name} nie jest tablicą -@msg {what}: {name} is not a simple property {what}: {name} nie jest prostą właściwością -@msg {what}: {name} is not a language alternative array {what}: {name} nie jest tablicą alternatyw językowych -@msg {what}: the array index {index} is out of range {what}: indeks tablicy {index} jest poza zakresem -@msg {what}: the namespace {uri} is not registered {what}: przestrzeń nazw {uri} nie jest zarejestrowana -@msg {what}: the file is closed {what}: plik jest zamknięty -@msg {what}: the file cannot be updated {what}: nie można zaktualizować pliku @msg {what}: the count must be a finite number, 0 or more {what}: liczba musi być liczbą skończoną, 0 lub większą @msg File.seek: the position must be a finite number File.seek: pozycja musi być liczbą skończoną @msg File.seek: the mode must be 0, 1 or 2 File.seek: tryb musi wynosić 0, 1 lub 2 diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 868a243cef..a1747af0b2 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6235,21 +6235,6 @@ liquify-list-end {0}, {1} {0} e {1} @msg the script passed more data to and from commands than one run may pass o script passou mais dados para os comandos e a partir deles do que uma execução pode passar @msg the script added more objects and data to the documents than one run may add o script adicionou aos documentos mais objetos e dados do que uma execução pode adicionar @msg {what}: the object is not a File or a Folder {what}: o objeto não é um File nem um Folder -@msg {what}: the library {name} is not available {what}: a biblioteca {name} não está disponível -@msg {what} is not available yet {what} ainda não está disponível -@msg {what}: the value {value} is not available yet {what}: o valor {value} ainda não está disponível -@msg {what}: the object is not an {class} object {what}: o objeto não é um objeto {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: o pacote XMP não é um XMP bem formado -@msg {what}: the XMP data is too large {what}: os dados XMP são grandes demais -@msg {what}: {name} is not a valid property name {what}: {name} não é um nome de propriedade válido -@msg {what}: the text holds a character XML does not allow {what}: o texto contém um caractere que o XML não permite -@msg {what}: {name} is not an array {what}: {name} não é uma matriz -@msg {what}: {name} is not a simple property {what}: {name} não é uma propriedade simples -@msg {what}: {name} is not a language alternative array {what}: {name} não é uma matriz de alternativas de idioma -@msg {what}: the array index {index} is out of range {what}: o índice de matriz {index} está fora do intervalo -@msg {what}: the namespace {uri} is not registered {what}: o namespace {uri} não está registrado -@msg {what}: the file is closed {what}: o arquivo está fechado -@msg {what}: the file cannot be updated {what}: o arquivo não pode ser atualizado @msg {what}: the count must be a finite number, 0 or more {what}: a contagem deve ser um número finito, 0 ou mais @msg File.seek: the position must be a finite number File.seek: a posição deve ser um número finito @msg File.seek: the mode must be 0, 1 or 2 File.seek: o modo deve ser 0, 1 ou 2 diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9af201db91..ca0c8d5145 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5067,21 +5067,6 @@ liquify-list-end {0}, {1} {0} и {1} @msg the script passed more data to and from commands than one run may pass скрипт передал командам и получил от них больше данных, чем разрешено одному запуску @msg the script added more objects and data to the documents than one run may add скрипт добавил в документы больше объектов и данных, чем разрешено одному запуску @msg {what}: the object is not a File or a Folder {what}: объект не является ни File, ни Folder -@msg {what}: the library {name} is not available {what}: библиотека {name} недоступна -@msg {what} is not available yet {what} пока недоступно -@msg {what}: the value {value} is not available yet {what}: значение {value} пока недоступно -@msg {what}: the object is not an {class} object {what}: объект не является объектом {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: пакет XMP не является правильно построенным XMP -@msg {what}: the XMP data is too large {what}: данные XMP слишком велики -@msg {what}: {name} is not a valid property name {what}: {name} не является допустимым именем свойства -@msg {what}: the text holds a character XML does not allow {what}: текст содержит символ, недопустимый в XML -@msg {what}: {name} is not an array {what}: {name} не является массивом -@msg {what}: {name} is not a simple property {what}: {name} не является простым свойством -@msg {what}: {name} is not a language alternative array {what}: {name} не является массивом языковых вариантов -@msg {what}: the array index {index} is out of range {what}: индекс массива {index} вне диапазона -@msg {what}: the namespace {uri} is not registered {what}: пространство имен {uri} не зарегистрировано -@msg {what}: the file is closed {what}: файл закрыт -@msg {what}: the file cannot be updated {what}: файл нельзя обновить @msg {what}: the count must be a finite number, 0 or more {what}: количество должно быть конечным числом, 0 или больше @msg File.seek: the position must be a finite number File.seek: позиция должна быть конечным числом @msg File.seek: the mode must be 0, 1 or 2 File.seek: режим должен быть 0, 1 или 2 diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c69017b569..c26474cf93 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4942,21 +4942,6 @@ liquify-list-end {0}, {1} {0} och {1} @msg the script passed more data to and from commands than one run may pass skriptet skickade mer data till och från kommandon än en körning får skicka @msg the script added more objects and data to the documents than one run may add skriptet lade till fler objekt och mer data i dokumenten än en körning får lägga till @msg {what}: the object is not a File or a Folder {what}: objektet är varken en File eller en Folder -@msg {what}: the library {name} is not available {what}: biblioteket {name} är inte tillgängligt -@msg {what} is not available yet {what} är inte tillgängligt än -@msg {what}: the value {value} is not available yet {what}: värdet {value} är inte tillgängligt än -@msg {what}: the object is not an {class} object {what}: objektet är inte ett {class}-objekt -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP-paketet är inte välformad XMP -@msg {what}: the XMP data is too large {what}: XMP-data är för stora -@msg {what}: {name} is not a valid property name {what}: {name} är inte ett giltigt egenskapsnamn -@msg {what}: the text holds a character XML does not allow {what}: texten innehåller ett tecken som XML inte tillåter -@msg {what}: {name} is not an array {what}: {name} är inte en matris -@msg {what}: {name} is not a simple property {what}: {name} är inte en enkel egenskap -@msg {what}: {name} is not a language alternative array {what}: {name} är inte en matris med språkalternativ -@msg {what}: the array index {index} is out of range {what}: matrisindexet {index} ligger utanför intervallet -@msg {what}: the namespace {uri} is not registered {what}: namnrymden {uri} är inte registrerad -@msg {what}: the file is closed {what}: filen är stängd -@msg {what}: the file cannot be updated {what}: filen kan inte uppdateras @msg {what}: the count must be a finite number, 0 or more {what}: antalet måste vara ett ändligt tal, 0 eller mer @msg File.seek: the position must be a finite number File.seek: positionen måste vara ett ändligt tal @msg File.seek: the mode must be 0, 1 or 2 File.seek: läget måste vara 0, 1 eller 2 diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 59fa066b58..82186ebcdd 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4789,21 +4789,6 @@ liquify-list-end {0}, {1} {0} ve {1} @msg the script passed more data to and from commands than one run may pass betik, komutlara ve komutlardan bir çalıştırmanın aktarabileceğinden daha fazla veri aktardı @msg the script added more objects and data to the documents than one run may add betik, belgelere bir çalıştırmanın ekleyebileceğinden daha fazla nesne ve veri ekledi @msg {what}: the object is not a File or a Folder {what}: nesne ne File ne de Folder -@msg {what}: the library {name} is not available {what}: {name} kitaplığı kullanılamıyor -@msg {what} is not available yet {what} henüz kullanılamıyor -@msg {what}: the value {value} is not available yet {what}: {value} değeri henüz kullanılamıyor -@msg {what}: the object is not an {class} object {what}: nesne bir {class} nesnesi değil -@msg {what}: the XMP packet is not well-formed XMP {what}: XMP paketi düzgün biçimli XMP değil -@msg {what}: the XMP data is too large {what}: XMP verileri çok büyük -@msg {what}: {name} is not a valid property name {what}: {name} geçerli bir özellik adı değil -@msg {what}: the text holds a character XML does not allow {what}: metin XML'in izin vermediği bir karakter içeriyor -@msg {what}: {name} is not an array {what}: {name} bir dizi değil -@msg {what}: {name} is not a simple property {what}: {name} basit bir özellik değil -@msg {what}: {name} is not a language alternative array {what}: {name} bir dil alternatifleri dizisi değil -@msg {what}: the array index {index} is out of range {what}: {index} dizi dizini aralık dışında -@msg {what}: the namespace {uri} is not registered {what}: {uri} ad alanı kayıtlı değil -@msg {what}: the file is closed {what}: dosya kapalı -@msg {what}: the file cannot be updated {what}: dosya güncellenemiyor @msg {what}: the count must be a finite number, 0 or more {what}: sayı 0 veya daha büyük, sonlu bir sayı olmalıdır @msg File.seek: the position must be a finite number File.seek: konum sonlu bir sayı olmalıdır @msg File.seek: the mode must be 0, 1 or 2 File.seek: mod 0, 1 veya 2 olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dcde17615c..de3329ef10 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5075,21 +5075,6 @@ liquify-list-end {0}, {1} {0} і {1} @msg the script passed more data to and from commands than one run may pass скрипт передав командам і отримав від них більше даних, ніж дозволено одному запуску @msg the script added more objects and data to the documents than one run may add скрипт додав до документів більше об'єктів і даних, ніж дозволено одному запуску @msg {what}: the object is not a File or a Folder {what}: об'єкт не є ні File, ні Folder -@msg {what}: the library {name} is not available {what}: бібліотека {name} недоступна -@msg {what} is not available yet {what} поки що недоступне -@msg {what}: the value {value} is not available yet {what}: значення {value} поки що недоступне -@msg {what}: the object is not an {class} object {what}: об'єкт не є об'єктом {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: пакет XMP не є правильно побудованим XMP -@msg {what}: the XMP data is too large {what}: дані XMP завеликі -@msg {what}: {name} is not a valid property name {what}: {name} не є допустимою назвою властивості -@msg {what}: the text holds a character XML does not allow {what}: текст містить символ, який XML не дозволяє -@msg {what}: {name} is not an array {what}: {name} не є масивом -@msg {what}: {name} is not a simple property {what}: {name} не є простою властивістю -@msg {what}: {name} is not a language alternative array {what}: {name} не є масивом мовних варіантів -@msg {what}: the array index {index} is out of range {what}: індекс масиву {index} поза діапазоном -@msg {what}: the namespace {uri} is not registered {what}: простір імен {uri} не зареєстровано -@msg {what}: the file is closed {what}: файл закрито -@msg {what}: the file cannot be updated {what}: файл неможливо оновити @msg {what}: the count must be a finite number, 0 or more {what}: кількість має бути скінченним числом, 0 або більше @msg File.seek: the position must be a finite number File.seek: позиція має бути скінченним числом @msg File.seek: the mode must be 0, 1 or 2 File.seek: режим має бути 0, 1 або 2 diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 02d2aa1ff4..675143a8d6 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5566,21 +5566,6 @@ liquify-list-end {0}, {1} {0} và {1} @msg the script passed more data to and from commands than one run may pass tập lệnh đã truyền đến và từ các lệnh nhiều dữ liệu hơn mức một lần chạy được phép @msg the script added more objects and data to the documents than one run may add tập lệnh đã thêm vào tài liệu nhiều đối tượng và dữ liệu hơn mức một lần chạy được phép @msg {what}: the object is not a File or a Folder {what}: đối tượng không phải File cũng không phải Folder -@msg {what}: the library {name} is not available {what}: thư viện {name} không khả dụng -@msg {what} is not available yet {what} chưa khả dụng -@msg {what}: the value {value} is not available yet {what}: giá trị {value} chưa khả dụng -@msg {what}: the object is not an {class} object {what}: đối tượng không phải đối tượng {class} -@msg {what}: the XMP packet is not well-formed XMP {what}: gói XMP không phải XMP đúng định dạng -@msg {what}: the XMP data is too large {what}: dữ liệu XMP quá lớn -@msg {what}: {name} is not a valid property name {what}: {name} không phải tên thuộc tính hợp lệ -@msg {what}: the text holds a character XML does not allow {what}: văn bản chứa ký tự mà XML không cho phép -@msg {what}: {name} is not an array {what}: {name} không phải mảng -@msg {what}: {name} is not a simple property {what}: {name} không phải thuộc tính đơn -@msg {what}: {name} is not a language alternative array {what}: {name} không phải mảng phương án ngôn ngữ -@msg {what}: the array index {index} is out of range {what}: chỉ số mảng {index} nằm ngoài phạm vi -@msg {what}: the namespace {uri} is not registered {what}: không gian tên {uri} chưa được đăng ký -@msg {what}: the file is closed {what}: tệp đã đóng -@msg {what}: the file cannot be updated {what}: không thể cập nhật tệp @msg {what}: the count must be a finite number, 0 or more {what}: số lượng phải là một số hữu hạn, 0 trở lên @msg File.seek: the position must be a finite number File.seek: vị trí phải là một số hữu hạn @msg File.seek: the mode must be 0, 1 or 2 File.seek: chế độ phải là 0, 1 hoặc 2 diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index e20c89b2f1..57f6a4403b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5582,21 +5582,6 @@ liquify-list-end {0}, {1} {0}和{1} @msg the script passed more data to and from commands than one run may pass 脚本与命令之间传递的数据超过了一次运行允许的数量 @msg the script added more objects and data to the documents than one run may add 脚本向文档添加的对象和数据超过了一次运行允许的数量 @msg {what}: the object is not a File or a Folder {what}:该对象既不是 File 也不是 Folder -@msg {what}: the library {name} is not available {what}:库 {name} 不可用 -@msg {what} is not available yet {what} 尚不可用 -@msg {what}: the value {value} is not available yet {what}:值 {value} 尚不可用 -@msg {what}: the object is not an {class} object {what}:该对象不是 {class} 对象 -@msg {what}: the XMP packet is not well-formed XMP {what}:XMP 数据包不是格式正确的 XMP -@msg {what}: the XMP data is too large {what}:XMP 数据过大 -@msg {what}: {name} is not a valid property name {what}:{name} 不是有效的属性名称 -@msg {what}: the text holds a character XML does not allow {what}:文本包含 XML 不允许的字符 -@msg {what}: {name} is not an array {what}:{name} 不是数组 -@msg {what}: {name} is not a simple property {what}:{name} 不是简单属性 -@msg {what}: {name} is not a language alternative array {what}:{name} 不是语言替代数组 -@msg {what}: the array index {index} is out of range {what}:数组索引 {index} 超出范围 -@msg {what}: the namespace {uri} is not registered {what}:命名空间 {uri} 未注册 -@msg {what}: the file is closed {what}:文件已关闭 -@msg {what}: the file cannot be updated {what}:文件无法更新 @msg {what}: the count must be a finite number, 0 or more {what}:数量必须是 0 或更大的有限数 @msg File.seek: the position must be a finite number File.seek:位置必须是有限数 @msg File.seek: the mode must be 0, 1 or 2 File.seek:模式必须是 0, 1 或 2 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index c18488af0e..9834c17ea6 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2928,21 +2928,6 @@ liquify-list-end {0}, {1} {0}和{1} @msg the script passed more data to and from commands than one run may pass 指令碼與命令之間傳遞的資料超過一次執行允許的數量 @msg the script added more objects and data to the documents than one run may add 指令碼加入文件的物件和資料超過一次執行允許的數量 @msg {what}: the object is not a File or a Folder {what}:此物件既不是 File 也不是 Folder -@msg {what}: the library {name} is not available {what}:程式庫 {name} 無法使用 -@msg {what} is not available yet {what} 尚無法使用 -@msg {what}: the value {value} is not available yet {what}:值 {value} 尚無法使用 -@msg {what}: the object is not an {class} object {what}:此物件不是 {class} 物件 -@msg {what}: the XMP packet is not well-formed XMP {what}:XMP 封包不是格式正確的 XMP -@msg {what}: the XMP data is too large {what}:XMP 資料過大 -@msg {what}: {name} is not a valid property name {what}:{name} 不是有效的屬性名稱 -@msg {what}: the text holds a character XML does not allow {what}:文字含有 XML 不允許的字元 -@msg {what}: {name} is not an array {what}:{name} 不是陣列 -@msg {what}: {name} is not a simple property {what}:{name} 不是簡單屬性 -@msg {what}: {name} is not a language alternative array {what}:{name} 不是語言替代陣列 -@msg {what}: the array index {index} is out of range {what}:陣列索引 {index} 超出範圍 -@msg {what}: the namespace {uri} is not registered {what}:命名空間 {uri} 未註冊 -@msg {what}: the file is closed {what}:檔案已關閉 -@msg {what}: the file cannot be updated {what}:檔案無法更新 @msg {what}: the count must be a finite number, 0 or more {what}:數量必須是 0 或更大的有限數 @msg File.seek: the position must be a finite number File.seek:位置必須是有限數 @msg File.seek: the mode must be 0, 1 or 2 File.seek:模式必須是 0, 1 或 2 diff --git a/docs/mcp.md b/docs/mcp.md index 5f394538d3..c1022c5933 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3072,7 +3072,8 @@ rules for these objects: missing file and a file over 8 MiB throw the `File` messages (`Script file access denied`, `Script file does not exist`, `Script file exceeds 8 MiB`). A `.xmp` file is read whole as its packet (a link counts by the file it leads to, when it is opened and again when it is written); any other file, and any file with - `XMPConst.OPEN_USE_PACKET_SCANNING`, is scanned for its first UTF-8 packet and is read only. Only a `.xmp` file + `XMPConst.OPEN_USE_PACKET_SCANNING`, is scanned for its first UTF-8 packet and is read only. A packet starts at a + ` Date: Sun, 22 Nov 2026 13:26:47 -0800 Subject: [PATCH 023/193] i18n: the message scan skips calls written inside string literals A marker such as `Err(`, an error variant, a `.map_err` or an error helper call that appears inside a string literal is text, not code. The scan matched these anyway, so a source holding `r##"Err(r#"sample error"#)"##` added "sample error" as a message. source_messages now finds every string and character literal span first and drops each match that starts inside one, and a new test covers the nested raw-string forms beside a real `Err(r#"..."#)` call. --- crates/ui-egui/src/i18n/tests.rs | 60 +++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b6200fb66a..7dd9a3f6a7 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2231,6 +2231,28 @@ fn string_literals(e: &str, keep: impl Fn(&str, &str) -> bool) -> Vec { out } +/// Where each string literal (its prefix included, see [`literal_at`]) and character literal in +/// `code` starts and ends, in order. +fn literal_spans(code: &str) -> Vec<(usize, usize)> { + let mut out = vec![]; + let mut i = 0; + while let Some(c) = code[i..].chars().next() { + let span = match c { + '"' => literal_at(code, i).map(|(start, end, _)| (start, end)), + '\'' => quoted_end(code, i).map(|end| (i, end)), + _ => None, + }; + match span { + Some((start, end)) => { + out.push((start, end)); + i = end; + } + None => i += c.len_utf8(), + } + } + out +} + /// For translators, `cargo test -p vectorcraft-ui-egui dump_source_strings` writes every English /// interface string to `VECTORCRAFT_I18N_DUMP=`, and every status and error message as a /// catalog template that [`untranslated_report`] checks to `VECTORCRAFT_I18N_DUMP_MESSAGES=`, @@ -4856,6 +4878,25 @@ fn run() -> Result<()> { assert_eq!(without_strings(r#"f('"', "a")"#), r#"f('"', "")"#); } +/// A marker, an error variant, a `.map_err` or an error helper call written inside a string literal +/// is text, not code: the scan reads no message from it, while the same call outside a literal +/// still gives its message. +#[test] +fn message_scan_skips_calls_inside_string_literals() { + let code = r####" +const SAMPLE: &str = r##"Err(r#"sample error"#)"##; +const VARIANT: &str = r##"Error::Lost(r#"variant error"#)"##; +const CLOSURE: &str = r##"load().map_err(|e| format!(r#"closure error {e}"#))"##; +const HELPER: &str = r##"bad(cmd, r#"helper error"#)"##; +fn run() -> Result<()> { + let _ = Err(r#"real error"#); + Ok(()) +} +"####; + let found = source_messages(code, &[("bad(", 1)], &Default::default()); + assert_eq!(found, ["real error"]); +} + /// A bracket in a character literal among a `format!`'s arguments does not end them: the scan /// removes the arguments up to the `format!`'s own closing parenthesis. #[test] @@ -7263,25 +7304,33 @@ fn named_const<'a>(rest: &str, consts: &'a std::collections::BTreeMap>) -> Vec { let code = &without_comments(code); + let spans = &literal_spans(code); + // Whether `code[at]` is inside a string or character literal, where a call is text, not code. + let in_literal = move |at: usize| { + let k = spans.partition_point(|&(start, _)| start <= at); + k > 0 && at < spans[k - 1].1 + }; + let code_matches = move |pat: &'static str| code.match_indices(pat).filter(move |&(at, _)| !in_literal(at)); let after_markers = - MESSAGE_MARKERS.iter().flat_map(|marker| code.match_indices(marker).map(|(at, _)| (&code[at + marker.len()..], *marker == "#[error("))); - let in_variants = ["Error::", "Fail::"].into_iter().flat_map(|enum_end| code.match_indices(enum_end)).filter_map(|(at, m)| { + MESSAGE_MARKERS.iter().flat_map(|marker| code_matches(marker).map(|(at, _)| (&code[at + marker.len()..], *marker == "#[error("))); + let in_variants = ["Error::", "Fail::"].into_iter().flat_map(code_matches).filter_map(|(at, m)| { let rest = &code[at + m.len()..]; let (variant, args) = rest.split_at(rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_').unwrap_or(rest.len())); let named = variant.starts_with(|c: char| c.is_ascii_uppercase()) && !NAME_VARIANTS.contains(&variant); let before = LATER_MESSAGE_VARIANTS.iter().find(|(v, _)| *v == variant).map_or(0, |&(_, n)| n); if named { skip_args(args.strip_prefix('(')?, before).map(|rest| (rest, false)) } else { None } }); - let in_map_err = code.match_indices(".map_err(").flat_map(|(at, m)| { + let in_map_err = code_matches(".map_err(").flat_map(|(at, m)| { let rest = code[at + m.len()..].trim_start(); let params = rest.strip_prefix("move").map_or(rest, str::trim_start).strip_prefix('|'); params.and_then(|p| p.find('|').map(|end| &p[end + 1..])).map(closure_returns).unwrap_or_default() }); let mut handlers = vec![]; - for (at, m) in code.match_indices(".map_err(") { + for (at, m) in code_matches(".map_err(") { let rest = &code[at + m.len()..]; let name = &rest[..rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_').unwrap_or(rest.len())]; if name.starts_with(|c: char| c.is_ascii_lowercase()) && rest[name.len()..].starts_with(')') && !handlers.contains(&name) { @@ -7291,6 +7340,7 @@ fn source_messages(code: &str, helpers: &[(&str, usize)], consts: &std::collecti let in_handlers = handlers.into_iter().flat_map(|name| handler_returns(code, name)); let in_helpers = helpers.iter().flat_map(|&(call, before)| { code.match_indices(call) + .filter(move |&(at, _)| !in_literal(at)) .filter(|&(at, _)| call.starts_with('.') || !code[..at].ends_with(|c: char| c.is_alphanumeric() || c == '_' || c == '.')) .filter(|&(at, _)| { let owner = code[..at].strip_suffix("::").map(|p| p.rsplit(|c: char| !c.is_alphanumeric() && c != '_').next().unwrap_or("")); From 2894c60473c332a43076cfc0569528c695fcd610 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 13:40:36 -0800 Subject: [PATCH 024/193] Scripts: XMP packets are checked as they are read and written, and safe closes use a temporary file - closeFile with XMPConst.CLOSE_UPDATE_SAFELY passes the flag to xmpWrite, which then writes only through a temporary file; where none may be made it throws and leaves the sidecar and the packet as they are. - On Unix the temporary file is created with mode 0600 and takes the sidecar's permission bits after the packet is written. - canPutXMP and putXMP check again that the file is open for update after converting the packet argument, since a toString may close it. - Path arguments are converted once, so a toString that changes between calls cannot mix two paths. - setLocalizedText moves an existing x-default item to the front. - A second ExternalObject install is refused and keeps the registered namespaces. - Text beside rdf:Description elements or their properties makes a packet malformed. - Properties read from a packet share one copy of each namespace URI, and reading stops once the properties exceed the script heap. - A value with qualifiers in the rdf:value form gives the text and options of its rdf:value, and an empty property element whose attributes are fields is a structure. - serialize() and reading refuse a value that would be written with more than 1,024 attributes or namespace declarations in scope at one element. - find_packet treats packet markers inside CDATA sections and comments as text, and passes over a packet that is not UTF-8 for the next one. A section that holds a trailer and then a start does not hide that start, and each marker search starts where the last one stopped, so the scan reads the bytes about once. - An rdf:Alt item with xml:lang="" has no language, so its array is not a language alternative; the empty attribute is written back as it was. - The rdf:about value counts toward the parse budget, also in a packet with no properties. - docs/mcp.md says that the prefix limit applies to a namespace being registered. - The round-trip property test generates valid packets, the retry test closes the same XMPFile again after a failed write, and the heap-limit test requires a heap-limit error and a change that goes through. --- crates/engine/src/script/files.rs | 35 ++- crates/engine/src/tests/script_xmp.rs | 137 ++++++++-- crates/js/src/realm.rs | 5 +- crates/js/src/xmp.rs | 377 +++++++++++++++++++++----- crates/js/src/xmp_classes.rs | 112 +++++--- crates/js/src/xmp_tests.rs | 288 +++++++++++++++++++- docs/mcp.md | 26 +- 7 files changed, 821 insertions(+), 159 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index e556449148..2a6d2ec971 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1925,13 +1925,14 @@ fn xmp_open(host: &Host, a: &[Data]) -> Result { ])) } -/// `xmpWrite(path, packet)`: 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. Open objects of the -/// file hold the new bytes. +/// `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. fn xmp_write(host: &Host, a: &[Data]) -> Result { let path = arg_text(a, 0); let packet = arg_text(a, 1).into_bytes(); + let safely = matches!(a.get(2), Some(Data::Bool(true))); if !is_sidecar(&path) { return Ok(error(ACCESS_DENIED)); } @@ -1955,12 +1956,16 @@ fn xmp_write(host: &Host, a: &[Data]) -> Result { if disk.open.values().any(|o| o.dirty && o.holds(&target)) { 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)))?; 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 { @@ -1968,7 +1973,15 @@ fn xmp_write(host: &Host, a: &[Data]) -> Result { // 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| allowed(t).then(|| std::fs::OpenOptions::new().write(true).create_new(true).open(t).ok()).flatten(); + 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)); }; @@ -1977,6 +1990,11 @@ fn xmp_write(host: &Host, a: &[Data]) -> Result { 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) }; let r = write_temp(); @@ -2650,6 +2668,9 @@ thread_local! { 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) }; + /// 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/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs index 6c68cadcff..b39f3b28d7 100644 --- a/crates/engine/src/tests/script_xmp.rs +++ b/crates/engine/src/tests/script_xmp.rs @@ -491,33 +491,56 @@ fn a_huge_sidecar_is_refused_before_it_is_read() { let _ = std::fs::remove_dir_all(base); } +/// The file named `name` in `dir` or a folder inside it. +fn find_file(dir: &Path, name: &str) -> 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` writes it; an `XMPFile` from an earlier run is closed. +/// 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); - let setup = format!( - "var p = Folder.userData.fsName + '/k.xmp'; var f = new File(p); f.open('w'); f.write({PACKET:?}); f.close();\n\ - $.global.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\ - vc.log(out); vc.log(p);" - ); crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(true)); - let log = logged(&mut s, &base, &setup); - crate::script::files::XMP_WRITE_FAILS.with(|f| f.set(false)); - assert_eq!(log[0], json!(["Script file could not be written", "changed"])); - let path = PathBuf::from(log[1].as_str().unwrap()); - assert!(std::fs::read_to_string(&path).unwrap().contains("image/svg+xml"), "the failed write leaves the file as it was"); - let log = logged( + start_framed( &mut s, &base, &format!( - "{setup}\nvc.log(new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_READ).getXMP().getProperty(XMPConst.NS_DC, 'format').value);" + "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);" ), ); - assert_eq!(log, json!([["closed"], path.to_string_lossy(), "changed"])); + 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); +} + +/// 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()); @@ -532,3 +555,85 @@ fn a_failed_write_keeps_the_packet_for_a_later_close() { 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 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/js/src/realm.rs b/crates/js/src/realm.rs index a9826703ed..4fc7619fb9 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -508,7 +508,10 @@ impl Realm { /// 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. + /// `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 second call fails with an internal error and leaves the realm's + /// `ExternalObject` and its registered namespaces as they are. pub fn define_external_object(&mut self) -> Result<(), RunError> { match crate::xmp_classes::install(&mut self.interp) { Ok(()) => Ok(()), diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index 8b508c1d6c..2d4be10caf 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -10,19 +10,23 @@ //! 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. The namespaces of the property, element 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, a child of `rdf:RDF` other than `rdf:Description` makes the -//! packet malformed, a property given twice keeps its first value, and [`find_packet`] finds only a -//! UTF-8 packet. A realm registers at most [`MAX_NAMESPACES`] namespaces holding at most +//! 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, a property given twice keeps its first value, and +//! [`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}; @@ -100,6 +104,8 @@ pub(crate) enum XmpError { BadText, /// A path form not read yet: a structure field, a qualifier or a selector. NotYet, + /// The metadata a packet gives is larger than the budget [`parse_within`] was given. + Heap, } /// The kind of an array. @@ -148,6 +154,13 @@ pub(crate) struct Item { pub(crate) lang: Option, } +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()) + } +} + /// A property's value. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum Value { @@ -165,6 +178,8 @@ pub(crate) enum Value { xml: String, options: u32, text: Option, + /// The most namespace declarations `xml` puts in scope at one of its elements. + decls: usize, }, } @@ -180,7 +195,7 @@ impl Value { } } Value::Array { form, items } => { - let alt_text = *form == Form::Alt && !items.is_empty() && items.iter().all(|i| i.lang.is_some()); + 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, @@ -200,7 +215,8 @@ impl Value { /// A top-level property. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Prop { - pub(crate) ns: String, + /// 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, } @@ -232,7 +248,7 @@ impl Meta { /// 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) + self.props.iter().position(|p| &*p.ns == ns && p.name == name) } } @@ -445,16 +461,64 @@ fn find_rdf<'a>(el: &'a El, scope: &mut Scope) -> Option<&'a El> { None } -/// Reads the packet `text`, registering the namespaces it uses in `registry`. A packet that fails -/// to read leaves `registry` unchanged. +/// 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)?; + let meta = parse_into(text, &mut staged, budget)?; *registry = staged; Ok(meta) } -fn parse_into(text: &str, registry: &mut Registry) -> Result { +/// 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, +} + +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) -> Result { if text.len() > MAX_BYTES { return Err(XmpError::TooLarge); } @@ -472,19 +536,26 @@ fn parse_into(text: &str, registry: &mut Registry) -> Result { let root = opts.parse(text.as_bytes()).map_err(|e| if e.is_limit() { XmpError::TooLarge } else { XmpError::Malformed })?; let mut scope = Scope::new(); let rdf = find_rdf(&root, &mut scope).ok_or(XmpError::Malformed)?; - let mut meta = Meta::default(); - let mut seen = HashSet::new(); + // 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 }; for d in rdf.elements() { let mark = scope.len(); push_decls(d, &mut scope); - if !is_named(&d.name, &scope, true, RDF, "Description") { + if !is_named(&d.name, &scope, true, RDF, "Description") || d.children.iter().any(is_stray_text) { return Err(XmpError::Malformed); } 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" && meta.about.is_empty() { - meta.about = v.to_string(); + 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; } @@ -493,26 +564,19 @@ fn parse_into(text: &str, registry: &mut Registry) -> Result { } let prefix = k.split_once(':').map_or("ns", |(p, _)| p); registry.register(&ns, prefix)?; - add(&mut meta, &mut seen, Prop { ns, name: local.to_string(), value: Value::Simple { text: v.to_string(), uri: false } }); + 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)?; - add(&mut meta, &mut seen, prop); + let prop = read_property(p, &mut scope, registry, &mut reading)?; + reading.add(prop)?; } scope.truncate(mark); } - Ok(meta) + Ok(reading.meta) } -/// Adds `prop` to `meta` unless it already has a property of that name; `seen` holds the names -/// `meta` has. -fn add(meta: &mut Meta, seen: &mut HashSet<(String, String)>, prop: Prop) { - if seen.insert((prop.ns.clone(), prop.name.clone())) { - meta.props.push(prop); - } -} - -fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry) -> Result { +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)?; @@ -540,10 +604,10 @@ fn read_property(p: &El, scope: &mut Scope, registry: &mut Registry) -> Result

Option { } } -/// A value kept as the XML it was read as. -fn other(p: &El, own: &[(&str, &str)], children: &[&El], scope: &mut Scope, mark: usize) -> Value { - // The first child's name is read with the prefixes it declares itself. - let form = children.first().and_then(|c| { - let inner = scope.len(); - push_decls(c, scope); - let form = [Form::Bag, Form::Seq, Form::Alt].into_iter().find(|f| is_named(&c.name, scope, true, RDF, &f.element()[4..])); - scope.truncate(inner); - form - }); +/// 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) -> Result { + let (options, text) = match qualified_value(own, children, scope) { + Some(found) => found, + None => kept_form(p, own, children, scope), + }; + let mut xml = String::new(); + 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, 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")); - let (options, text) = match form { + // 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 }; - let mut xml = String::new(); - write_fragment(p, scope.get(..mark).unwrap_or(&[]), &mut xml); - Value::Other { xml, options, text } + 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 } } /// Writes the element `p` as XML, declaring on it the prefixes from `outer` that it and the -/// elements inside it use and do not declare themselves. -fn write_fragment(p: &El, outer: &[(String, String)], out: &mut String) { +/// elements inside it use and do not declare themselves. → the declarations it added. +fn write_fragment(p: &El, outer: &[(String, String)], out: &mut String) -> usize { 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_str(&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_str(" xmlns=\""); } else { @@ -661,6 +825,7 @@ fn write_fragment(p: &El, outer: &[(String, String)], out: &mut String) { } } write_rest(p, out); + added } /// The prefixes the names of `el` and the elements inside it use, `""` for an unprefixed element. @@ -740,11 +905,19 @@ pub(crate) fn serialize(meta: &Meta, registry: &Registry, wrapper: bool) -> Resu 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.as_str()) { + 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)); + 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()); @@ -824,37 +997,97 @@ pub(crate) fn pad_size(packet: &str) -> usize { /// 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_header = |at: usize| { - 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())) + 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())) + } }; - // The first start from `from` that begins before `to`. - let start_in = |mut from: usize, to: usize| loop { - let at = find(from, to, BEGIN)?; - if is_header(at) { - return Some(at); + // 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 pos = 0; + while let Some(at) = rest(pos).iter().position(|&b| b == b'<').map(|i| i + pos) { + pos = at + 1; + if starts.binary_search(&at).is_ok() { + start = Some(at); + pos = at + BEGIN.len(); + continue; } - from = at + BEGIN.len(); - }; - let mut start = start_in(0, len)?; - loop { - let end_tag = find(start + BEGIN.len(), len, END)?; - while let Some(next) = start_in(start + BEGIN.len(), end_tag) { - start = next; + let Some(from) = start else { + // Nothing before the next start matters. + pos = start_after(pos)?; + continue; + }; + let here = rest(at); + 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(); + } + continue; } - let after = end_tag + END.len(); - let next = start_in(after, len); - match find(after, next.unwrap_or(len), b"?>") { - Some(close) => return Some(PacketSpan { start, end: close + 2, writeable: bytes.get(after + 1) == Some(&b'w') }), - None => start = next?, + 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); + pos = next + BEGIN.len(); + continue; + } + let span = PacketSpan { start: from, end: close + 2, writeable: bytes.get(after + 1) == Some(&b'w') }; + if bytes.get(span.start..span.end).is_some_and(|p| std::str::from_utf8(p).is_ok()) { + return Some(span); + } + start = None; + pos = 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 } } diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 9d7db14901..974be6b645 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -24,7 +24,8 @@ //! `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; an +//! `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 run that opened it, and a packet it kept and did not write is //! dropped when the run ends. 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. @@ -125,6 +126,7 @@ fn xmp_error(i: &mut Interp, what: &str, e: XmpError, name: &str) -> Abrupt { 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), } } @@ -313,7 +315,8 @@ fn parse_packet(i: &mut Interp, what: &str, text: &str) -> JsResult { // Reading copies the realm's namespaces. let copied = registry(i)?.bytes(); spend(i, text.len().saturating_add(copied))?; - let r = xmp::parse(text, registry(i)?); + let budget = i.limits.heap_bytes; + let r = xmp::parse_within(text, registry(i)?, budget); r.map_err(|e| xmp_error(i, what, e, "")) } @@ -340,8 +343,18 @@ fn namespace(i: &mut Interp, v: &Value, what: &str) -> JsResult { Ok(uri) } -/// The namespace and path arguments at `at`: the namespace, the property name and its step. -fn target(i: &mut Interp, args: &[Value], at: usize, what: &str) -> JsResult<(String, String, Step)> { +/// 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. @@ -350,7 +363,7 @@ fn target(i: &mut Interp, args: &[Value], at: usize, what: &str) -> JsResult<(St } let r = xmp::parse_path(&path, &ns, registry(i)?); match r { - Ok((name, step)) => Ok((ns, name, step)), + Ok((name, step)) => Ok(Target { ns, name, step, path }), Err(e) => Err(xmp_error(i, what, e, &path)), } } @@ -395,12 +408,11 @@ fn property_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsRe fn get_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.getProperty"; let o = this_meta(i, &this, what)?; - let (ns, name, step) = target(i, args, 0, 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 path = text(i, &arg(args, 1))?; let found = { let m = meta_of(i, o)?; m.find(&ns, &name).map(|at| m.props[at].value.clone()) @@ -421,7 +433,7 @@ fn get_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.setProperty"; let o = this_meta(i, &this, what)?; - let (ns, name, step) = target(i, args, 0, 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) { @@ -449,7 +461,7 @@ fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul Some(true) => Ok(Value::Undefined), Some(false) => Err(not_array(i, what, &name)), None => { - let prop = xmp::Prop { ns, name, value: xmp::Value::Array { form: Form::from_options(options), items: Vec::new() } }; + 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) } }; @@ -471,7 +483,7 @@ fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul }) } None => { - let prop = xmp::Prop { ns, name, value: new }; + let prop = xmp::Prop { ns: ns.into(), name, value: new }; change(i, o, prop.heap_bytes(), |m, _| m.props.push(prop)) } } @@ -481,7 +493,7 @@ fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul fn delete_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let what = "XMPMeta.deleteProperty"; let o = this_meta(i, &this, what)?; - let (ns, name, step) = target(i, args, 0, what)?; + let Target { ns, name, step, .. } = target(i, args, 0, what)?; match step { Step::Whole => { let at = meta_of(i, o)?.find(&ns, &name); @@ -497,7 +509,7 @@ fn delete_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe 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 (ns, name, step) = target(i, args, 0, 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, @@ -525,20 +537,19 @@ fn array_items(i: &mut Interp, o: ObjId, ns: &str, name: &str, what: &str) -> Js } } -/// The array name argument at `at` after the namespace: a whole property. -fn array_target(i: &mut Interp, args: &[Value], what: &str) -> JsResult<(String, String)> { - let (ns, name, step) = target(i, args, 0, what)?; - if step != Step::Whole { - let path = text(i, &arg(args, 1))?; - return Err(not_handled(i, what, &path)); +/// 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((ns, name)) + 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 (ns, name) = array_target(i, args, 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)) } @@ -546,7 +557,7 @@ fn count_array_items(i: &mut Interp, this: Value, args: &[Value], _: bool) -> Js 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 (ns, name) = array_target(i, args, 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) }; @@ -555,14 +566,14 @@ fn get_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRes _ => None, }; let Some(item) = item else { return Ok(Value::Undefined) }; - let path = format!("{}[{}]", text(i, &arg(args, 1))?, p + 1); + let path = format!("{path}[{}]", p + 1); property(i, &ns, &path, Some(&item.text), 0, 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 (ns, name) = array_target(i, args, 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())) @@ -597,11 +608,8 @@ fn insert_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: Option { let Some(form) = form else { return Err(not_array(i, what, name)) }; - let prop = xmp::Prop { - ns: ns.to_string(), - name: name.to_string(), - value: xmp::Value::Array { form, items: vec![Item { text: value, lang: None }] }, - }; + 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))?; } } @@ -655,7 +663,7 @@ fn delete_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: i64, what: 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 (ns, name) = array_target(i, args, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; // `itemOptions` may be left out: a string or `null` third argument is the item's value. let (value, array_options) = match arg(args, 2) { Value::Number(_) => { @@ -674,7 +682,7 @@ fn append_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> Js 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 (ns, name) = array_target(i, args, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; let index = item_index(i, &arg(args, 2), what)?; let value = xml_text(i, &arg(args, 3), what)?; item_options(i, &arg(args, 4), what)?; @@ -684,7 +692,7 @@ fn insert_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> Js 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 (ns, name) = array_target(i, args, what)?; + let Target { ns, name, .. } = array_target(i, args, what)?; let index = item_index(i, &arg(args, 2), what)?; let value = xml_text(i, &arg(args, 3), what)?; item_options(i, &arg(args, 4), what)?; @@ -694,7 +702,7 @@ fn set_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRes 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 (ns, name) = array_target(i, args, 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) } @@ -733,10 +741,10 @@ fn lang(i: &mut Interp, v: &Value, what: &str) -> JsResult { } /// Is the property at `at` of `o` a language alternative: an `rdf:Alt` whose items, if it has any, -/// all have a language? +/// 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| item.lang.is_some()), + Some(xmp::Value::Array { form: Form::Alt, items }) => items.iter().all(Item::has_lang), _ => false, }) } @@ -744,7 +752,7 @@ fn is_alt_text(i: &Interp, o: ObjId, at: usize) -> JsResult { 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 (ns, name) = array_target(i, args, 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, _, _)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) }; @@ -764,7 +772,7 @@ fn get_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J 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 (ns, name) = array_target(i, args, 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) { @@ -776,7 +784,7 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J 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, name, value: xmp::Value::Array { form: Form::Alt, items: Vec::new() } })), + 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) { @@ -806,6 +814,13 @@ fn set_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J /// 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()) { @@ -1094,7 +1109,7 @@ fn packet_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { // registers nothing. let mut scratch = registry(i)?.clone(); spend(i, s.len().saturating_add(2 * scratch.bytes()))?; - xmp::parse(&s, &mut scratch).map_err(|e| xmp_error(i, what, e, ""))?; + xmp::parse_within(&s, &mut scratch, i.limits.heap_bytes).map_err(|e| xmp_error(i, what, e, ""))?; Ok(s) } @@ -1106,7 +1121,11 @@ fn can_put_xmp(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult } let packet = packet_arg(i, &arg(args, 0), what); match packet { - Ok(_) => Ok(Value::Bool(true)), + // 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), } @@ -1119,6 +1138,11 @@ fn put_xmp(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult< 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 r = i.rooted(&[path.clone(), pending.clone()], |i| crate::file_classes::call_host(i, "xmpWrite", &[path.clone(), pending.clone()]))?; + 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. @@ -1247,8 +1273,12 @@ fn link(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { } /// Adds the global `ExternalObject`, which defines `XMPMeta`, `XMPFile` and `XMPConst` when a -/// script loads the XMP library ([`crate::Realm::define_external_object`]). +/// script loads the XMP library ([`crate::Realm::define_external_object`]). A second call is +/// refused and changes nothing, so the namespaces registered stay. 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))); diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 293b4d3157..039d111a8b 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -1,7 +1,7 @@ use proptest::prelude::*; use crate::xmp::{self, Form, Registry, XmpError}; -use crate::{JsValue, Limits, Realm, RunErrorKind}; +use crate::{JsValue, LimitKind, Limits, Realm, RunErrorKind}; fn realm() -> Realm { let mut r = Realm::with_options(crate::Options::default(), Limits::default()); @@ -354,6 +354,7 @@ fn localized_text_updates_a_single_generic_language_item() { #[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() }); @@ -365,17 +366,24 @@ fn localized_text_past_the_heap_limit_adds_no_array() { seen.push(format!("{step} text {e:?}")); continue; } - if r.run("m.setLocalizedText(XMPConst.NS_DC, 'title', null, s, s);").is_ok() { - seen.push(format!("{step} set")); - break; - } - stopped += 1; - match r.run("m.doesPropertyExist(XMPConst.NS_DC, 'title')") { - Ok(v) => assert_eq!(v, JsValue::Bool(false), "heap step {step}"), - Err(e) => panic!("{e:?}"), + 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. @@ -444,11 +452,13 @@ fn text_beside_an_array_is_kept() { #[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"] { - assert_eq!( - thrown(&format!("new XMPMeta().setProperty({ns:?}, 'foo', 'x')")), - "Error: XMPMeta.setProperty: foo is not a valid property name", - "{ns}" - ); + 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" @@ -456,6 +466,196 @@ fn rdf_and_xml_namespaces_hold_no_properties() { } } +/// 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()))); +} + +/// 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); @@ -490,9 +690,69 @@ const PIECES: &[&str] = &[ "", ]; +/// 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] diff --git a/docs/mcp.md b/docs/mcp.md index c1022c5933..11446fc177 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3062,29 +3062,39 @@ rules for these objects: `setArrayItem`, `deleteArrayItem`, `doesArrayItemExist`, `getLocalizedText` and `setLocalizedText`, and the functions `XMPMeta.registerNamespace`, `getNamespacePrefix` and `getNamespaceURI`. A path is a property name, `prefix:name`, or either with `[n]` (from 1) or `[last()]` for an array item. Arrays hold simple items; a structure - or a value with qualifiers that a packet holds is kept as it was written, and `getProperty` gives its options. - The namespaces that a packet's property, element and attribute names use are registered with the prefix the packet + or a value with qualifiers that a packet holds is kept as it was written, and `getProperty` gives its options. A + value with qualifiers in the `rdf:value` form also gives the text of its `rdf:value`, and an empty property element + whose attributes are fields is a structure. The namespaces that a packet's property, element and attribute names use are registered with the prefix the packet gives them, or `prefix_1_` when that prefix names another namespace; a namespace the packet declares but no name uses is not registered. At most 4,096 namespaces, holding at most 1 MiB together, are registered. A namespace URI over 1,024 bytes, a prefix over 128 bytes, and a namespace past either limit throw `… the XMP data is too large`, - both from `registerNamespace` and from a packet that uses the namespace. + both from `registerNamespace` and from a packet that uses the namespace. The prefix limit applies to a namespace + being registered, with any `_n_` suffix added to its prefix; a namespace already registered keeps its prefix, and + `registerNamespace` returns that prefix whatever prefix it is given. An `rdf:Alt` item with `xml:lang=""` has no + language, so its array is not a language alternative for `getLocalizedText` and `setLocalizedText`. - `XMPFile(path, format, openFlags)` reads a file through the same places as `File`, so a path outside them, a missing file and a file over 8 MiB throw the `File` messages (`Script file access denied`, `Script file does not exist`, `Script file exceeds 8 MiB`). A `.xmp` file is read whole as its packet (a link counts by the file it leads to, when it is opened and again when it is written); any other file, and any file with `XMPConst.OPEN_USE_PACKET_SCANNING`, is scanned for its first UTF-8 packet and is read only. A packet starts at a - ` Date: Sun, 22 Nov 2026 16:01:53 -0800 Subject: [PATCH 025/193] Scripts: a replaced XMP sidecar keeps its group and access ACL closeFile() now replaces a sidecar through vectorcraft_format::keep_permissions, the same step a saved document takes. On Unix the temporary file takes the sidecar's permission bits, group and (on Linux) access ACL, or stays readable by its owner alone where the group or the ACL cannot be kept. Permission bits that cannot be set fail the write, and the sidecar stays as it was. A Linux test checks that a folder's default ACL does not reach a replaced sidecar. --- crates/engine/src/script/files.rs | 20 ++++++++--------- crates/engine/src/tests/script_xmp.rs | 31 +++++++++++++++++++++++++++ crates/format/src/atomic.rs | 8 ++++--- crates/format/src/lib.rs | 2 +- docs/mcp.md | 4 +++- 5 files changed, 50 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 2a6d2ec971..d0de6896c7 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1999,16 +1999,16 @@ fn xmp_write(host: &Host, a: &[Data]) -> Result { }; let r = write_temp(); drop(out); - // The replacement keeps the sidecar's permission bits. On Windows the only permission is the - // read-only attribute, and a read-only temporary file could not be removed after a failed - // rename. - let permissions = if cfg!(unix) { std::fs::metadata(&target).map(|m| m.permissions()).ok() } else { None }; - let r = r - .and_then(|()| permissions.map_or(Ok(()), |p| std::fs::set_permissions(&temp, p))) - .and_then(|()| std::fs::rename(&temp, &target)) - .inspect_err(|_| { - let _ = std::fs::remove_file(&temp); - }); + // 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. Permission + // bits that cannot be set fail the write, and the sidecar stays as it was. + #[cfg(not(target_arch = "wasm32"))] + let r = r.and_then(|()| 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 { diff --git a/crates/engine/src/tests/script_xmp.rs b/crates/engine/src/tests/script_xmp.rs index b39f3b28d7..40352cdd3d 100644 --- a/crates/engine/src/tests/script_xmp.rs +++ b/crates/engine/src/tests/script_xmp.rs @@ -583,6 +583,37 @@ fn a_temporary_file_starts_private() { 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] diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index e8f3c42b8e..8d034ab5df 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -302,9 +302,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(()) }; @@ -340,8 +341,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 430769069d..996bad2b4a 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -56,7 +56,7 @@ use vectorcraft_brush::stored_art::StoredArt; use vectorcraft_doc::{Document, ImageBlob}; #[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/docs/mcp.md b/docs/mcp.md index 11446fc177..d365ca743b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3084,7 +3084,9 @@ rules for these objects: the script may not write throws `Script file access denied`; other files open read only with that flag. After `putXMP`, `closeFile()` writes the packet in UTF-8 through a temporary file in the same folder when the script may write there, otherwise straight to the file; - when no temporary name is free, nothing is written. With `XMPConst.CLOSE_UPDATE_SAFELY`, `closeFile()` writes only + when no temporary name is free, nothing is written. On Unix the replacement keeps the file's permission bits, group + and (on Linux) access ACL, as a saved document does, and is readable by its owner alone where the group or the ACL + cannot be kept. With `XMPConst.CLOSE_UPDATE_SAFELY`, `closeFile()` writes only through a temporary file, and where the script may not make one it throws `Script file could not be written` and leaves the file as it is. A failed write throws and keeps the file open with its packet. While an open `File` of the same file holds changes it has not written, `closeFile()` throws `Script file could not be written` and the `File` keeps its changes. `getXMP`, `getPacketInfo`, `getFileInfo` and `canPutXMP` are available. An `XMPFile` is open only in the From a0cc0230b034809149c9945e183e0020caf0f3c3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:52:35 -0800 Subject: [PATCH 026/193] Scripts: an XMP sidecar update flushes the packet first and goes through on volumes without Unix permissions - closeFile() flushes the temporary file to the disk with vectorcraft_format::sync_file before it takes the sidecar's name, as a saved document's temporary file is flushed. - Keeping the sidecar's permissions is best effort, as in write_atomic: a volume that refuses Unix permissions (SMB, FAT) no longer makes every update throw "Script file could not be written". - docs/mcp.md says both. --- crates/engine/src/script/files.rs | 15 +++++++++++---- docs/mcp.md | 3 ++- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index d0de6896c7..762dae099a 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1995,17 +1995,24 @@ fn xmp_write(host: &Host, a: &[Data]) -> Result { 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) + 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. Permission - // bits that cannot be set fail the write, and the sidecar stays as it was. + // 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"))] - let r = r.and_then(|()| vectorcraft_format::keep_permissions(&target, &temp)); + 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); }); diff --git a/docs/mcp.md b/docs/mcp.md index d365ca743b..5fd06c6901 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3086,7 +3086,8 @@ rules for these objects: UTF-8 through a temporary file in the same folder when the script may write there, otherwise straight to the file; when no temporary name is free, nothing is written. On Unix the replacement keeps the file's permission bits, group and (on Linux) access ACL, as a saved document does, and is readable by its owner alone where the group or the ACL - cannot be kept. With `XMPConst.CLOSE_UPDATE_SAFELY`, `closeFile()` writes only + cannot be kept; on a volume that refuses Unix permissions (SMB, FAT) the update still goes through. The packet is flushed to the disk before the temporary file takes the file's + name. With `XMPConst.CLOSE_UPDATE_SAFELY`, `closeFile()` writes only through a temporary file, and where the script may not make one it throws `Script file could not be written` and leaves the file as it is. A failed write throws and keeps the file open with its packet. While an open `File` of the same file holds changes it has not written, `closeFile()` throws `Script file could not be written` and the `File` keeps its changes. `getXMP`, `getPacketInfo`, `getFileInfo` and `canPutXMP` are available. An `XMPFile` is open only in the From c17e7936efc62a33cbbc204a99e80c9551cc0310 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:01:22 -0800 Subject: [PATCH 027/193] Scripts: the host-name tables list ExternalObject and its members script_host_vs_scriptcheck failed on this branch because the host now adds the global ExternalObject. It goes in the table of names that reach outside the document, with the nativeCode id that script.check gives it; its length, prototype, search, constructor and terminate members stay inside. --- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 660433b800..fc1d5f9bf9 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. @@ -47,6 +48,8 @@ const INSIDE: &[(&str, &str)] = &[ ("Object.prototype.", "toSource"), ("localize.", "length"), ("toSource.", "length"), + ("ExternalObject.", "length prototype search"), + ("ExternalObject.prototype.", "constructor terminate"), ( "$.", "about appEncoding appEncoding= bp build buildDate colorPicker decimalPoint engineName error fileName flags \ From 74ca9fb769f48a2c4f2a9422888726c88315f218 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:01:23 -0800 Subject: [PATCH 028/193] Scripts: XMP array items with xml:lang report the qualifier and language options getProperty with an item path and getArrayItem gave an item with an xml:lang qualifier the options 0. They now give PROP_HAS_QUALIFIERS and PROP_HAS_LANG, as a property with xml:lang has, and docs/mcp.md says so. --- crates/js/src/xmp.rs | 6 ++++++ crates/js/src/xmp_classes.rs | 4 ++-- crates/js/src/xmp_tests.rs | 11 +++++++++++ docs/mcp.md | 3 ++- 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/js/src/xmp.rs b/crates/js/src/xmp.rs index 2d4be10caf..fd1bff54f5 100644 --- a/crates/js/src/xmp.rs +++ b/crates/js/src/xmp.rs @@ -159,6 +159,12 @@ impl Item { 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. diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 974be6b645..4587570ebe 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -422,7 +422,7 @@ fn get_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul Step::Whole => property(i, &ns, &path, value.text(), value.options(), ""), Step::Item(index) => match value { xmp::Value::Array { items, .. } => match position(index, items.len()).and_then(|p| items.get(p)) { - Some(item) => property(i, &ns, &path, Some(&item.text), 0, item.lang.as_deref().unwrap_or("")), + Some(item) => property(i, &ns, &path, Some(&item.text), item.options(), item.lang.as_deref().unwrap_or("")), None => Ok(Value::Undefined), }, _ => Err(not_array(i, what, &name)), @@ -567,7 +567,7 @@ fn get_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRes }; let Some(item) = item else { return Ok(Value::Undefined) }; let path = format!("{path}[{}]", p + 1); - property(i, &ns, &path, Some(&item.text), 0, item.lang.as_deref().unwrap_or("")) + 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 { diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index 039d111a8b..391d09696f 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -76,6 +76,17 @@ fn a_packet_reads_into_properties() { 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/'; diff --git a/docs/mcp.md b/docs/mcp.md index 5fd06c6901..f453f92b2b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3062,7 +3062,8 @@ rules for these objects: `setArrayItem`, `deleteArrayItem`, `doesArrayItemExist`, `getLocalizedText` and `setLocalizedText`, and the functions `XMPMeta.registerNamespace`, `getNamespacePrefix` and `getNamespaceURI`. A path is a property name, `prefix:name`, or either with `[n]` (from 1) or `[last()]` for an array item. Arrays hold simple items; a structure - or a value with qualifiers that a packet holds is kept as it was written, and `getProperty` gives its options. A + or a value with qualifiers that a packet holds is kept as it was written, and `getProperty` gives its options. An + array item with an `xml:lang` qualifier has the qualifier and language options in `getProperty` and `getArrayItem`. A value with qualifiers in the `rdf:value` form also gives the text of its `rdf:value`, and an empty property element whose attributes are fields is a structure. The namespaces that a packet's property, element and attribute names use are registered with the prefix the packet gives them, or `prefix_1_` when that prefix names another namespace; a namespace the packet declares but no name From 01566a41206dc8f67b48c0b910fffdcd783576b9 Mon Sep 17 00:00:00 2001 From: ViktorBystrov72 <18964918+ViktorBystrov72@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:52:04 +0500 Subject: [PATCH 029/193] Place: measure aligned point type in embedded native artwork --- crates/engine/src/cmd/place/document.rs | 7 +++++++ crates/engine/src/tests/place.rs | 22 ++++++++++++++++++++++ 2 files changed, 29 insertions(+) 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/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] From a99db2ce13c7c2c558df76c6f38f5b2bd5a38b06 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 23 Nov 2026 10:08:56 -0800 Subject: [PATCH 030/193] Select gradient mode buttons by their accessibility role --- crates/ui-egui/tests/gradient_stop_color_mode_menu.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs b/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs index 3bb31a263d..dd6a7b3df5 100644 --- a/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs +++ b/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs @@ -110,7 +110,9 @@ impl Scene { self.buttons.clear(); let update = output.platform_output.accesskit_update.as_ref().expect("AccessKit enabled"); for (_, node) in &update.nodes { - if let Some((label, bounds)) = node.label().zip(node.bounds()) { + if node.role() == egui::accesskit::Role::Button + && let Some((label, bounds)) = node.label().zip(node.bounds()) + { self.buttons .push((label.to_owned(), Rect::from_min_max(pos2(bounds.x0 as f32, bounds.y0 as f32), pos2(bounds.x1 as f32, bounds.y1 as f32)))); } From c08a99e0d01060eb5f2a0f85771fcb500850790d Mon Sep 17 00:00:00 2001 From: Carlo1911 <17356993+Carlo1911@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:44:14 -0500 Subject: [PATCH 031/193] AI import: a compound path with the gradient on its last path stays one compound path (#9239) Illustrator writes a gradient instance around only the last path of a compound path; the paths before it keep the default fill. paints_apart read that as a drawn look whose paths paint apart, so a sunburst's rays became black paths plus one gradient path. Several alike paths followed by one painted with a gradient or pattern are now the subpaths of one compound path, which takes the last path's paint. Co-Authored-By: Claude Sonnet 5.5 --- crates/eps/src/import/ai/read/ops.rs | 11 +++++++++++ crates/eps/src/import/ai/tests.rs | 16 ++++++++++++++++ 2 files changed, 27 insertions(+) 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. From 8f6c8236e1b34c559f8758ab7acd71144def37de Mon Sep 17 00:00:00 2001 From: Carlo1911 <17356993+Carlo1911@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:39:39 -0500 Subject: [PATCH 032/193] =?UTF-8?q?Missing=20Fonts:=20Find=20in=20Folder?= =?UTF-8?q?=E2=80=A6=20asks=20for=20the=20folder=20through=20the=20app=20(?= =?UTF-8?q?#9299)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The dialog filed the folder pick from inside its own frame and waited there for the answer. It now closes and asks through the app, as Type > Find Font's Find in Folder… does, and comes back searching the folder. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/dialogs/missing_fonts.rs | 48 +++++-------------- .../src/dialogs/missing_fonts/tests.rs | 26 ++++++++++ 2 files changed, 38 insertions(+), 36 deletions(-) diff --git a/crates/ui-egui/src/dialogs/missing_fonts.rs b/crates/ui-egui/src/dialogs/missing_fonts.rs index 75c72b0cef..5b5086f126 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_command(app, 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); diff --git a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs index 36dc534870..0ed05a5fe8 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs @@ -195,6 +195,32 @@ 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}"); +} + /// 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] From 68c51bf839c3d7359dbd8e9a5a8e1f4f29729c21 Mon Sep 17 00:00:00 2001 From: Carlo1911 Date: Wed, 25 Nov 2026 12:57:27 -0500 Subject: [PATCH 033/193] =?UTF-8?q?Missing=20Fonts:=20Find=20in=20Folder?= =?UTF-8?q?=E2=80=A6=20searches=20for=20the=20fonts=20of=20the=20dialog's?= =?UTF-8?q?=20document=20(#9299)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A dialog left open for one document while another is active asked for the folder, and searched, for the active document. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/dialogs/missing_fonts.rs | 8 +++++- .../src/dialogs/missing_fonts/tests.rs | 27 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/missing_fonts.rs b/crates/ui-egui/src/dialogs/missing_fonts.rs index 5b5086f126..96a32785e3 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts.rs @@ -374,7 +374,7 @@ fn settle(app: &mut VectorcraftApp, Answer { act, mut state }: Answer) { 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_command(app, None).map(|_| false), + 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); @@ -473,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 0ed05a5fe8..dad177950a 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs @@ -221,6 +221,33 @@ fn find_in_folder_asks_for_the_folder_and_the_dialog_comes_back_searching_it() { 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] From d0dc0c41b1e65666e6085f5501d3011e7dccb089 Mon Sep 17 00:00:00 2001 From: jmverges Date: Thu, 26 Nov 2026 04:07:56 +0000 Subject: [PATCH 034/193] .ai import: made point type is matched with the page's type where it draws Type made from a file's text document has no layout when the import matches it with the page's type, so the box it was matched by was the estimate of type without a layout: as wide as an average font would set it, running right from its anchor. Right-aligned point type draws on the other side of its anchor, centered type lies half outside that box, and vertical type runs down the page across it. Where the text document makes the type of every text object that shows (`made_only`), the page's type there was then nobody's: the import noted "some of the page's type has no text object in the layers, so it is left out" for type that is in the layers, and the made type, not seen on the page, was weighed against the page as type the page may not draw, and sometimes taken out. `made_only` (`crates/eps/src/import/native/plan.rs`) now takes the box of made point type that shows from its layout (`drawn_box`), in the fonts the import has, as the document measures it once it is open. The node itself keeps no layout, so the document's type is measured when it opens, as before. Area type and type on a path are matched by their frame and path, as before. Where some text object's type isn't made (`plan`), the box stays the estimate: there the page's pieces in the box where made type draws can belong to text objects stacked on it whose type isn't made, and the made type would take them all. Co-Authored-By: Claude Opus 5.5 --- crates/eps/src/import/native/plan.rs | 75 ++++++++++++++++++++++++--- crates/eps/src/import/tests_native.rs | 20 +++++++ 2 files changed, 88 insertions(+), 7 deletions(-) diff --git a/crates/eps/src/import/native/plan.rs b/crates/eps/src/import/native/plan.rs index 17107dded9..309202c490 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -145,7 +145,8 @@ pub(super) fn made_only( warn: &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,21 +316,44 @@ 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, }) .collect() } +/// Where made type draws: its visual box, point type laid out first. Made type has no layout yet, +/// and without one 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. +/// The node keeps no layout: the document's type is measured when it opens. [`made_only`] matches +/// by this box; [`plan`] doesn't yet. +fn drawn_box(node: &Node) -> Option { + if let NodeKind::Text(t) = &node.kind + && matches!(t.kind, 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() +} + /// Mark the made type that has at least half of a piece of the page's type where it draws (or round /// it, as far as strokes round type reach) as type the page draws. How many of the page's text /// objects no made type takes, shown or not: none that holds a piece of the object has its words @@ -391,8 +415,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]| { @@ -547,3 +574,37 @@ fn fill_hidden(infos: &[SlotInfo], stories: &[Option>], content: &mut } } } + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_doc::{CharStyle, Justify, TextObject}; + + /// Made point type is matched with the page's type where it draws: 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() { + let anchor = 300.0; + let made = |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; + Node::new(NodeId(1), NodeKind::Text(Box::new(t))) + }; + let boxed = |justify, vertical| { + let node = made(justify, vertical); + 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:?}"); + } +} diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index f809141202..4540f0940a 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -5509,6 +5509,26 @@ 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); + } +} + /// 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. From 62af02a78c2cb386938cd8785e6dfafb039942d1 Mon Sep 17 00:00:00 2001 From: jmverges Date: Thu, 26 Nov 2026 13:58:33 +0000 Subject: [PATCH 035/193] docs: file-format parity row for made point type matched where it draws Co-Authored-By: Claude Opus 5.5 --- docs/file-format-parity.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 2af1064315..02cf4c0ccd 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -422,6 +422,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-26 | minor | `.ai` and EPS import: where the text document makes the type of every text object that shows, point type made from it is matched with the page's type where it draws. Made type has no layout when it is matched, and its box was the estimate of type without one (0.55 em a character, running right from its anchor): beside right-aligned type, over half of centered type, across vertical type, and too short for a wide font. The page's type there was counted as type with no text object, with the note "some of the page's type has no text object in the layers, so it is left out" (a loss, so `convert` wouldn't write over the file), and the made type went on to be weighed against the page as type the page may not draw, and could be taken out. The box of made point type that shows now comes from its layout in the fonts the import has; the text object keeps no layout, so the document measures it when it opens, as before. Files where some text object's type isn't made keep the estimate: there the page's pieces where made type draws can belong to text objects stacked on it. Tests `right_aligned_and_centered_point_type_takes_the_pages_type_where_it_draws` in `crates/eps/src/import/tests_native.rs` and `made_point_type_s_box_is_where_its_alignment_and_orientation_draw_it` in `crates/eps/src/import/native/plan.rs`. Scores and estimates unchanged. | | 2026-11-22 | minor | EPS import: type in a Type 1 or Type 42 font the file carries, whose family isn't available, is drawn in a TrueType font built from the glyphs the file shows (outlines and advances from the font program), kept with the document as PDF import keeps a PDF's (#4569), and spaced by those glyphs' own advances; once its text is edited it takes the fallback font. A string that draws a character with another glyph than the one kept for it comes in as outlines. The warning names those families with PDF import's words ("show as the file draws them, in the fonts it carries, until their text is edited"). Fonts the file only names, Type 3 fonts and type from an Illustrator editing copy are unchanged. Tests `embedded_type1_type_draws_with_the_files_glyphs`, `a_second_glyph_for_a_character_keeps_its_type_as_outlines`, `kept_type1_glyphs_survive_saving_and_go_when_the_text_is_edited`, `type_in_fonts_that_arent_available_is_named_in_a_warning` in `crates/eps/src/import/tests_type1.rs`, `type_in_a_carried_type42_font_draws_with_the_files_glyphs` in `crates/eps/src/import/tests_type42.rs`; scores unchanged | | 2026-11-19 | minor | `.ai` import: a stroke's arrowheads were left out, so lines came in without their heads (#8188). A Stroke Style filter's stroke dictionary names each end's head as a symbol of the file (`/GObjRef : (name) /SymbolArt ; (BSArrowBeginSymbol)` or `(BSArrowEndSymbol)`), with its scale in percent (`BSArrowEndScale`, and `BSArrowBeginScale` read the same way; 100 without one). As the files have it, such a symbol's art (y down, as symbols are read) points right along a straight, level sample of the line: an open stroked path with no fill, which ends where the line stops under the head. The rest of the art that paints is the head, its tip its rightmost point, at one symbol unit a head weight (the stroke's weight at the scale). The head comes in as a custom arrowhead with that outline and that stop (a custom head now carries an optional stop, else its line ends halfway along it, as before). Its placement is the one of the two (tip on the end of the path, or Extend, the tip past it by the line's length under the head) that gives the object its drawn art's bounds; the user's file has every tip on its path's end. A stroke keeps its drawn look when neither placement gives those bounds (heads on other subpaths, say) or both do while a head moves 0.2 pt or more between them (a line whose end lies inside the bounds of its other segments), when its symbol isn't read whole or isn't read as a head (no sample or more than one, a sample that isn't 1 pt wide, as in art stored at a Large Canvas scale, art other than paths, compound paths and groups such as a clip group, a group with fills or strokes of its own, effects, brushes, partial opacity or an opacity mask), when its dictionary holds another `BSArrow` entry beside heads, when a scale is outside 1–1000 %, or when the head's weight would be under the 0.25 pt least one VectorCraft draws; a graphic style with such a stroke isn't read rather than read without its heads, and one with heads takes them on the end of the path, so an object whose heads are read past its ends isn't linked to its listed style. Measured on a user's file of ten arrows (used locally, never committed): every line gets its heads, and drawn at 4× its pixels match the file's own page but for 3 of 9,825 inked ones (0.24.1: 1,232 differ). Tests `a_strokes_arrowhead_symbols_are_its_arrowheads`, `a_strokes_start_arrowhead_points_back_and_keeps_its_side`, `a_stroke_takes_both_heads_at_their_own_scales`, `heads_drawn_past_the_path_extend_it`, `arrowheads_this_does_not_read_keep_the_drawn_look`, `an_arrowhead_entry_without_heads_leaves_the_stroke_read` in `crates/eps/src/import/ai/tests.rs`, `heads_whose_placement_the_drawn_bounds_leave_open_keep_the_drawn_look`, `a_head_that_stays_put_leaves_a_moving_heads_placement_open`, `a_style_library_reads_the_heads_of_symbols_defined_after_its_styles` in it, `a_symbol_entry_cut_short_leaves_the_next_style_read` and `a_comment_inside_a_symbol_entry_is_skipped` in `crates/eps/src/import/ai/style/tests.rs`, `partly_transparent_or_masked_art_makes_no_head` in `crates/eps/src/import/ai/arrowhead.rs`, fuzzed by `ai_arrowhead_strokes_never_panic`; scores unchanged | | 2026-11-19 | minor | PDF import (#8549 follow-up): type filled and stroked after a page of type filled only came in as a filled object and a stroked one: since #8549 lines filled only are kept for a stroke pass too, and the glyphs of the lines finished past the 64 kept were remembered until the next stroke, so `2 Tr (Title) Tj` after more than 64 lines of type filled only took its first stroke for the start of a stroke pass over them, always once more than 4,096 glyphs had been finished so. Those glyphs are now forgotten when anything else is drawn (a path, an image, a Type 3 glyph's art, a change of blend mode or soft mask: nothing is drawn between an operator's fill pass and its stroke pass), and past the first 4,096 glyphs none are remembered instead of every stroke matching. A `TJ` over more lines than are kept still comes in as a filled object and a stroked one for each part, also when it ends where it began, and when a glyph kept as an outline comes before that (the line it starts keeps the glyphs of the lines finished). Remaining: with nothing drawn between them, type filled and stroked at exactly the place, font, size and text of a glyph filled only on a line finished so still comes in as a filled object and a stroked one, as the device can't tell its stroke pass from the start of one over that glyph. Tests: `type_filled_and_stroked_after_a_dense_page_of_filled_type_is_filled_and_stroked`, `type_filled_and_stroked_over_a_finished_glyph_after_a_path_is_filled_and_stroked`, `an_outline_glyph_in_a_tj_over_more_lines_than_are_kept_leaves_fill_and_stroke_apart`; scores and estimates unchanged. | From 57bb305f83f280a46c6b1b0cea07512e333fa0c7 Mon Sep 17 00:00:00 2001 From: jmverges Date: Thu, 26 Nov 2026 19:51:10 +0000 Subject: [PATCH 036/193] .ai import: made point type that differs from the page counts as type where it draws The page comparison tells type that differs from art that differs by where the layers' text objects are (`type_areas` and `all_type_areas` in `crates/eps/src/import/native/compare.rs`). Type made from the file's text document has no layout then, so its box was the estimate of type without one, running right from its anchor: right-aligned type draws on the other side of it, centered type half outside it, vertical type across it. What differed there (type laid out again, or in another font) was counted as art, which is held to a stricter limit: the layers could be refused and the file sent to its PDF part or page, or the note said the art differs where the type does. The type areas now come from where the type draws: `drawn_box`, the box the first commit matches by, moved to `slots.rs` so both use it. The page's own type keeps its measured box, as before. `prune_unseen` and the boxes of made type that doesn't show still use the estimate. Co-Authored-By: Claude Opus 5.5 --- crates/eps/src/import/native/compare.rs | 12 ++--- crates/eps/src/import/native/plan.rs | 58 +------------------------ crates/eps/src/import/native/slots.rs | 49 +++++++++++++++++++++ crates/eps/src/import/tests_native.rs | 15 +++++++ 4 files changed, 73 insertions(+), 61 deletions(-) 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>, laid: bool) -> Vec< .collect() } -/// Where made type draws: its visual box, point type laid out first. Made type has no layout yet, -/// and without one 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. -/// The node keeps no layout: the document's type is measured when it opens. [`made_only`] matches -/// by this box; [`plan`] doesn't yet. -fn drawn_box(node: &Node) -> Option { - if let NodeKind::Text(t) = &node.kind - && matches!(t.kind, 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() -} - /// Mark the made type that has at least half of a piece of the page's type where it draws (or round /// it, as far as strokes round type reach) as type the page draws. How many of the page's text /// objects no made type takes, shown or not: none that holds a piece of the object has its words @@ -574,37 +554,3 @@ fn fill_hidden(infos: &[SlotInfo], stories: &[Option>], content: &mut } } } - -#[cfg(test)] -mod tests { - use super::*; - use vectorcraft_doc::{CharStyle, Justify, TextObject}; - - /// Made point type is matched with the page's type where it draws: 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() { - let anchor = 300.0; - let made = |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; - Node::new(NodeId(1), NodeKind::Text(Box::new(t))) - }; - let boxed = |justify, vertical| { - let node = made(justify, vertical); - 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:?}"); - } -} diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index ebd6deef88..1056701d1e 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -610,10 +610,59 @@ pub(super) fn extent(parts: &[Arc]) -> Option { parts.iter().filter_map(|n| n.visual_bounds()).reduce(|a, b| a.union(b)) } +/// Where type made from the file's text document draws: its visual box, point type laid out +/// first. Made type has no layout during the import, and without one 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. 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, and the page comparison counts what differs +/// in it as type; `plan` doesn't match by it yet. +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 4540f0940a..4bb8e8f837 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -5529,6 +5529,21 @@ fn right_aligned_and_centered_point_type_takes_the_pages_type_where_it_draws() { } } +/// 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. From 58e99f5fb3fd5bfc0708899ad3f16e8fb31e9f6c Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 12:24:42 -0800 Subject: [PATCH 037/193] Format the native gradient stop interaction cases --- .../tests/gradient_stop_color_mode_menu.rs | 49 +++++++++++++------ 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs b/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs index 5e667c70cf..478d02b58b 100644 --- a/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs +++ b/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs @@ -108,7 +108,8 @@ impl Scene { self.app.ui(ui); }); let _ = self.app.frame_input(take_output(&self.ctx)); - self.nodes = output.platform_output.accesskit_update.as_ref().expect("AccessKit enabled").nodes.iter().map(|(_, node)| node.clone()).collect(); + self.nodes = + output.platform_output.accesskit_update.as_ref().expect("AccessKit enabled").nodes.iter().map(|(_, node)| node.clone()).collect(); output.textures_delta.clear(); } @@ -141,8 +142,11 @@ impl Scene { } fn popover(&self) -> Rect { - self.nodes.iter().find(|n| n.role() == Role::Dialog && n.label() == Some("Gradient stop")) - .and_then(Self::node_rect).expect("the actual native stop popover") + self.nodes + .iter() + .find(|n| n.role() == Role::Dialog && n.label() == Some("Gradient stop")) + .and_then(Self::node_rect) + .expect("the actual native stop popover") } fn editor_open(&self) -> bool { @@ -154,8 +158,7 @@ impl Scene { } fn child_open(&self) -> bool { - overlay::top(&self.ctx).and_then(|id| overlay::entry(&self.ctx, id)) - .is_some_and(|entry| !entry.exiting && entry.keys == OwnerClass::Menu) + overlay::top(&self.ctx).and_then(|id| overlay::entry(&self.ctx, id)).is_some_and(|entry| !entry.exiting && entry.keys == OwnerClass::Menu) } fn open_stop(&mut self) { @@ -175,8 +178,13 @@ impl Scene { fn button(&self, label: &str) -> Rect { let popover = self.popover(); - let matches: Vec<_> = self.nodes.iter().filter(|node| node.role() == Role::Button && node.label() == Some(label)) - .filter_map(Self::node_rect).filter(|rect| rect.is_positive() && popover.contains(rect.center())).collect(); + let matches: Vec<_> = self + .nodes + .iter() + .filter(|node| node.role() == Role::Button && node.label() == Some(label)) + .filter_map(Self::node_rect) + .filter(|rect| rect.is_positive() && popover.contains(rect.center())) + .collect(); assert_eq!(matches.len(), 1, "one actual native mode chooser {label:?}"); matches[0] } @@ -192,13 +200,17 @@ impl Scene { } fn mode_rows(&self) -> Vec<(String, bool, Rect)> { - let mut rows: Vec<_> = self.nodes.iter().filter_map(|node| { - let label = node.label()?; - if !matches!(node.role(), Role::MenuItem | Role::MenuItemRadio | Role::MenuItemCheckBox) || !MODES.contains(&label) { - return None; - } - Some((label.to_owned(), node.toggled() == Some(Toggled::True), Self::node_rect(node)?)) - }).collect(); + let mut rows: Vec<_> = self + .nodes + .iter() + .filter_map(|node| { + let label = node.label()?; + if !matches!(node.role(), Role::MenuItem | Role::MenuItemRadio | Role::MenuItemCheckBox) || !MODES.contains(&label) { + return None; + } + Some((label.to_owned(), node.toggled() == Some(Toggled::True), Self::node_rect(node)?)) + }) + .collect(); rows.sort_by(|a, b| a.2.top().total_cmp(&b.2.top())); rows } @@ -242,8 +254,13 @@ impl Scene { fn spectrum(&self) -> Rect { let popover = self.popover(); - let found: Vec<_> = self.nodes.iter().filter(|node| node.role() == Role::Group && node.label() == Some("Color Ramp")) - .filter_map(Self::node_rect).filter(|rect| popover.contains(rect.center())).collect(); + let found: Vec<_> = self + .nodes + .iter() + .filter(|node| node.role() == Role::Group && node.label() == Some("Color Ramp")) + .filter_map(Self::node_rect) + .filter(|rect| popover.contains(rect.center())) + .collect(); assert_eq!(found.len(), 1, "the actual native Color panel spectrum"); found[0] } From e19bb786f55b3f7d7aa8b8cced7f5aafe24a9c96 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 12:39:18 -0800 Subject: [PATCH 038/193] Use the current native menu trigger import --- crates/ui-egui/src/dialogs/gradient_stop.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 37b70f2907..0c82b2af34 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -21,11 +21,11 @@ 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, PopupKind, 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, Trigger}; +use craft::ui::menu::{Menu, MenuItem}; use craft::ui::notices::Notice; use craft::ui::popover::Popover; use craft::ui::runtime::env::{Env, Label, UnitKind}; From cc13866e998f5aabb5aef1dacb4917c734ed4185 Mon Sep 17 00:00:00 2001 From: jmverges Date: Thu, 26 Nov 2026 21:07:18 +0000 Subject: [PATCH 039/193] docs: the parity row covers the page comparison's type areas Co-Authored-By: Claude Opus 5.5 --- docs/file-format-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 02cf4c0ccd..f712b979b0 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -422,7 +422,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| -| 2026-11-26 | minor | `.ai` and EPS import: where the text document makes the type of every text object that shows, point type made from it is matched with the page's type where it draws. Made type has no layout when it is matched, and its box was the estimate of type without one (0.55 em a character, running right from its anchor): beside right-aligned type, over half of centered type, across vertical type, and too short for a wide font. The page's type there was counted as type with no text object, with the note "some of the page's type has no text object in the layers, so it is left out" (a loss, so `convert` wouldn't write over the file), and the made type went on to be weighed against the page as type the page may not draw, and could be taken out. The box of made point type that shows now comes from its layout in the fonts the import has; the text object keeps no layout, so the document measures it when it opens, as before. Files where some text object's type isn't made keep the estimate: there the page's pieces where made type draws can belong to text objects stacked on it. Tests `right_aligned_and_centered_point_type_takes_the_pages_type_where_it_draws` in `crates/eps/src/import/tests_native.rs` and `made_point_type_s_box_is_where_its_alignment_and_orientation_draw_it` in `crates/eps/src/import/native/plan.rs`. Scores and estimates unchanged. | +| 2026-11-26 | minor | `.ai` and EPS import: where the text document makes the type of every text object that shows, point type made from it is matched with the page's type where it draws. Made type has no layout when it is matched, and its box was the estimate of type without one (0.55 em a character, running right from its anchor): beside right-aligned type, over half of centered type, across vertical type, and too short for a wide font. The page's type there was counted as type with no text object, with the note "some of the page's type has no text object in the layers, so it is left out" (a loss, so `convert` wouldn't write over the file), and the made type went on to be weighed against the page as type the page may not draw, and could be taken out. The box of made point type that shows now comes from its layout in the fonts the import has; the text object keeps no layout, so the document measures it when it opens, as before. Files where some text object's type isn't made keep the estimate: there the page's pieces where made type draws can belong to text objects stacked on it. The page comparison takes the same box for the layers' type areas (`type_areas` in `compare.rs`): made point type that differs from the page (laid out again, or in another font) counts as type where it draws, whatever its alignment. Counted as art beside the estimate, it could send the file to its PDF part or page, or be noted as art that differs. Tests `right_aligned_and_centered_point_type_takes_the_pages_type_where_it_draws` and `right_aligned_point_type_that_differs_from_the_page_differs_as_type` in `crates/eps/src/import/tests_native.rs`, and `made_point_type_s_box_is_where_its_alignment_and_orientation_draw_it` in `crates/eps/src/import/native/slots.rs`. Scores and estimates unchanged. | | 2026-11-22 | minor | EPS import: type in a Type 1 or Type 42 font the file carries, whose family isn't available, is drawn in a TrueType font built from the glyphs the file shows (outlines and advances from the font program), kept with the document as PDF import keeps a PDF's (#4569), and spaced by those glyphs' own advances; once its text is edited it takes the fallback font. A string that draws a character with another glyph than the one kept for it comes in as outlines. The warning names those families with PDF import's words ("show as the file draws them, in the fonts it carries, until their text is edited"). Fonts the file only names, Type 3 fonts and type from an Illustrator editing copy are unchanged. Tests `embedded_type1_type_draws_with_the_files_glyphs`, `a_second_glyph_for_a_character_keeps_its_type_as_outlines`, `kept_type1_glyphs_survive_saving_and_go_when_the_text_is_edited`, `type_in_fonts_that_arent_available_is_named_in_a_warning` in `crates/eps/src/import/tests_type1.rs`, `type_in_a_carried_type42_font_draws_with_the_files_glyphs` in `crates/eps/src/import/tests_type42.rs`; scores unchanged | | 2026-11-19 | minor | `.ai` import: a stroke's arrowheads were left out, so lines came in without their heads (#8188). A Stroke Style filter's stroke dictionary names each end's head as a symbol of the file (`/GObjRef : (name) /SymbolArt ; (BSArrowBeginSymbol)` or `(BSArrowEndSymbol)`), with its scale in percent (`BSArrowEndScale`, and `BSArrowBeginScale` read the same way; 100 without one). As the files have it, such a symbol's art (y down, as symbols are read) points right along a straight, level sample of the line: an open stroked path with no fill, which ends where the line stops under the head. The rest of the art that paints is the head, its tip its rightmost point, at one symbol unit a head weight (the stroke's weight at the scale). The head comes in as a custom arrowhead with that outline and that stop (a custom head now carries an optional stop, else its line ends halfway along it, as before). Its placement is the one of the two (tip on the end of the path, or Extend, the tip past it by the line's length under the head) that gives the object its drawn art's bounds; the user's file has every tip on its path's end. A stroke keeps its drawn look when neither placement gives those bounds (heads on other subpaths, say) or both do while a head moves 0.2 pt or more between them (a line whose end lies inside the bounds of its other segments), when its symbol isn't read whole or isn't read as a head (no sample or more than one, a sample that isn't 1 pt wide, as in art stored at a Large Canvas scale, art other than paths, compound paths and groups such as a clip group, a group with fills or strokes of its own, effects, brushes, partial opacity or an opacity mask), when its dictionary holds another `BSArrow` entry beside heads, when a scale is outside 1–1000 %, or when the head's weight would be under the 0.25 pt least one VectorCraft draws; a graphic style with such a stroke isn't read rather than read without its heads, and one with heads takes them on the end of the path, so an object whose heads are read past its ends isn't linked to its listed style. Measured on a user's file of ten arrows (used locally, never committed): every line gets its heads, and drawn at 4× its pixels match the file's own page but for 3 of 9,825 inked ones (0.24.1: 1,232 differ). Tests `a_strokes_arrowhead_symbols_are_its_arrowheads`, `a_strokes_start_arrowhead_points_back_and_keeps_its_side`, `a_stroke_takes_both_heads_at_their_own_scales`, `heads_drawn_past_the_path_extend_it`, `arrowheads_this_does_not_read_keep_the_drawn_look`, `an_arrowhead_entry_without_heads_leaves_the_stroke_read` in `crates/eps/src/import/ai/tests.rs`, `heads_whose_placement_the_drawn_bounds_leave_open_keep_the_drawn_look`, `a_head_that_stays_put_leaves_a_moving_heads_placement_open`, `a_style_library_reads_the_heads_of_symbols_defined_after_its_styles` in it, `a_symbol_entry_cut_short_leaves_the_next_style_read` and `a_comment_inside_a_symbol_entry_is_skipped` in `crates/eps/src/import/ai/style/tests.rs`, `partly_transparent_or_masked_art_makes_no_head` in `crates/eps/src/import/ai/arrowhead.rs`, fuzzed by `ai_arrowhead_strokes_never_panic`; scores unchanged | | 2026-11-19 | minor | PDF import (#8549 follow-up): type filled and stroked after a page of type filled only came in as a filled object and a stroked one: since #8549 lines filled only are kept for a stroke pass too, and the glyphs of the lines finished past the 64 kept were remembered until the next stroke, so `2 Tr (Title) Tj` after more than 64 lines of type filled only took its first stroke for the start of a stroke pass over them, always once more than 4,096 glyphs had been finished so. Those glyphs are now forgotten when anything else is drawn (a path, an image, a Type 3 glyph's art, a change of blend mode or soft mask: nothing is drawn between an operator's fill pass and its stroke pass), and past the first 4,096 glyphs none are remembered instead of every stroke matching. A `TJ` over more lines than are kept still comes in as a filled object and a stroked one for each part, also when it ends where it began, and when a glyph kept as an outline comes before that (the line it starts keeps the glyphs of the lines finished). Remaining: with nothing drawn between them, type filled and stroked at exactly the place, font, size and text of a glyph filled only on a line finished so still comes in as a filled object and a stroked one, as the device can't tell its stroke pass from the start of one over that glyph. Tests: `type_filled_and_stroked_after_a_dense_page_of_filled_type_is_filled_and_stroked`, `type_filled_and_stroked_over_a_finished_glyph_after_a_path_is_filled_and_stroked`, `an_outline_glyph_in_a_tj_over_more_lines_than_are_kept_leaves_fill_and_stroke_apart`; scores and estimates unchanged. | From f2c9e05294c0ca2ea4b796385e4d91083efbf4ff Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 13:28:13 -0800 Subject: [PATCH 040/193] Close the gradient editor with an outside-dismissed mode menu --- crates/ui-egui/src/dialogs/gradient_stop.rs | 15 +++++++++++---- .../tests/gradient_stop_color_mode_menu.rs | 3 ++- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 0c82b2af34..407d44b8c5 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -218,6 +218,9 @@ impl StackDialog for GradientStopPopover { .at_point(*at) .close_on_enter(true) .show(ui, |ui, _| body(ui, feed, tab, panel, filed)); + if shown.inner == Some(true) { + return Some(DialogResult::Cancel); + } match shown.output.closed { Some(CloseReason::Enter) => Some(DialogResult::Ok(set.clone())), Some(_) => Some(DialogResult::Cancel), @@ -268,7 +271,8 @@ impl StackDialog for GradientStopPopover { /// The popover's body: the tabs and the eyedropper, the Color panel or the swatches, then opacity and location (a /// point: spread). What the user edits is filed in `filed`. -fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, filed: &mut Filed) { +fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, filed: &mut Filed) -> bool { + let mut outside = false; Stack::new().show(ui, |ui, _| { Row::new().show(ui, |ui, _| { let tabs = [ @@ -282,7 +286,7 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi filed.eyedropper |= DropperButton::new(tip, Bind::given(false)).show(ui).edit.value() == Some(&true); } if *tab == Tab::Color { - mode_menu(ui, &feed.shown, panel.mode); + outside |= mode_menu(ui, &feed.shown, panel.mode); } }); match *tab { @@ -307,11 +311,12 @@ 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. -fn mode_menu(ui: &mut Ui, shown: &ColorPanelShown, fallback: ColorPanelMode) { +fn mode_menu(ui: &mut Ui, shown: &ColorPanelShown, fallback: ColorPanelMode) -> bool { let words = Env::of(ui).words::(); let label = match shown { ColorPanelShown::Mode(mode) => mode.label(&words), @@ -319,11 +324,13 @@ fn mode_menu(ui: &mut Ui, shown: &ColorPanelShown, fallback: ColorPanelMode) { _ => fallback.label(&words), }; let button = Button::new(label).popup(PopupKind::Menu).show(ui); - Menu::new(tl!("Color mode")).opened_by(&button, Trigger::Click).show(ui, |ui, _| { + let menu = Menu::new(tl!("Color mode")).opened_by(&button, Trigger::Click).show(ui, |ui, _| { for mode in ColorPanelMode::FILL_STROKE { MenuItem::command(mode.command()).show(ui); } }); + // The child absorbs an outside press before its parent sees it. Close both for that event only. + menu.output.closed == Some(CloseReason::Outside) } /// Document swatches as tiles: a pick gives the stop (or point) that colour. diff --git a/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs b/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs index 478d02b58b..d1e5a9f2eb 100644 --- a/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs +++ b/crates/ui-egui/tests/gradient_stop_color_mode_menu.rs @@ -257,7 +257,8 @@ impl Scene { let found: Vec<_> = self .nodes .iter() - .filter(|node| node.role() == Role::Group && node.label() == Some("Color Ramp")) + // The component and its interactive bar share a name; only the bar carries the mode value. + .filter(|node| node.role() == Role::Group && node.label() == Some("Color Ramp") && node.value() == Some("RGB Sliders")) .filter_map(Self::node_rect) .filter(|rect| popover.contains(rect.center())) .collect(); From 870c640fcbc964369e54f1a8a9bc498a80c6ebfe Mon Sep 17 00:00:00 2001 From: jmverges Date: Thu, 26 Nov 2026 21:48:17 +0000 Subject: [PATCH 041/193] import tests: centered point type at a heading's size is matched where it draws A centered line of 72 point type on a tight leading, as garment headings are set: with the estimate box the page's type has no text object and the import notes a loss; with the laid-out box it is the text object's. The 14 point centered case passes either way, as the 6 points round the estimate cover half of so short a line. `drawn_box`'s comment says what it lays out (any point type without a layout, in the installed fonts) and where it is used. Co-Authored-By: Claude Opus 5.5 --- crates/eps/src/import/native/slots.rs | 21 +++++++++++++-------- crates/eps/src/import/tests_native.rs | 25 +++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index 1056701d1e..5be707fac7 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -610,14 +610,19 @@ pub(super) fn extent(parts: &[Arc]) -> Option { parts.iter().filter_map(|n| n.visual_bounds()).reduce(|a, b| a.union(b)) } -/// Where type made from the file's text document draws: its visual box, point type laid out -/// first. Made type has no layout during the import, and without one 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. 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, and the page comparison counts what differs -/// in it as type; `plan` doesn't match by it yet. +/// 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) diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 4bb8e8f837..262ed32c94 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -5529,6 +5529,31 @@ fn right_aligned_and_centered_point_type_takes_the_pages_type_where_it_draws() { } } +/// 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.) From 8c17fed1f86d3bedbe3232a194001cf1b6ccdb64 Mon Sep 17 00:00:00 2001 From: jmverges Date: Thu, 26 Nov 2026 21:52:37 +0000 Subject: [PATCH 042/193] docs: the parity row names the centered heading test Co-Authored-By: Claude Opus 5.5 --- docs/file-format-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index f712b979b0..0ed84c3f24 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -422,7 +422,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| -| 2026-11-26 | minor | `.ai` and EPS import: where the text document makes the type of every text object that shows, point type made from it is matched with the page's type where it draws. Made type has no layout when it is matched, and its box was the estimate of type without one (0.55 em a character, running right from its anchor): beside right-aligned type, over half of centered type, across vertical type, and too short for a wide font. The page's type there was counted as type with no text object, with the note "some of the page's type has no text object in the layers, so it is left out" (a loss, so `convert` wouldn't write over the file), and the made type went on to be weighed against the page as type the page may not draw, and could be taken out. The box of made point type that shows now comes from its layout in the fonts the import has; the text object keeps no layout, so the document measures it when it opens, as before. Files where some text object's type isn't made keep the estimate: there the page's pieces where made type draws can belong to text objects stacked on it. The page comparison takes the same box for the layers' type areas (`type_areas` in `compare.rs`): made point type that differs from the page (laid out again, or in another font) counts as type where it draws, whatever its alignment. Counted as art beside the estimate, it could send the file to its PDF part or page, or be noted as art that differs. Tests `right_aligned_and_centered_point_type_takes_the_pages_type_where_it_draws` and `right_aligned_point_type_that_differs_from_the_page_differs_as_type` in `crates/eps/src/import/tests_native.rs`, and `made_point_type_s_box_is_where_its_alignment_and_orientation_draw_it` in `crates/eps/src/import/native/slots.rs`. Scores and estimates unchanged. | +| 2026-11-26 | minor | `.ai` and EPS import: where the text document makes the type of every text object that shows, point type made from it is matched with the page's type where it draws. Made type has no layout when it is matched, and its box was the estimate of type without one (0.55 em a character, running right from its anchor): beside right-aligned type, over half of centered type, across vertical type, and too short for a wide font. The page's type there was counted as type with no text object, with the note "some of the page's type has no text object in the layers, so it is left out" (a loss, so `convert` wouldn't write over the file), and the made type went on to be weighed against the page as type the page may not draw, and could be taken out. The box of made point type that shows now comes from its layout in the fonts the import has; the text object keeps no layout, so the document measures it when it opens, as before. Files where some text object's type isn't made keep the estimate: there the page's pieces where made type draws can belong to text objects stacked on it. The page comparison takes the same box for the layers' type areas (`type_areas` in `compare.rs`): made point type that differs from the page (laid out again, or in another font) counts as type where it draws, whatever its alignment. Counted as art beside the estimate, it could send the file to its PDF part or page, or be noted as art that differs. A file whose layers failed the comparison that way and opened without it now passes it and shows its notes. Tests `right_aligned_and_centered_point_type_takes_the_pages_type_where_it_draws`, `centered_point_type_at_a_heading_s_size_takes_the_pages_type_where_it_draws` and `right_aligned_point_type_that_differs_from_the_page_differs_as_type` in `crates/eps/src/import/tests_native.rs`, and `made_point_type_s_box_is_where_its_alignment_and_orientation_draw_it` in `crates/eps/src/import/native/slots.rs`. Scores and estimates unchanged. | | 2026-11-22 | minor | EPS import: type in a Type 1 or Type 42 font the file carries, whose family isn't available, is drawn in a TrueType font built from the glyphs the file shows (outlines and advances from the font program), kept with the document as PDF import keeps a PDF's (#4569), and spaced by those glyphs' own advances; once its text is edited it takes the fallback font. A string that draws a character with another glyph than the one kept for it comes in as outlines. The warning names those families with PDF import's words ("show as the file draws them, in the fonts it carries, until their text is edited"). Fonts the file only names, Type 3 fonts and type from an Illustrator editing copy are unchanged. Tests `embedded_type1_type_draws_with_the_files_glyphs`, `a_second_glyph_for_a_character_keeps_its_type_as_outlines`, `kept_type1_glyphs_survive_saving_and_go_when_the_text_is_edited`, `type_in_fonts_that_arent_available_is_named_in_a_warning` in `crates/eps/src/import/tests_type1.rs`, `type_in_a_carried_type42_font_draws_with_the_files_glyphs` in `crates/eps/src/import/tests_type42.rs`; scores unchanged | | 2026-11-19 | minor | `.ai` import: a stroke's arrowheads were left out, so lines came in without their heads (#8188). A Stroke Style filter's stroke dictionary names each end's head as a symbol of the file (`/GObjRef : (name) /SymbolArt ; (BSArrowBeginSymbol)` or `(BSArrowEndSymbol)`), with its scale in percent (`BSArrowEndScale`, and `BSArrowBeginScale` read the same way; 100 without one). As the files have it, such a symbol's art (y down, as symbols are read) points right along a straight, level sample of the line: an open stroked path with no fill, which ends where the line stops under the head. The rest of the art that paints is the head, its tip its rightmost point, at one symbol unit a head weight (the stroke's weight at the scale). The head comes in as a custom arrowhead with that outline and that stop (a custom head now carries an optional stop, else its line ends halfway along it, as before). Its placement is the one of the two (tip on the end of the path, or Extend, the tip past it by the line's length under the head) that gives the object its drawn art's bounds; the user's file has every tip on its path's end. A stroke keeps its drawn look when neither placement gives those bounds (heads on other subpaths, say) or both do while a head moves 0.2 pt or more between them (a line whose end lies inside the bounds of its other segments), when its symbol isn't read whole or isn't read as a head (no sample or more than one, a sample that isn't 1 pt wide, as in art stored at a Large Canvas scale, art other than paths, compound paths and groups such as a clip group, a group with fills or strokes of its own, effects, brushes, partial opacity or an opacity mask), when its dictionary holds another `BSArrow` entry beside heads, when a scale is outside 1–1000 %, or when the head's weight would be under the 0.25 pt least one VectorCraft draws; a graphic style with such a stroke isn't read rather than read without its heads, and one with heads takes them on the end of the path, so an object whose heads are read past its ends isn't linked to its listed style. Measured on a user's file of ten arrows (used locally, never committed): every line gets its heads, and drawn at 4× its pixels match the file's own page but for 3 of 9,825 inked ones (0.24.1: 1,232 differ). Tests `a_strokes_arrowhead_symbols_are_its_arrowheads`, `a_strokes_start_arrowhead_points_back_and_keeps_its_side`, `a_stroke_takes_both_heads_at_their_own_scales`, `heads_drawn_past_the_path_extend_it`, `arrowheads_this_does_not_read_keep_the_drawn_look`, `an_arrowhead_entry_without_heads_leaves_the_stroke_read` in `crates/eps/src/import/ai/tests.rs`, `heads_whose_placement_the_drawn_bounds_leave_open_keep_the_drawn_look`, `a_head_that_stays_put_leaves_a_moving_heads_placement_open`, `a_style_library_reads_the_heads_of_symbols_defined_after_its_styles` in it, `a_symbol_entry_cut_short_leaves_the_next_style_read` and `a_comment_inside_a_symbol_entry_is_skipped` in `crates/eps/src/import/ai/style/tests.rs`, `partly_transparent_or_masked_art_makes_no_head` in `crates/eps/src/import/ai/arrowhead.rs`, fuzzed by `ai_arrowhead_strokes_never_panic`; scores unchanged | | 2026-11-19 | minor | PDF import (#8549 follow-up): type filled and stroked after a page of type filled only came in as a filled object and a stroked one: since #8549 lines filled only are kept for a stroke pass too, and the glyphs of the lines finished past the 64 kept were remembered until the next stroke, so `2 Tr (Title) Tj` after more than 64 lines of type filled only took its first stroke for the start of a stroke pass over them, always once more than 4,096 glyphs had been finished so. Those glyphs are now forgotten when anything else is drawn (a path, an image, a Type 3 glyph's art, a change of blend mode or soft mask: nothing is drawn between an operator's fill pass and its stroke pass), and past the first 4,096 glyphs none are remembered instead of every stroke matching. A `TJ` over more lines than are kept still comes in as a filled object and a stroked one for each part, also when it ends where it began, and when a glyph kept as an outline comes before that (the line it starts keeps the glyphs of the lines finished). Remaining: with nothing drawn between them, type filled and stroked at exactly the place, font, size and text of a glyph filled only on a line finished so still comes in as a filled object and a stroked one, as the device can't tell its stroke pass from the start of one over that glyph. Tests: `type_filled_and_stroked_after_a_dense_page_of_filled_type_is_filled_and_stroked`, `type_filled_and_stroked_over_a_finished_glyph_after_a_path_is_filled_and_stroked`, `an_outline_glyph_in_a_tj_over_more_lines_than_are_kept_leaves_fill_and_stroke_apart`; scores and estimates unchanged. | From 758a62317b17724f85c95652d1b31a099e742cd8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 14:01:22 -0800 Subject: [PATCH 043/193] Correct XMP array insertion and empty item values --- crates/js/src/xmp_classes.rs | 13 ++++++++++--- crates/js/src/xmp_tests.rs | 18 ++++++++++++++++++ docs/mcp.md | 4 +++- docs/target-app-parity.md | 2 ++ 4 files changed, 33 insertions(+), 4 deletions(-) diff --git a/crates/js/src/xmp_classes.rs b/crates/js/src/xmp_classes.rs index 2588485114..40a3769fb3 100644 --- a/crates/js/src/xmp_classes.rs +++ b/crates/js/src/xmp_classes.rs @@ -16,6 +16,8 @@ //! 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. //! //! `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 @@ -626,7 +628,10 @@ fn insert_item(i: &mut Interp, o: ObjId, ns: &str, name: &str, index: Option len, - Some(-1) => 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)), @@ -717,7 +722,8 @@ fn insert_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> Js 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 = xml_text(i, &arg(args, 3), 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) } @@ -727,7 +733,8 @@ fn set_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRes 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 = xml_text(i, &arg(args, 3), 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) } diff --git a/crates/js/src/xmp_tests.rs b/crates/js/src/xmp_tests.rs index b8c1f7274c..edd70e3fe1 100644 --- a/crates/js/src/xmp_tests.rs +++ b/crates/js/src/xmp_tests.rs @@ -119,6 +119,24 @@ fn properties_arrays_and_namespaces_round_trip() { assert_eq!(string("XMPMeta.getNamespaceURI('dc:')"), "http://purl.org/dc/elements/1.1/"); } +#[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] diff --git a/docs/mcp.md b/docs/mcp.md index 4ac7e7b6bb..628d27699e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3388,7 +3388,9 @@ rules for these objects: `deleteProperty`, `doesPropertyExist`, `countArrayItems`, `getArrayItem`, `appendArrayItem`, `insertArrayItem`, `setArrayItem`, `deleteArrayItem`, `doesArrayItemExist`, `getLocalizedText` and `setLocalizedText`, and the functions `XMPMeta.registerNamespace`, `getNamespacePrefix` and `getNamespaceURI`. A path is a property name, - `prefix:name`, or either with `[n]` (from 1) or `[last()]` for an array item. Arrays hold simple items; a structure + `prefix:name`, or either with `[n]` (from 1) or `[last()]` for an array item. `insertArrayItem` with + `XMPConst.ARRAY_LAST_ITEM` inserts before the last existing item and rejects an empty array. `insertArrayItem` + and `setArrayItem` store `null` as an empty item value. Arrays hold simple items; a structure or a value with qualifiers that a packet holds is kept as it was written, and `getProperty` gives its options. An array item with an `xml:lang` qualifier has the qualifier and language options in `getProperty` and `getArrayItem`. A value with qualifiers in the `rdf:value` form also gives the text of its `rdf:value`, and an empty property element diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8fedb40187..d15873b281 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -34,6 +34,8 @@ Native saves on Unix flush the destination directory after writing or replacing ## Feature submission evidence +XMP array insertion with `XMPConst.ARRAY_LAST_ITEM` precedes the last existing item and rejects an empty array. Array insertion and replacement store `null` as an empty item value. `crates/js/src/xmp_tests.rs` covers ordering, empty arrays, and null values. + `vectorcraft-js` ends a paused or waiting run before `Realm::run` or `Realm::start` compiles new source. Its globals remain available. The earlier run's remaining code and queued jobs do not run. Regressions in `crates/js/src/host_tests.rs` cover paused scripts, Promise reactions, waiting host calls, invalid replacement source, and deferred language settings. History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. From 2ccc604ceccd95db3886f73351268a881c7f51c7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:36:13 -0800 Subject: [PATCH 044/193] Keep sharp width changes in Stroke previews --- crates/ui-egui/src/panels/stroke.rs | 229 ++++++++++++++++++++++++++-- 1 file changed, 216 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index d7406230d7..fefe1d1515 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -551,24 +551,155 @@ pub(crate) fn arrow_thumb(cx: &ContentPainterCx, rect: Rect, arrow: Option<&Arro thumbs.paint(cx, rect, &state, &ThumbPaint::default().checker(false).tint(DataColor::new(cx.ink()))); } -/// The silhouette of a width profile (its points; None: the plain bar) in `r` as its top and bottom edges. A profile -/// made with the Width tool can be many times the stroke's weight: the silhouette is scaled to fit `r` by its widest -/// point (#909). -fn profile_outline(r: Rect, points: Option<&[(f64, f64, f64)]>) -> (Vec, Vec) { - let n = 32; +/// The widths entering and leaving one position in a thumbnail's stroke profile. +#[derive(Clone, Copy)] +struct ProfileKnot { + t: f64, + incoming: (f64, f64), + outgoing: (f64, f64), +} + +const PROFILE_KNOT_SPACING: f64 = 1e-9; + +/// Extracts the knots to draw. Long profiles keep sharp changes and their adjacent knots over smooth detail. +fn profile_knots(mut points: &[(f64, f64, f64)]) -> Vec { + const MAX_KNOTS: usize = 512; + let long = points.len() > MAX_KNOTS; + let mut groups = std::iter::from_fn(|| { + let (&(t, left, right), rest) = points.split_first()?; + let joined = rest.iter().take_while(|point| point.0 - t <= PROFILE_KNOT_SPACING).count(); + let &(_, outgoing_left, outgoing_right) = &points[joined]; + points = &rest[joined..]; + Some(ProfileKnot { t, incoming: (left, right), outgoing: (outgoing_left, outgoing_right) }) + }) + .filter(|knot| (0.0..=1.0).contains(&knot.t)) + .peekable(); + let mut knots: Vec = Vec::new(); + let mut previous: Option = None; + let mut keep_next = false; + let mut steps = 0; + let mut turning_points = 0; + while let Some(knot) = groups.next() { + let endpoint = knot.t == 0.0 || knot.t == 1.0; + let keep_step = long && !endpoint && knot.incoming != knot.outgoing && steps < MAX_KNOTS; + let choose_turn = |before: f64, middle: f64, after: f64| middle.total_cmp(&before) != after.total_cmp(&middle); + let keep_turn = long + && turning_points < MAX_KNOTS + && previous.zip(groups.peek()).is_some_and(|(before, after)| { + choose_turn(before.outgoing.0, knot.incoming.0, after.incoming.0) || choose_turn(before.outgoing.1, knot.incoming.1, after.incoming.1) + }); + let shape_knot = keep_step || keep_turn; + if shape_knot + && let Some(before) = previous + && knots.last().is_none_or(|last| last.t < before.t) + { + knots.push(before); + } + if !long || endpoint || keep_next || shape_knot { + knots.push(knot); + } + if keep_step { + steps += 1; + } + if keep_turn && !keep_step && !endpoint { + turning_points += 1; + } + previous = Some(knot); + keep_next = shape_knot; + } + knots +} + +/// Widest factor that occupies at least half a physical pixel in the piecewise-linear mesh. +fn profile_scale(widths: &[(f64, f64, f64)], pixel_width: f64) -> f64 { + let maximum = widths.iter().flat_map(|&(_, left, right)| [left, right]).filter(|w| w.is_finite()).fold(1.0, f64::max); + if maximum == 1.0 || pixel_width <= 0.0 { + return 1.0; + } + let has_span = |factor: f64| { + let mut length = [0.0; 2]; + for pair in widths.windows(2) { + let [(from, left, right), (to, next_left, next_right)] = pair else { continue }; + let span = to - from; + for (side, (&before, &after)) in [left, right].into_iter().zip([next_left, next_right]).enumerate() { + let before = if before.is_finite() { before } else { 0.0 }; + let after = if after.is_finite() { after } else { 0.0 }; + let continues = after >= factor; + length[side] = match (before >= factor, continues) { + (true, true) => length[side] + span, + (true, false) => length[side] + span * (before - factor) / (before - after), + (false, true) => span * (after - factor) / (after - before), + (false, false) => 0.0, + }; + if length[side] * pixel_width >= 0.5 { + return true; + } + if !continues { + length[side] = 0.0; + } + } + } + false + }; + if has_span(maximum) { + return maximum; + } + // Search exponents so even a huge imported width at a subpixel spike cannot dominate the result. + let (mut low, mut high) = (0.0, maximum.log2()); + for _ in 0..20 { + let middle = (low + high) * 0.5; + if has_span(middle.exp2()) { + low = middle; + } else { + high = middle; + } + } + low.exp2() +} + +/// The silhouette of a width profile (its points; None: the plain bar) in `r` as its top and bottom edges. +/// A profile made with the Width tool can be many times the stroke's weight, so scale its silhouette to fit `r`. +fn profile_outline(r: Rect, pixels_per_point: f32, points: Option<&[(f64, f64, f64)]>) -> (Vec, Vec) { + const SEGMENTS: usize = 32; let half = r.height() / 2.0 - 1.0; - let widths: Vec<(f64, f64)> = (0..=n).map(|i| points.map_or((0.35, 0.35), |p| WidthProfile::at_points(p, i as f64 / n as f64))).collect(); - let widest = widths.iter().map(|(l, rr)| l.max(*rr)).filter(|w| w.is_finite()).fold(1.0, f64::max); + let mut widths = Vec::new(); + let mut covered = [false; SEGMENTS + 1]; + for knot in profile_knots(points.unwrap_or_default()) { + let ProfileKnot { t, incoming: (left, right), outgoing: (outgoing_left, outgoing_right) } = knot; + let nearby = (t * SEGMENTS as f64).round() as usize; + let grid = nearby as f64 / SEGMENTS as f64; + if t == grid || ((1..SEGMENTS).contains(&nearby) && (t - grid).abs() <= PROFILE_KNOT_SPACING) { + covered[nearby] = true; + } + // The first point contributes only its outgoing width, the last only its incoming width. + if t > 0.0 { + widths.push((t, left, right)); + } + if t == 0.0 || (t < 1.0 && knot.incoming != knot.outgoing) { + widths.push((t, outgoing_left, outgoing_right)); + } + } + for (i, covered) in covered.into_iter().enumerate() { + if !covered { + let t = i as f64 / SEGMENTS as f64; + let (l, r) = points.map_or((0.35, 0.35), |p| WidthProfile::at_points(p, t)); + widths.push((t, l, r)); + } + } + // Keep incoming and outgoing values in order where they share an x coordinate. + widths.sort_by(|a, b| a.0.total_cmp(&b.0)); + let x = |t: f64| r.left() + t as f32 * r.width(); + let pixel_width = f64::from(r.width()) * f64::from(pixels_per_point); + let widest = profile_scale(&widths, pixel_width); let side = |w: f64| if w.is_finite() { (w / widest).clamp(0.0, 1.0) as f32 * half } else { 0.0 }; - let x = |i: usize| r.left() + i as f32 / n as f32 * r.width(); - let top = widths.iter().enumerate().map(|(i, (l, _))| pos2(x(i), r.center().y - side(*l))).collect(); - let bottom = widths.iter().enumerate().map(|(i, (_, rr))| pos2(x(i), r.center().y + side(*rr))).collect(); + let top = widths.iter().map(|(t, left, _)| pos2(x(*t), r.center().y - side(*left))).collect(); + let bottom = widths.iter().map(|(t, _, right)| pos2(x(*t), r.center().y + side(*right))).collect(); (top, bottom) } /// Draws a width profile's silhouette ([`profile_outline`]) into `rect` in the surface's ink, clipped to it. pub fn paint_profile(cx: &ContentPainterCx, rect: Rect, points: Option<&[(f64, f64, f64)]>) { - let (top, bottom) = profile_outline(rect, points); + let (top, bottom) = profile_outline(rect, cx.pixels_per_point(), points); let ink = cx.ink(); let mut mesh = egui::Mesh::default(); for (t, b) in top.iter().zip(&bottom) { @@ -732,12 +863,12 @@ mod tests { #[test] fn wide_profiles_fit_their_preview() { let r = Rect::from_min_size(pos2(10.0, 10.0), egui::vec2(80.0, 16.0)); - let (top, bottom) = profile_outline(r, Some(&[(0.0, 1.0, 1.0), (0.5, 10.0, 10.0), (1.0, 1.0, 1.0)])); + let (top, bottom) = profile_outline(r, 1.0, Some(&[(0.0, 1.0, 1.0), (0.5, 10.0, 10.0), (1.0, 1.0, 1.0)])); let all: Vec<_> = top.iter().chain(&bottom).collect(); assert!(all.iter().all(|p| p.y >= r.top() && p.y <= r.bottom()), "{all:?}"); let middle = all.iter().map(|p| (p.y - r.center().y).abs()).fold(0.0, f32::max); assert!((middle - (r.height() / 2.0 - 1.0)).abs() < 1e-3, "the widest point fills the box ({middle})"); - let (top, bottom) = profile_outline(r, None); + let (top, bottom) = profile_outline(r, 1.0, None); assert!(top.iter().chain(&bottom).all(|p| (p.y - r.center().y).abs() <= 0.35 * (r.height() / 2.0 - 1.0) + 1e-3)); } @@ -761,6 +892,78 @@ mod tests { assert_eq!(head.stop, Some(0.5)); } + #[test] + fn width_profile_thumbnails_keep_sharp_changes_and_visible_endpoints() { + let r = Rect::from_min_size(pos2(10.0, 10.0), egui::vec2(80.0, 16.0)); + let pulse = + [(0.0, 1.0, 1.0), (0.47, 1.0, 1.0), (0.47, 10.0, 10.0), (0.475, 10.0, 10.0), (0.49, 10.0, 10.0), (0.49, 1.0, 1.0), (1.0, 1.0, 1.0)]; + let long_pulse: Vec<_> = std::iter::once(pulse[0]) + .chain((1..=512).flat_map(|i| [(f64::from(i) / 1200.0, 1.0, 1.0); 2])) + .chain(pulse[1..].iter().copied()) + .collect(); + for profile in [&pulse[..], long_pulse.as_slice()] { + let (top, _) = profile_outline(r, 1.0, Some(profile)); + for t in [0.47, 0.49] { + let x = r.left() + t * r.width(); + let edge: Vec<_> = top.iter().filter(|point| (point.x - x).abs() < 1e-3).collect(); + assert_eq!(edge.len(), 2, "both sides of each step remain"); + assert!((edge[1].y - edge[0].y).abs() > 5.0, "the step keeps its height"); + } + } + + let with_taper: Vec<_> = + long_pulse.iter().copied().filter(|p| p.0 < 0.47).chain([(0.475, 1.0, 1.0), (0.475, 10.0, 10.0), (0.485, 1.0, 1.0), pulse[6]]).collect(); + let (top, _) = profile_outline(r, 1.0, Some(&with_taper)); + let taper_end = r.left() + 0.485 * r.width(); + assert!(top.iter().any(|p| (p.x - taper_end).abs() < 1e-3 && p.y > r.top() + 5.0), "the continuous knot sets where the taper ends"); + + let plateau = [(0.0, 1.0, 1.0), (0.4945, 1.0, 1.0), (0.4945, 10.0, 10.0), (0.502, 10.0, 10.0), (0.502, 1.0, 1.0), pulse[6]]; + let (top, _) = profile_outline(r, 1.0, Some(&plateau)); + assert!(top[0].y > r.top() + 5.0, "a grid sample cannot split a visible plateau for scaling"); + + let narrow: Vec<_> = long_pulse + .iter() + .copied() + .filter(|p| p.0 < 0.47) + .chain([(0.47, 1.0, 1.0), (0.47, 100.0, 100.0), (0.4701, 100.0, 100.0), (0.4702, 1.0, 1.0), pulse[6]]) + .collect(); + let (top, _) = profile_outline(r, 1.0, Some(&narrow)); + assert!(top.iter().all(|p| (p.y - (r.top() + 1.0)).abs() < 1e-3), "adding distant knots cannot make a subpixel spike visible"); + + let continuous: Vec<_> = long_pulse + .iter() + .copied() + .filter(|p| p.0 < 0.47) + .chain([(0.47, 1.0, 1.0), (0.4799, 1.1, 1.1), (0.48, 100.0, 100.0), (0.4801, 1.1, 1.1), (0.49, 1.0, 1.0), pulse[6]]) + .collect(); + let (top, _) = profile_outline(r, 1.0, Some(&continuous)); + assert!(top[0].y < r.top() + 3.0, "a subpixel continuous peak cannot shrink the whole stroke"); + + let endpoints = [(0.0, 100.0, 100.0), (0.0, 1.0, 1.0), (1.0, 1.0, 1.0), (1.0, 100.0, 100.0)]; + let (top, bottom) = profile_outline(r, 1.0, Some(&endpoints)); + assert!(top.iter().all(|p| (p.y - (r.top() + 1.0)).abs() < 1e-3)); + assert!(bottom.iter().all(|p| (p.y - (r.bottom() - 1.0)).abs() < 1e-3)); + + let cluster = [(0.0, 1.0, 1.0), (0.48, 1.0, 1.0), (0.48 + 2e-10, 100.0, 100.0), (0.48 + 5e-10, 1.0, 1.0), (1.0, 1.0, 1.0)]; + let (top, _) = profile_outline(r, 1.0, Some(&cluster)); + assert!(top.iter().all(|p| (p.y - (r.top() + 1.0)).abs() < 1e-3), "the preview samples the same exposed widths as the stroke"); + + let nearby = [(0.0, 1.0, 1.0), (0.48, 1.0, 1.0), (0.48, 10.0, 10.0), (0.48000005, 10.0, 10.0), (0.48000005, 1.0, 1.0), (1.0, 1.0, 1.0)]; + let wide = Rect::from_min_size(r.min, egui::vec2(20_000_000.0, r.height())); + let (top, _) = profile_outline(wide, 1.0, Some(&nearby)); + let falling = wide.left() + 0.48000005_f32 * wide.width(); + let outgoing = top.iter().rfind(|point| point.x == falling).unwrap(); + assert!(outgoing.y > wide.top() + 5.0, "the second step ends the pulse"); + for thumbnail in [r, r.translate(egui::vec2(1000.0, 0.0))] { + let (top, _) = profile_outline(thumbnail, 1.0, Some(&nearby)); + assert!(top.iter().all(|p| (p.y - (r.top() + 1.0)).abs() < 1e-3), "a subpixel pulse cannot change the scale as the panel moves"); + } + + let collapsed = [(0.0, 1.0, 1.0), (0.48 - 2e-9, 1.0, 1.0), (0.48, 100.0, 100.0), (0.48 + 2e-9, 1.0, 1.0), (1.0, 1.0, 1.0)]; + let (top, _) = profile_outline(r, 1.0, Some(&collapsed)); + assert!(top.iter().all(|p| (p.y - (r.top() + 1.0)).abs() < 1e-3), "a peak collapsed to one x cannot scale the thumbnail"); + } + #[test] fn while_typing_the_panel_strokes_the_selected_characters() { use vectorcraft_doc::{LineJoin, NodeKind}; From ebf351024594f9baf2ef4057aec02ebff3c00c96 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 14:41:51 -0800 Subject: [PATCH 045/193] Exercise the dialog after changing the active document --- crates/ui-egui/src/dialogs/new_text_style.rs | 50 ++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index 2b13671cdd..bc133a77e7 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -103,3 +103,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); + } +} From cb73a47f0c29de3871eebac88a26bc2915da27c7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 14:46:26 -0800 Subject: [PATCH 046/193] Keep new styles in their opening document --- crates/ui-egui/src/dialogs/new_text_style.rs | 22 +++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index bc133a77e7..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(()) } From 2a939130435d50c119793cb168af968c5d63e618 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 14:51:56 -0800 Subject: [PATCH 047/193] Exercise Character Style Options after switching documents --- .../src/dialogs/char_style_options/tests.rs | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) 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..6b39964c0f 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,70 @@ 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 unchanged_basic_fields_preserve_original_keys() { for attrs in [ From 1b7f00551a6c4cd0b0b932d9a31d32fb0d8ec486 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 14:46:15 -0800 Subject: [PATCH 048/193] Keep Relink attached to its opening document --- crates/ui-egui/src/dialogs/relink.rs | 68 +++++++++++++++++++++++++--- 1 file changed, 62 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/relink.rs b/crates/ui-egui/src/dialogs/relink.rs index b0d67a92f0..c9bf384dca 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,14 +194,14 @@ 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>) { @@ -393,6 +402,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"]); From ef7d2286a95cff7987685d6b2330448505546d6e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 14:53:19 -0800 Subject: [PATCH 049/193] Keep Character Style Options in its opening document --- .../ui-egui/src/dialogs/char_style_options.rs | 45 ++++++++++++++++--- .../src/dialogs/char_style_options/tests.rs | 21 +++++++++ crates/ui-egui/src/lib.rs | 2 +- 3 files changed, 60 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index f1d1b618af..51c00df1fe 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,20 @@ 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)>, +} + 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 +1219,37 @@ 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 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 preview.activation == active { + 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) { + let previous = app.char_style_preview.activation; + if previous.is_some() && previous != Some(activation) && app.session.in_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 previous == Some(activation) { preview.live } else { LivePreview::default() }; + let (live, answer) = drive(app, live, tl!("Character Style Options"), "charStyle.edit", &frame); + app.char_style_preview = Preview { live, activation: Some(activation) }; + 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 6b39964c0f..cbf7c386cf 100644 --- a/crates/ui-egui/src/dialogs/char_style_options/tests.rs +++ b/crates/ui-egui/src/dialogs/char_style_options/tests.rs @@ -190,6 +190,27 @@ fn cancelling_style_options_leaves_the_other_documents_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()); +} + #[test] fn unchanged_basic_fields_preserve_original_keys() { for attrs in [ diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a9b143e397..d63ae41a52 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -311,7 +311,7 @@ pub struct VectorcraftApp { /// Check Spelling's walk through the documents' type, while its dialog is open. pub(crate) spelling: Option, /// The Character Style Options dialog's live preview. - pub(crate) char_style_preview: dialogs::preview::LivePreview, + pub(crate) char_style_preview: dialogs::char_style_options::Preview, /// The Paragraph Style Options dialog's live preview. pub(crate) para_style_preview: dialogs::preview::LivePreview, /// The Justification dialog, while it is open. From 65c031d068884efc643d0f6aa4f2ed5af03bc7f8 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 15:02:33 -0800 Subject: [PATCH 050/193] Use the current stroke paint API in Properties --- crates/ui-egui/src/panels/properties/appearance_section.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/properties/appearance_section.rs b/crates/ui-egui/src/panels/properties/appearance_section.rs index cd71a0f035..e2ae112143 100644 --- a/crates/ui-egui/src/panels/properties/appearance_section.rs +++ b/crates/ui-egui/src/panels/properties/appearance_section.rs @@ -102,7 +102,7 @@ fn effect_delete(app: &mut VectorcraftApp, ui: &mut Ui, id: NodeId, effects: &[( /// active Appearance row in `PropertiesUi::edited_profiled`. False while the Type tool edits text or /// the Live Paint Bucket is active, when the list edits the stroke the panel shows. fn edited_strokes_profiled(app: &mut VectorcraftApp) -> bool { - if panels::character::text_editing(app).is_some() || app.session.bucket_paints() { + if panels::character::text_editing(app).is_some() || app.session.tool_paints(true) { return false; } let Some(st) = app.session.active() else { return false }; From 4b029c657e15e7badf5d476ae80a443f0be96886 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 15:02:33 -0800 Subject: [PATCH 051/193] Use the current stroke paint API in Properties --- crates/ui-egui/src/panels/properties/appearance_section.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/properties/appearance_section.rs b/crates/ui-egui/src/panels/properties/appearance_section.rs index cd71a0f035..e2ae112143 100644 --- a/crates/ui-egui/src/panels/properties/appearance_section.rs +++ b/crates/ui-egui/src/panels/properties/appearance_section.rs @@ -102,7 +102,7 @@ fn effect_delete(app: &mut VectorcraftApp, ui: &mut Ui, id: NodeId, effects: &[( /// active Appearance row in `PropertiesUi::edited_profiled`. False while the Type tool edits text or /// the Live Paint Bucket is active, when the list edits the stroke the panel shows. fn edited_strokes_profiled(app: &mut VectorcraftApp) -> bool { - if panels::character::text_editing(app).is_some() || app.session.bucket_paints() { + if panels::character::text_editing(app).is_some() || app.session.tool_paints(true) { return false; } let Some(st) = app.session.active() else { return false }; From 8c637199101958ebca2194495895b327168835dc Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 15:02:33 -0800 Subject: [PATCH 052/193] Use the current stroke paint API in Properties --- crates/ui-egui/src/panels/properties/appearance_section.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/properties/appearance_section.rs b/crates/ui-egui/src/panels/properties/appearance_section.rs index cd71a0f035..e2ae112143 100644 --- a/crates/ui-egui/src/panels/properties/appearance_section.rs +++ b/crates/ui-egui/src/panels/properties/appearance_section.rs @@ -102,7 +102,7 @@ fn effect_delete(app: &mut VectorcraftApp, ui: &mut Ui, id: NodeId, effects: &[( /// active Appearance row in `PropertiesUi::edited_profiled`. False while the Type tool edits text or /// the Live Paint Bucket is active, when the list edits the stroke the panel shows. fn edited_strokes_profiled(app: &mut VectorcraftApp) -> bool { - if panels::character::text_editing(app).is_some() || app.session.bucket_paints() { + if panels::character::text_editing(app).is_some() || app.session.tool_paints(true) { return false; } let Some(st) = app.session.active() else { return false }; From 836b5e735bf777a8fe02cef8b19001736bf7966f Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 15:19:29 -0800 Subject: [PATCH 053/193] Keep sampler execution evidence tied to its tested revision --- docs/roadmap.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index bd6d39dbc4..77080b77a9 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -199,7 +199,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | -| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview; this main86d composition is unrun). | 6–10 | +| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | From 2c905d82280230950cbab7cd8eb60bee5955111f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:21:09 -0800 Subject: [PATCH 054/193] Restart a refused Each Link Separately pass --- crates/ui-egui/src/dialogs/relink.rs | 37 ++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/crates/ui-egui/src/dialogs/relink.rs b/crates/ui-egui/src/dialogs/relink.rs index c9bf384dca..ac99cf9b0c 100644 --- a/crates/ui-egui/src/dialogs/relink.rs +++ b/crates/ui-egui/src/dialogs/relink.rs @@ -205,6 +205,10 @@ impl HoldsOk for RelinkDialog { } 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); } } @@ -499,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] From 03c438480efd95fe038859a77cebfdb9ef254a44 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:00:01 -0800 Subject: [PATCH 055/193] Keep Save PDF and PDF Export tied to their opening drawing --- crates/ui-egui/src/dialogs/save_pdf.rs | 36 +++++++++++++++----- crates/ui-egui/src/dialogs/save_pdf/tests.rs | 22 ++++++++++++ 2 files changed, 50 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index e003cf6a7e..b03cf32bcd 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. + 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() { From 5ca266423c702ed73bcf5274a1a32a186c85e7dc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:00:01 -0800 Subject: [PATCH 056/193] Keep Vector Halftone in its opening drawing --- crates/ui-egui/src/canvas/tests.rs | 42 ++++++++++++++++++++++++++ crates/ui-egui/src/dialogs/halftone.rs | 37 ++++++++++++++++++++--- 2 files changed, 75 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d560fd2b6b..d17bda10c0 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/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) } From 0b910720285d631ca4f4a0b322864dc380c491ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:03:19 -0800 Subject: [PATCH 057/193] Keep hyphenation on its opening drawing and text --- crates/ui-egui/src/dialogs/hyphenation.rs | 85 ++++++++++++++++++++++- 1 file changed, 82 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/hyphenation.rs b/crates/ui-egui/src/dialogs/hyphenation.rs index 749c1970a9..e8f9a78ed2 100644 --- a/crates/ui-egui/src/dialogs/hyphenation.rs +++ b/crates/ui-egui/src/dialogs/hyphenation.rs @@ -43,7 +43,29 @@ 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; + + 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)) = character::text_editing(app) { + 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)); @@ -57,11 +79,20 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let lengths = crate::canvas::rulers::general_lengths(app); let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| ParamDialog::new(KIND, tl!("Hyphenation"), rows(lengths))); 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) @@ -156,4 +187,52 @@ 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_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); + } } From da0d3357c8f3e334941f83d893aa96ea6629b685 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:03:05 -0800 Subject: [PATCH 058/193] Exercise Simplify dialog preview and outline after a drawing switch --- crates/ui-egui/src/dialogs/path_ops.rs | 75 ++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 64176e93ac..343a2d9e19 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -339,6 +339,81 @@ pub(crate) fn open_simplify(app: &mut VectorcraftApp, tolerance: f64) { open_dialog(app, PathOp::Simplify, simplify_dialog(tolerance), None); } + +#[cfg(test)] +mod simplify_options_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"); + } +} + fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remember: Option) { let Some(ctx) = app.ui_ctx.clone() else { app.status("There is no window to show the dialog in."); From 7a8cf41a2754d49411318b95481941434fbce737 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:07:16 -0800 Subject: [PATCH 059/193] Keep prominent peaks and short tapers in Stroke thumbnails --- crates/ui-egui/src/panels/stroke.rs | 102 ++++++++++++++++++---------- 1 file changed, 65 insertions(+), 37 deletions(-) diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index fefe1d1515..c62559fd65 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -561,11 +561,11 @@ struct ProfileKnot { const PROFILE_KNOT_SPACING: f64 = 1e-9; -/// Extracts the knots to draw. Long profiles keep sharp changes and their adjacent knots over smooth detail. +/// Extracts the knots to draw. Long profiles keep the largest steps and the knots furthest from +/// the line between their neighbors, along with those neighbors. fn profile_knots(mut points: &[(f64, f64, f64)]) -> Vec { const MAX_KNOTS: usize = 512; - let long = points.len() > MAX_KNOTS; - let mut groups = std::iter::from_fn(|| { + let knots: Vec<_> = std::iter::from_fn(|| { let (&(t, left, right), rest) = points.split_first()?; let joined = rest.iter().take_while(|point| point.0 - t <= PROFILE_KNOT_SPACING).count(); let &(_, outgoing_left, outgoing_right) = &points[joined]; @@ -573,41 +573,43 @@ fn profile_knots(mut points: &[(f64, f64, f64)]) -> Vec { Some(ProfileKnot { t, incoming: (left, right), outgoing: (outgoing_left, outgoing_right) }) }) .filter(|knot| (0.0..=1.0).contains(&knot.t)) - .peekable(); - let mut knots: Vec = Vec::new(); - let mut previous: Option = None; - let mut keep_next = false; - let mut steps = 0; - let mut turning_points = 0; - while let Some(knot) = groups.next() { - let endpoint = knot.t == 0.0 || knot.t == 1.0; - let keep_step = long && !endpoint && knot.incoming != knot.outgoing && steps < MAX_KNOTS; - let choose_turn = |before: f64, middle: f64, after: f64| middle.total_cmp(&before) != after.total_cmp(&middle); - let keep_turn = long - && turning_points < MAX_KNOTS - && previous.zip(groups.peek()).is_some_and(|(before, after)| { - choose_turn(before.outgoing.0, knot.incoming.0, after.incoming.0) || choose_turn(before.outgoing.1, knot.incoming.1, after.incoming.1) - }); - let shape_knot = keep_step || keep_turn; - if shape_knot - && let Some(before) = previous - && knots.last().is_none_or(|last| last.t < before.t) - { - knots.push(before); - } - if !long || endpoint || keep_next || shape_knot { - knots.push(knot); - } - if keep_step { - steps += 1; - } - if keep_turn && !keep_step && !endpoint { - turning_points += 1; - } - previous = Some(knot); - keep_next = shape_knot; + .collect(); + if knots.len() <= MAX_KNOTS { + return knots; } - knots + + let width_difference = |from: (f64, f64), to: (f64, f64)| (from.0 - to.0).abs().max((from.1 - to.1).abs()); + let mut steps = Vec::new(); + let mut bends = Vec::new(); + for (i, knot) in knots.iter().enumerate() { + if knot.t == 0.0 || knot.t == 1.0 { + continue; + } + let step = width_difference(knot.incoming, knot.outgoing); + if step > 0.0 && step.is_finite() { + steps.push((i, step)); + } else if let Some((before, after)) = i.checked_sub(1).and_then(|prev| knots.get(prev).zip(knots.get(i + 1))) { + let t = (knot.t - before.t) / (after.t - before.t); + let interpolate = |a: f64, b: f64| (1.0 - t) * a + t * b; + let line = (interpolate(before.outgoing.0, after.incoming.0), interpolate(before.outgoing.1, after.incoming.1)); + let bend = width_difference(knot.incoming, line); + if bend > 0.0 && bend.is_finite() { + bends.push((i, bend)); + } + } + } + let mut keep = vec![false; knots.len()]; + for candidates in [&mut steps, &mut bends] { + if candidates.len() > MAX_KNOTS { + candidates.select_nth_unstable_by(MAX_KNOTS, |a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + } + for &(i, _) in candidates.iter().take(MAX_KNOTS) { + let first = i.saturating_sub(1); + let last = (i + 1).min(knots.len() - 1); + keep[first..=last].fill(true); + } + } + knots.into_iter().zip(keep).filter_map(|(knot, keep)| (keep || knot.t == 0.0 || knot.t == 1.0).then_some(knot)).collect() } /// Widest factor that occupies at least half a physical pixel in the piecewise-linear mesh. @@ -964,6 +966,32 @@ mod tests { assert!(top.iter().all(|p| (p.y - (r.top() + 1.0)).abs() < 1e-3), "a peak collapsed to one x cannot scale the thumbnail"); } + #[test] + fn width_profile_thumbnails_keep_a_late_peak() { + let r = Rect::from_min_size(pos2(10.0, 10.0), egui::vec2(80.0, 16.0)); + let mut noisy: Vec<_> = (0..514) + .map(|i| { + let width = if i % 2 == 0 { 1.0 } else { 1.01 }; + (f64::from(i) / 1200.0, width, width) + }) + .collect(); + noisy.extend([(0.474, 1.0, 1.0), (0.48, 10.0, 10.0), (0.486, 1.0, 1.0), (1.0, 1.0, 1.0)]); + let (top, _) = profile_outline(r, 1.0, Some(&noisy)); + let peak_x = r.left() + 0.48 * r.width(); + assert!(top.iter().any(|p| (p.x - peak_x).abs() < 1e-3 && p.y < r.top() + 2.0), "the later peak survives the earlier small turns"); + } + + #[test] + fn width_profile_thumbnails_do_not_widen_a_short_taper() { + let r = Rect::from_min_size(pos2(10.0, 10.0), egui::vec2(80.0, 16.0)); + let flat = (0..514).map(|i| (f64::from(i) / 1200.0, 1.0, 1.0)); + let short_taper: Vec<_> = flat + .chain([(0.47, 1.0, 1.0), (0.47, 10.0, 10.0), (0.47001, 9.999, 9.999), (0.4702, 1.1, 1.1), (0.49, 1.02, 1.02), (1.0, 1.0, 1.0)]) + .collect(); + let (top, _) = profile_outline(r, 1.0, Some(&short_taper)); + assert!(top[0].y < r.top() + 3.0, "the short taper cannot shrink the baseline"); + } + #[test] fn while_typing_the_panel_strokes_the_selected_characters() { use vectorcraft_doc::{LineJoin, NodeKind}; From ff9bc615c34e9c618ba1061ec2615be025f56a19 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:07:17 -0800 Subject: [PATCH 060/193] Keep Gradient Stop edits with the stop that opened the popover --- crates/ui-egui/src/dialogs/gradient_stop.rs | 121 +++++++++++++++++--- 1 file changed, 106 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 3ba900ff01..2fe5dbaebc 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -31,6 +31,7 @@ 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_doc::NodeId; use vectorcraft_geom::{Point, Rect}; use vectorcraft_tools::params::color_json; @@ -58,6 +59,42 @@ enum Target { Point(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) + } +} + impl Target { fn color(&self) -> Color { match self { @@ -127,13 +164,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: TargetKey, + fields: PopoverFields, +} + /// The target's values and what the Color panel shows, as `pump` last pushed them. #[derive(Clone)] struct Feed { @@ -163,6 +205,7 @@ struct Filed { /// The gradient stop popover. pub(crate) struct GradientStopPopover { + target: TargetKey, /// Where it opened. pub(crate) anchor: Anchor, /// The view it shows. @@ -177,8 +220,9 @@ pub(crate) struct GradientStopPopover { } impl GradientStopPopover { - fn new(anchor: Anchor) -> Self { + fn new(anchor: Anchor, target: TargetKey) -> Self { Self { + target, anchor, tab: Tab::default(), at: Pos2::ZERO, @@ -199,21 +243,21 @@ 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)); 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,8 +299,8 @@ 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() }) } } @@ -397,8 +441,9 @@ 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 }; dialogs.with(|host| { - host.open(GradientStopPopover::new(anchor)); + host.open(GradientStopPopover::new(anchor, key)); }); refresh(app, &ctx, dialog_id(KIND), &target); } @@ -409,9 +454,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: key, fields })) => { if fields != PopoverFields::default() && let Some(target) = selected(app) + && key.matches(app, &target) { apply(app, &target, &fields); } @@ -420,11 +466,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { Some(_) => return, None => {} } - if !dialogs.with(|host| host.is_open::()) { - return; - } - let Some(target) = selected(app) else { - // The stop or point went away (undo, another object selected): nothing left to edit. + let Some(key) = dialogs.with(|host| host.get_by_id::(id).map(|popover| popover.target.clone())) else { return }; + let Some(target) = selected(app).filter(|target| key.matches(app, target)) else { dialogs.with(|host| host.cancel_by_id(ctx, id)); return; }; @@ -432,6 +475,16 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { if filed.fields != PopoverFields::default() { apply(app, &target, &filed.fields); } + if filed.fields.location.is_some() + && let Some(index) = app.session.selected_stop() + { + // The stop can cross its neighbor when its location changes. + dialogs.with(|host| { + if let Some(popover) = host.get_mut_by_id::(id) { + popover.target.index = index; + } + }); + } if let Some((name, color)) = filed.swatch && let Some(target) = selected(app) { @@ -591,6 +644,44 @@ 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); + } + #[test] fn on_a_freeform_gradient_it_edits_the_selected_point() { let mut app = app(); From 65b52aed876c7ca1a1ab5e6b9675ba6be07abc97 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:07:21 -0800 Subject: [PATCH 061/193] Exercise Offset Path preview in a second drawing --- crates/ui-egui/src/dialogs/path_ops.rs | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 343a2d9e19..37ea857dd6 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -339,9 +339,8 @@ pub(crate) fn open_simplify(app: &mut VectorcraftApp, tolerance: f64) { open_dialog(app, PathOp::Simplify, simplify_dialog(tolerance), None); } - #[cfg(test)] -mod simplify_options_tests { +mod preview_document_tests { use super::*; use crate::dialogs::tests::{app, cancel, confirm, frame, set}; @@ -412,6 +411,28 @@ mod simplify_options_tests { 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); + } } fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remember: Option) { From 78ebac9eab9928bc770609cf18a8c2f123c4872b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:10:46 -0800 Subject: [PATCH 062/193] Keep Simplify and Offset Path previews in the opening drawing --- crates/ui-egui/src/dialogs/path_ops.rs | 115 +++++++++++++++++++------ 1 file changed, 90 insertions(+), 25 deletions(-) diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 37ea857dd6..7351a70863 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -3,6 +3,8 @@ //! Every dialog is a held parameter dialog: its OK is the closure given to `open_held`, a refusal keeps it open with //! the reason, and [`pump`] only runs the live preview of the kinds that have one. +use std::sync::{Arc, Weak}; + // PLAN: the framework import paths below are assumed from the contract rows (craft-ui-patterns re-exports contract and // runtime; the form-dialog items live under `patterns::form_dialogs`; `Field` and `NumberField` under craft-ui-widgets). use craft::behavior::ColumnWidth; @@ -19,7 +21,7 @@ use craft::ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; use craft::ui::text::{NumberField, NumberOutput}; use craft::ui::value_drag::SliderScale; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{NodeId, NodeKind, Selection}; use vectorcraft_geom::PathData; use super::form; @@ -111,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. @@ -309,6 +314,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 }; @@ -440,6 +475,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(); @@ -455,17 +495,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 => { @@ -479,24 +513,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."), } } @@ -568,6 +618,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 { @@ -575,13 +636,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); @@ -602,7 +667,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() From 14b118f9c4d6968e26f2d93b8d7404e7be7e9e26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:27:53 -0800 Subject: [PATCH 063/193] Place browser drops in the tiled drawing under the pointer --- crates/ui-egui/src/canvas/panes.rs | 21 ++++++++++++ crates/ui-egui/src/place.rs | 35 +++++++++++--------- crates/ui-egui/src/tests/place.rs | 53 ++++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+), 16 deletions(-) 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/place.rs b/crates/ui-egui/src/place.rs index 1b2a678a4e..6458cc8d5d 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -68,8 +68,10 @@ pub enum DropTarget { /// Where a dropped file landed, as far as the platform says. #[derive(Clone, Copy, Debug, PartialEq)] pub enum DropSpot { - /// On the canvas, at this document point. + /// On the active canvas, at this document point. Canvas(Point), + /// On a tiled canvas, identified by its document uid and point. + TiledCanvas { doc: u64, at: Point }, /// Off the canvas: a panel, the tab bar, a dialog. Elsewhere, /// The platform gives no place (floating panel windows, desktop drags without a position). @@ -805,28 +807,29 @@ impl VectorcraftApp { /// plug-in reads opens wherever it is dropped, as File → Open opens it ([`io::opens_as`], /// [`fileio::opens_with_importer`]). pub fn drop_target(&self, name: &str, spot: DropSpot, shift: bool) -> DropTarget { - let (Some(st), Some(v)) = (self.session.active(), self.view()) else { return DropTarget::Open }; - let at = match spot { - _ if io::opens_as(name).is_some() || fileio::opens_with_importer(name) => return DropTarget::Open, - DropSpot::Elsewhere => return DropTarget::Open, - DropSpot::Canvas(at) => at, - DropSpot::Unknown if is_document(name) => return DropTarget::Open, - DropSpot::Unknown => v.center, + if io::opens_as(name).is_some() || fileio::opens_with_importer(name) { + return DropTarget::Open; + } + let (st, at) = match spot { + DropSpot::Canvas(at) => (self.view().and(self.session.active()), at), + DropSpot::TiledCanvas { doc, at } => (self.session.documents().iter().find(|st| st.uid == doc), at), + DropSpot::Unknown if !is_document(name) => { + let Some(view) = self.view() else { return DropTarget::Open }; + (self.session.active(), view.center) + } + _ => return DropTarget::Open, }; - DropTarget::Place(DropAt { doc: st.uid, reverts: st.reverts, at, embed: shift }) + st.map_or(DropTarget::Open, |st| DropTarget::Place(DropAt { doc: st.uid, reverts: st.reverts, at, embed: shift })) } /// Where a drop at `pos` on the window lands, for a host that follows its file drags itself (the - /// web's): on the active canvas as it last showed, else elsewhere; without a position, unknown. + /// web's): on the canvas shown under the pointer, else elsewhere; without a position, unknown. pub fn drop_spot(&self, pos: Option) -> DropSpot { let Some(pos) = pos else { return DropSpot::Unknown }; - match self.canvas_view() { - Some(view) if view.rect.contains(pos) => { - let at = view.to_doc(pos); - DropSpot::Canvas(Point::new(at.x, at.y)) - } - _ => DropSpot::Elsewhere, + if let Some(view) = self.canvas_view().filter(|view| view.rect.contains(pos)) { + return DropSpot::Canvas(view.to_doc(pos)); } + crate::canvas::panes::file_drop_at(self, pos).map_or(DropSpot::Elsewhere, |(doc, at)| DropSpot::TiledCanvas { doc, at }) } } diff --git a/crates/ui-egui/src/tests/place.rs b/crates/ui-egui/src/tests/place.rs index f23f63b763..6ae8dcd25c 100644 --- a/crates/ui-egui/src/tests/place.rs +++ b/crates/ui-egui/src/tests/place.rs @@ -462,6 +462,59 @@ fn images(app: &VectorcraftApp, i: usize) -> usize { n } +#[test] +fn a_browser_drop_uses_the_inactive_tiled_canvas_under_the_pointer() { + let mut app = app(); + let inbox = crate::place::PlaceInbox::default(); + app.services.place_inbox = Some(inbox.clone()); + let ctx = window(&app); + app.run("file.new", json!({"width": 600, "height": 500})).unwrap(); + app.run("window.arrange.tile", json!({})).unwrap(); + laid_out(&mut app, &ctx); + assert_eq!(app.session.active_index(), Some(1)); + + let (w, _) = app.canvas.panes.last.iter().copied().find(|(w, _)| w.0 == 0).unwrap(); + let view = crate::doc_windows::view(&app, w).unwrap(); + let pos = view.rect.center() + vec2(19.0, -13.0); + assert!(!app.canvas_view().unwrap().rect.contains(pos)); + let want = view.canvas(app.ui_scaling(), view.rect).to_doc(pos); + let name = "pane.png"; + let spot = app.drop_spot(Some(pos)); + let (doc, reverts) = (app.session.documents()[0].uid, app.session.documents()[0].reverts); + let drop = DropAt { doc, reverts, at: want, embed: true }; + assert_eq!(app.drop_target(name, spot, true), DropTarget::Place(drop)); + assert_eq!(app.drop_target("palette.gpl", spot, false), DropTarget::Open); + + inbox.lock().unwrap().push(crate::place::PlaceArrival { name: name.into(), bytes: png(20, 10, 72.0), drop }); + frame(&mut app, &ctx, vec![], &[], false); + assert_eq!((images(&app, 0), images(&app, 1)), (1, 0)); + let center = selected_image(&app).geometric_bounds().unwrap().center(); + assert!((center.x - want.x).abs() < 1e-6 && (center.y - want.y).abs() < 1e-6, "{center:?} vs {want:?}"); +} + +#[test] +fn a_browser_drop_cannot_reach_an_inactive_tile_through_a_floating_window() { + let mut app = app(); + let ctx = window(&app); + for _ in 0..2 { + app.run("file.new", json!({"width": 600, "height": 500})).unwrap(); + } + app.run("window.arrange.tile", json!({})).unwrap(); + app.run("window.arrange.floatInWindow", json!({"index": 2, "at": [45, 130]})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + laid_out(&mut app, &ctx); + assert_eq!(app.session.active_index(), Some(1)); + + let (tile, _) = app.canvas.panes.last.iter().copied().find(|(w, _)| w.0 == 0).unwrap(); + let tile = crate::doc_windows::view(&app, tile).unwrap().rect; + let floating = crate::doc_windows::view(&app, (2, app.ui.floating[0].view)).unwrap().rect; + let overlap = tile.intersect(floating); + assert!(overlap.is_positive(), "the floating window {floating:?} covers part of the tile {tile:?}"); + let pos = overlap.center(); + assert!(!app.canvas_view().unwrap().rect.contains(pos)); + assert_eq!(app.drop_target("covered.png", app.drop_spot(Some(pos)), false), DropTarget::Open); +} + /// The web reads dropped files asynchronously (#359): a file that arrives after another document /// became active still lands where it was dropped, and is dropped itself when that document closed. #[test] From 64d19d9f416a802984f30ab22aca3367b6512140 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:33:52 -0800 Subject: [PATCH 064/193] Keep Symbolism density tied to its original selection --- .../ui-egui/src/dialogs/symbolism_options.rs | 95 +++++++++++++++++-- 1 file changed, 87 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 7cfe2649ec..f60181ea8a 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -10,7 +10,7 @@ //! and `affectsDensity` (Symbol Sizer). 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}; @@ -83,6 +83,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 +97,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 +106,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,6 +116,48 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { json!({ "dialog": KIND }) } +#[derive(Clone)] +struct DensityTarget { + value: Option, + document: Option<(u64, u64)>, + sets: Vec, +} + +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() + .copied() + .filter(|id| { + let id = vectorcraft_doc::NodeId(*id); + doc.doc.node(id).is_some_and(vectorcraft_engine::cmd::is_symbol_set) && editable(id) + }) + .collect() + }; + if !sets.is_empty() { + app.run("symbol.setDensity", json!({ "from": from, "to": to, "ids": sets }))?; + } + Ok(()) + } +} + /// The selected symbol sets that can be edited (a locked or hidden one keeps its density). fn selected_sets(app: &VectorcraftApp) -> Vec { let Some(st) = app.session.active() else { return vec![] }; @@ -196,6 +237,44 @@ 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 ok_sets_the_options_with_a_locked_symbol_set_selected() { let mut app = app(); From 00d41a7c7ce4e05dbc10abfdd2c1bb793c0ce184 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:47:16 -0800 Subject: [PATCH 065/193] Place Path Ops regression tests after the implementation --- crates/ui-egui/src/dialogs/path_ops.rs | 192 ++++++++++++------------- 1 file changed, 96 insertions(+), 96 deletions(-) diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 7351a70863..fc99b2c20c 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -374,102 +374,6 @@ pub(crate) fn open_simplify(app: &mut VectorcraftApp, tolerance: f64) { open_dialog(app, PathOp::Simplify, simplify_dialog(tolerance), None); } -#[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); - } -} - fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remember: Option) { let Some(ctx) = app.ui_ctx.clone() else { app.status("There is no window to show the dialog in."); @@ -677,3 +581,99 @@ pub(crate) fn original_paths(app: &VectorcraftApp) -> Vec<(NodeId, &PathData)> { }) .collect() } + +#[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); + } +} From 97e09e6a62d5ffc53068386ca3ba6dc0318b46e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:51:22 -0800 Subject: [PATCH 066/193] Keep Transform previews and confirmation in the original drawing --- crates/ui-egui/src/dialogs/transform.rs | 120 +++++++++++++++++++++--- 1 file changed, 108 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/dialogs/transform.rs b/crates/ui-egui/src/dialogs/transform.rs index 4e124e5345..e8651efb49 100644 --- a/crates/ui-egui/src/dialogs/transform.rs +++ b/crates/ui-egui/src/dialogs/transform.rs @@ -106,6 +106,8 @@ impl Kind { pub(crate) struct Open { /// The dialog's id on the window's host. pub id: DialogId, + /// The drawing whose selection and reference point the dialog acts on. + document: Option, /// Which transform it is. pub kind: Kind, /// The reference point of a tool click, sent with every command but Move's. @@ -114,6 +116,25 @@ pub(crate) struct Open { pub preview: LivePreview, } +impl Open { + fn in_source(&self, app: &VectorcraftApp) -> bool { + self.document == app.session.active().map(|doc| doc.uid) + } + + fn owns_preview(&self, app: &VectorcraftApp) -> bool { + app.session.active().and_then(|doc| doc.interaction.as_ref()).is_some_and(|interaction| { + interaction.preview.as_ref().map_or_else(|| interaction.label == self.kind.title(), |(command, _)| command == self.kind.command()) + }) + } + + fn cancel_preview(&mut self, app: &mut VectorcraftApp) { + let preview = std::mem::take(&mut self.preview); + if self.in_source(app) && self.owns_preview(app) { + preview.cancel(app); + } + } +} + /// Opens the dialog of `kind`; `tool` is the tool click's params (its `origin`), or `{}` from a menu. pub(crate) fn open(app: &mut VectorcraftApp, kind: Kind, tool: &Value) { let Some(ctx) = app.ui_ctx.clone() else { @@ -121,6 +142,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: Kind, tool: &Value) { return; }; let Value::Object(opening) = opening(app, kind) else { return }; + let document = app.session.active().map(|doc| doc.uid); let rows = rows(app, kind, &opening); let fields = fields_of(&rows, &opening); let dialog = HostedParamDialog::new(&ctx, kind.command(), fields, move |f| { @@ -138,13 +160,13 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: Kind, tool: &Value) { app.status("no window".to_string()); return; }; - app.object_dialogs.transform = Some(Open { id, kind, origin: tool.get("origin").cloned(), preview: LivePreview::default() }); + app.object_dialogs.transform = Some(Open { id, document, kind, origin: tool.get("origin").cloned(), preview: LivePreview::default() }); } /// Rolls the preview back and drops the record: Cancel, Esc and the close box. fn cancel_preview(app: &mut VectorcraftApp) { - if let Some(open) = app.object_dialogs.transform.take() { - open.preview.cancel(app); + if let Some(mut open) = app.object_dialogs.transform.take() { + open.cancel_preview(app); } } @@ -156,6 +178,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let shown = dialogs.with(|host| host.get_mut_by_id::(id).map(|d| (d.is_previewing(), d.fields().clone()))); let Some((on, fields)) = shown else { return }; let Some(mut open) = app.object_dialogs.transform.take() else { return }; + if !open.in_source(app) { + open.preview = LivePreview::default(); + app.object_dialogs.transform = Some(open); + return; + } + if !open.owns_preview(app) { + open.preview = LivePreview::default(); + } let (cmd, mut params) = command(app, kind, &fields, open.origin.as_ref()); if kind == Kind::Scale { add_scale_options(app, &fields, &mut params); @@ -168,16 +198,19 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// OK: the preview is rolled back and the command run as without one, so its undo step, its journal /// entry and Transform Again are the same either way. fn ok(app: &mut VectorcraftApp, kind: Kind, ctx: &egui::Context, result: &ParamResult) -> Result<(), String> { - let origin = match app.object_dialogs.transform.take() { - Some(open) => { - let origin = open.origin; - open.preview.cancel(app); - origin - } - None => None, - }; + let Some(mut open) = app.object_dialogs.transform.take() else { return Err("the Transform dialog is closed".into()) }; + if open.id != result.id || open.kind != kind { + app.object_dialogs.transform = Some(open); + return Err("the Transform dialog was replaced".into()); + } + if !open.in_source(app) { + app.object_dialogs.transform = Some(open); + return Err(tl!("Return to the original drawing to apply the transform").into()); + } + open.cancel_preview(app); let fields = &result.fields; - let (cmd, mut params) = command(app, kind, fields, origin.as_ref()); + let (cmd, mut params) = command(app, kind, fields, open.origin.as_ref()); + app.object_dialogs.transform = Some(open); if kind == Kind::Scale { params = with_scale_options(app, fields, params)?; } @@ -190,6 +223,7 @@ fn ok(app: &mut VectorcraftApp, kind: Kind, ctx: &egui::Context, result: &ParamR } } result.remember(ctx); + app.object_dialogs.transform = None; Ok(()) } @@ -458,6 +492,68 @@ mod tests { } } + #[test] + fn transform_preview_pauses_before_editing_a_second_drawing() { + let mut rig = two_drawings(); + rig.open("object.move"); + rig.set("dx", json!(35)); + assert_eq!(rig.bounds().x0, 135.0); + rig.app.run("document.activate", json!({"index": 1})).unwrap(); + rig.frame(); + assert_eq!(rig.bounds().x0, 10.0); + assert!(!rig.app.session.in_interaction()); + + rig.app.run("document.activate", json!({"index": 0})).unwrap(); + rig.frame(); + assert_eq!(rig.bounds().x0, 135.0); + rig.confirm(); + assert_eq!(rig.bounds().x0, 135.0); + assert!(!rig.app.session.in_interaction()); + } + + #[test] + fn transform_ok_waits_for_its_original_drawing() { + let mut rig = two_drawings(); + rig.open("object.scale"); + rig.set("preview", json!(false)); + rig.set("sx", json!(200)); + rig.app.run("document.activate", json!({"index": 1})).unwrap(); + let steps = rig.undo_steps(); + let id = rig.id(); + let dialogs = rig.app.dialogs().unwrap(); + rig.confirm(); + assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_)))); + assert_eq!(rig.size(), (25.0, 15.0)); + assert_eq!(rig.undo_steps(), steps); + + rig.app.run("document.activate", json!({"index": 0})).unwrap(); + crate::tests::picks::answer_dialog(&mut rig.app, id, &[], true); + assert_eq!(rig.size().0, 120.0); + assert!(rig.app.object_dialogs.transform.is_none()); + assert!(dialogs.with(|h| h.get_by_id::(id).is_none())); + } + + #[test] + fn cancelling_transform_leaves_a_second_drawings_interaction_alone() { + let mut rig = two_drawings(); + rig.open("object.move"); + rig.set("dx", json!(35)); + assert!(rig.app.session.in_interaction()); + rig.app.run("document.activate", json!({"index": 1})).unwrap(); + rig.app.session.begin_interaction("The second drawing's edit").unwrap(); + rig.cancel(); + assert_eq!(rig.app.session.active().unwrap().interaction.as_ref().unwrap().label, "The second drawing's edit"); + assert_eq!(rig.bounds().x0, 10.0); + } + + fn two_drawings() -> Rig { + let mut rig = Rig::new(); + rig.app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + rig.app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 25, "height": 15})).unwrap(); + rig.app.run("document.activate", json!({"index": 0})).unwrap(); + rig + } + #[test] fn scale_options_start_from_and_update_the_preferences() { let mut rig = Rig::new(); From 921357fe838eab1bfe0ec8cbc52fa79763f7ff88 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:57:16 -0800 Subject: [PATCH 067/193] Reproduce approving Layers Delete Selection after File Revert --- .../ui-egui/src/panels/layers/tests_reveal.rs | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/crates/ui-egui/src/panels/layers/tests_reveal.rs b/crates/ui-egui/src/panels/layers/tests_reveal.rs index b0e33f482a..b3ce78d24d 100644 --- a/crates/ui-egui/src/panels/layers/tests_reveal.rs +++ b/crates/ui-egui/src/panels/layers/tests_reveal.rs @@ -483,6 +483,39 @@ fn isolation_keeps_a_confirmed_delete_to_the_rows_listed() { assert!(app.session.active().unwrap().doc.node(sub).is_none()); } +#[test] +fn delete_selection_approval_does_not_remove_restored_layer_art() { + let (app, [_, sub, _, _, art, _]) = nested(); + let mut app = crate::testing::windowed(app); + let file = std::env::temp_dir().join(format!("vectorcraft-layer-delete-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("layer.setProps", json!({"id": sub.0, "name": "Edited sublayer"})).unwrap(); + assert!(app.run("ui.layerDelete", json!({"ids": [sub.0]})).unwrap().is_null()); + 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.node(sub).unwrap().name.as_deref(), Some("Sub")); + assert!(st.doc.node(art).is_some()); + let undo = undo_len(&app); + + let confirm = craft::ui::dialog::dialog_id(crate::dialogs::confirm::KIND); + crate::tests::picks::answer_dialog(&mut app, confirm, &[], true); + let st = app.session.active().unwrap(); + assert!(st.doc.node(sub).is_some() && st.doc.node(art).is_some(), "old approval cannot delete restored artwork"); + assert_eq!(undo_len(&app), undo); + + assert!(app.run("ui.layerDelete", json!({"ids": [sub.0]})).unwrap().is_null()); + crate::tests::picks::answer_dialog(&mut app, confirm, &[], true); + let st = app.session.active().unwrap(); + assert!(st.doc.node(sub).is_none() && st.doc.node(art).is_none(), "a fresh confirmation still deletes the requested layer"); +} + /// A document put in isolation mode opens its isolated row at once, and showing the documents again opens nothing. #[test] fn isolation_opens_the_isolated_row_of_each_document() { From 4490db0c4b7a610e54aef0ad406a45ad1063dc00 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:00:58 -0800 Subject: [PATCH 068/193] Process every file in a mixed canvas drop --- crates/ui-egui/src/place.rs | 19 ++++++++----------- crates/ui-egui/src/tests/place.rs | 24 ++++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 3 files changed, 33 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 1b2a678a4e..006f55d56c 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -830,16 +830,15 @@ impl VectorcraftApp { } } -/// Files held over, or dropped on, a canvas that would be placed there. +/// A file drop that includes artwork for this canvas. pub struct CanvasDrop { files: Vec, at: Point, } -/// The canvas as a target of files dragged from the OS: it takes those [`VectorcraftApp::drop_target`] -/// places, and outlines the canvas while they hover. On the web the browser gives a hovered file's -/// type but not its name, so any file is taken then, including libraries, presets, plug-ins and -/// shortcut sets, which open when dropped. +/// The canvas accepts a file drop when [`VectorcraftApp::drop_target`] would place any member and +/// outlines the canvas while it hovers. The drop router places or opens each member of the batch. +/// A file hovering without a name is also eligible until its name arrives. pub struct CanvasFiles<'a> { app: &'a VectorcraftApp, rect: egui::Rect, @@ -859,13 +858,11 @@ impl FilesTarget for CanvasFiles<'_> { fn accept(&self, payload: &OsFiles, at: egui::Pos2, _op: DropOperation) -> Option { let doc = self.view.to_doc(at); let at = Point::new(doc.x, doc.y); - let files: Vec = payload + let accepts = payload .files .iter() - .filter(|f| f.name.is_empty() || matches!(self.app.drop_target(&f.name, DropSpot::Canvas(at), false), DropTarget::Place(_))) - .cloned() - .collect(); - (!files.is_empty()).then_some(CanvasDrop { files, at }) + .any(|file| file.name.is_empty() || matches!(self.app.drop_target(&file.name, DropSpot::Canvas(at), false), DropTarget::Place(_))); + accepts.then(|| CanvasDrop { files: payload.files.clone(), at }) } fn mark(&self, _: &CanvasDrop) -> DropMark { @@ -878,7 +875,7 @@ impl FilesTarget for CanvasFiles<'_> { } } -/// Files dropped on the canvas ([`CanvasFiles`]), placed where they landed; Shift embeds them. +/// Route the whole canvas drop. Shift embeds its placed artwork. // PLAN: `DropOperation` has no Shift, so the held modifiers of the drop's frame are read here. pub fn canvas_drop(app: &mut VectorcraftApp, ctx: &egui::Context, dropped: CanvasDrop) { let shift = ctx.input(|i| i.modifiers.shift); diff --git a/crates/ui-egui/src/tests/place.rs b/crates/ui-egui/src/tests/place.rs index f23f63b763..701170aac3 100644 --- a/crates/ui-egui/src/tests/place.rs +++ b/crates/ui-egui/src/tests/place.rs @@ -340,6 +340,30 @@ fn a_dropped_png_is_placed_where_it_was_dropped() { assert!(matches!(&selected_image(&app).kind, NodeKind::Image(im) if im.link.is_none())); } +#[test] +fn a_mixed_canvas_drop_places_the_artwork_and_opens_the_palette() { + let mut app = app(); + let ctx = window(&app); + let rect = laid_out(&mut app, &ctx); + let dir = Folder::new("ui-place-image-and-palette"); + let palette = dir.file("mixed.gpl", b"GIMP Palette\nName: Mixed Drop\n#\n255 0 0\tRed\n"); + let png = dir.file("artwork.png", &png(20, 10, 72.0)); + let pos = rect.center() + vec2(60.0, -40.0); + let want = app.canvas_view().unwrap().to_doc(pos); + + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos)], &[&palette, &png], false); + + let placed = selected_image(&app); + let center = placed.geometric_bounds().unwrap().center(); + assert!((center.x - want.x).abs() < 1e-6 && (center.y - want.y).abs() < 1e-6, "{center:?} vs {want:?}"); + assert_eq!((app.session.documents().len(), images(&app, 0)), (1, 1)); + assert!( + crate::panels::library_panel::last_open(&app.ui).is_some_and(|library| library.id == format!("loaded/{palette}")), + "the same canvas drop must open the palette: {}", + app.ui.status + ); +} + /// A document dropped where the platform gives no position opens as a new tab, not into the open /// document; the pictures dropped with it are placed in the document that was open, before it /// opens. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index df69c18888..078605bce2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1300,7 +1300,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - An EPS or PostScript file that stops on a PostScript error gives the error's name as PostScript spells it (`typecheck`, `rangecheck` and the other names the reader raises, except `undefined`, whose message names the unknown name) followed by what it means, in the warning after opening and in the error when the file can't be opened. The status bar and the open-error dialog show the meaning in the interface language: each meaning has a row in every catalog (`postscript_error_meanings_are_translated`). - The macOS menu bar is built from the in-window menus (one model, `native_menu`) and laid out as a Mac app's: the VectorCraft menu holds About, Settings ▸ (each Preferences page, General… ⌘K), Language ▸, Appearance ▸ (UI brightness), Services, Hide VectorCraft ⌃⌘H (⌘H stays Hide Edges), Hide Others, Show All and Quit; Window gains Minimize ⌃⌘M, Zoom and Bring All to Front, and Help the system's search field. Its key equivalents go back to egui as key presses, so user shortcuts, focused text fields and the Type tool's input method behave as in the window, and nothing fires twice; enabled, check marks and labels update in place. `--in-window-menus` or `VECTORCRAFT_IN_WINDOW_MENUS=1` keeps the menus in the window; `ui.inspect` reports `nativeMenuBar`. - macOS: Finder opens every format File › Open reads with VectorCraft (double-click, Open With, a drop on the Dock icon, `open -a`), at launch or while it runs; the release and `cargo xtask bundle` apps share one `Info.plist` that declares those document types, owning only VectorCraft's own formats. The DMG opens on a designed Finder window, VectorCraft.app beside the `Applications` link over a background with the app icon (#493). - - Swatch and graphic style libraries, Libraries panel files, presets and plug-ins open wherever they are dropped on the window, as File › Open opens them. + - Swatch and graphic style libraries, Libraries panel files, presets and plug-ins open wherever they are dropped on the window, as File › Open opens them. A mixed canvas drop places its artwork and opens its library files. Evidence includes `a_mixed_canvas_drop_places_the_artwork_and_opens_the_palette`. - File › Open has a filter for each kind of file it opens other than a document, Graphic Style Libraries (`.vcstyles`, after Swatch libraries) and Perspective grid presets (`.vcperspective`, after Print presets) among them, and Other Library… lists its library filter once. Graph designs are stored in the document, with no file type or filter of their own. Tests: `open_exts_cover_every_readable_format`, `library_open_filters_list_library_formats_first`. - **Symbol libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)): Window › Symbol Libraries and the Symbols panel's Symbol Libraries Menu open each library in a library panel of its own, as swatch and graphic style libraries do. The built-in libraries, Basic Shapes, UI Frames (Panel, Button and Bar with default 9-slice guides), Map Markers (Pin, Flag, Crosshair and Checkpoint, no default 9-slice), Inventory Icons (Sword, Shield, Potion, Key and Gem, no default 9-slice), Skill Icons (Attack, Defend, Heal, Buff and Ult, no default 9-slice), Weather Icons (Sun, Moon, Cloud, Rain, Thunder and Snow, no default 9-slice), Nature Icons (Leaf, Flower, Tree, Mountain and Wave, no default 9-slice) and Media Controls (Play, Pause, Stop, Skip Next, Shuffle and Repeat, no default 9-slice), are original art generated in code (`crates/engine/src/cmd/symbollib.rs`). A click on a symbol adds it to the document's Symbols as one undo step, with its Symbol Options (size, registration, export type, 9-slice guides) and every resource it uses (the symbols it nests, patterns, swatches, brushes, graphic styles, images), and makes it the current symbol; a symbol the document already has is not added again and another symbol of the same name keeps its name, the library's comes in numbered. Thumbnails, in the library panels and the Symbols panel, draw a symbol with the symbols it nests and the patterns and images it uses. Dragging a library symbol onto the canvas also places an instance there, in the same step ([placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)). Save Symbols (the library menu) and Save Symbol Library… (the Symbols panel menu) write the document's symbols as a `.vectorcraft` document holding only them, into the user library folder (listed under User Defined) or a file; Other Library… reads the symbols of any document VectorCraft opens; a file it can't read is an error and opens no panel. Tests: `crates/engine/src/tests/symbollib.rs`, `crates/ui-egui/src/panels/tests_symbol_libraries.rs`, `panels::symbols::tests::thumbnails_show_the_symbols_a_symbol_nests`, `canvas::tests::a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step`. - **Nature Icons library:** Leaf, Flower, Tree, Mountain and Wave are five original procedural vector symbols. Each has a finite natural size, can be added and placed through the symbol library controls, and survives saving to a library file; no 9-slice guides are assigned by default. From c8f33dbce8ea110b30ab651c32a194baa0ec4728 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:02:02 -0800 Subject: [PATCH 069/193] Reject stale Layers Delete Selection approval after File Revert --- crates/ui-egui/src/panels/layers/controls.rs | 21 ++++++++++++------- .../ui-egui/src/panels/layers/tests_reveal.rs | 1 + 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index 17c66bfe68..6097efffd1 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -472,13 +472,14 @@ pub(crate) fn footer(tree: &DocLayers, ui: &mut Ui, out: &mut Vec<(String, Value } } -/// `ui.layerDelete {ids?|id?, doc?, confirmed?}`: Delete Selection as the Layers panel runs it (the +/// `ui.layerDelete {ids?|id?, doc?, reverts?, confirmed?}`: Delete Selection as the Layers panel runs it (the /// trash button, rows dropped on it, the panel menu, Delete and Backspace), on the rows /// `layer.delete` takes (default: the highlighted rows, else the current layer; in isolation mode a /// current layer outside the isolated art is an error). When a layer or sublayer among them holds art (an object other than a /// guide, hidden, locked and nested ones included), it asks first: OK deletes those rows, by id, in -/// the same document (`doc`, its uid, with `confirmed`); with another document active then, nothing -/// is deleted. In isolation mode a row outside the isolated art is an error, and nothing is deleted. Other rows, and rows `layer.delete` refuses (an unknown id, every top-level layer), +/// the same document (`doc`, its uid, and `reverts`, its saved-content generation, with `confirmed`). +/// Switching documents or reverting the drawing invalidates the approval. In isolation mode a row +/// outside the isolated art is an error. Other rows, and rows `layer.delete` refuses (an unknown id, every top-level layer), /// go to `layer.delete` at once. → `layer.delete`'s result, or null while the question is open pub fn delete(app: &mut VectorcraftApp, p: &Value) -> Result { super::unrevealed(app, |app| delete_rows(app, p)) @@ -487,15 +488,19 @@ pub fn delete(app: &mut VectorcraftApp, p: &Value) -> Result { /// [`delete`], which locates nothing. fn delete_rows(app: &mut VectorcraftApp, p: &Value) -> Result { let confirmed = crate::menus::opt_bool(p, "confirmed")?.unwrap_or(false); - let key = "doc"; - let doc = match p.get(key) { - None | Some(Value::Null) => None, - Some(v) => Some(v.as_u64().ok_or_else(|| format!("`{key}` must be a whole number of 0 or more"))?), + let opening = |key| match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_u64().map(Some).ok_or_else(|| format!("`{key}` must be a whole number of 0 or more")), }; + let doc = opening("doc")?; + let reverts = opening("reverts")?; let st = app.session.active().ok_or("no document open")?; if doc.is_some_and(|d| d != st.uid) { return Err("the active document changed while the question was open; nothing was deleted".into()); } + if reverts.is_some_and(|reverts| reverts != st.reverts) { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").into()); + } let rows: serde_json::Map = ["ids", "id"].iter().filter_map(|k| Some((k.to_string(), p.get(*k)?.clone()))).collect(); // An id the engine refuses: `layer.delete` gives the error, and deletes nothing. let row = |v: &Value| v.as_u64().map(NodeId).filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_ruler_guide())); @@ -532,7 +537,7 @@ fn delete_rows(app: &mut VectorcraftApp, p: &Value) -> Result { [n] if n.is_layer() => tl!("Delete this layer and its artwork?"), _ => tl!("Delete the selected items and their artwork?"), }; - let params = json!({"ids": ids.iter().map(|i| i.0).collect::>(), "doc": st.uid, "confirmed": true}); + let params = json!({"ids": ids.iter().map(|i| i.0).collect::>(), "doc": st.uid, "reverts": st.reverts, "confirmed": true}); crate::dialogs::confirm::ask(app, message, "", "ui.layerDelete", params); Ok(Value::Null) } diff --git a/crates/ui-egui/src/panels/layers/tests_reveal.rs b/crates/ui-egui/src/panels/layers/tests_reveal.rs index b3ce78d24d..ba8f490da6 100644 --- a/crates/ui-egui/src/panels/layers/tests_reveal.rs +++ b/crates/ui-egui/src/panels/layers/tests_reveal.rs @@ -509,6 +509,7 @@ fn delete_selection_approval_does_not_remove_restored_layer_art() { let st = app.session.active().unwrap(); assert!(st.doc.node(sub).is_some() && st.doc.node(art).is_some(), "old approval cannot delete restored artwork"); assert_eq!(undo_len(&app), undo); + assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue."); assert!(app.run("ui.layerDelete", json!({"ids": [sub.0]})).unwrap().is_null()); crate::tests::picks::answer_dialog(&mut app, confirm, &[], true); From 8930964b896aba3c1a9a9e50fb35e7320e28a481 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:04:16 -0800 Subject: [PATCH 070/193] Retire Rearrange Artboards settings and placement after Revert --- .../src/dialogs/rearrange_artboards.rs | 92 ++++++++++++++++--- crates/ui-egui/src/state.rs | 1 + 2 files changed, 79 insertions(+), 14 deletions(-) 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/state.rs b/crates/ui-egui/src/state.rs index 27aa8d39f4..82175cc93c 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -49,6 +49,7 @@ pub enum ViewMove { #[derive(Clone, Debug)] pub struct RearrangePlacement { pub doc: u64, + pub reverts: u64, pub tool: String, pub params: Value, pub ids: Vec, From 47d079602b3895bea7b09278d78dd33388bc4115 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:05:19 -0800 Subject: [PATCH 071/193] Return errors when New Graphic Style cannot be opened --- crates/ui-egui/src/panels/graphic_styles.rs | 38 ++++++++++++++++----- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 1d089378d3..b386f01eb2 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -670,7 +670,11 @@ fn on_footer(app: &mut VectorcraftApp, out: &FooterOutput) { } None => match out.picked { Some(AT_BREAK_LINK) => run_status(app, "graphicStyle.breakLink", json!({})), - Some(AT_NEW) => new_style(app, out.mods.alt), + Some(AT_NEW) => { + if let Err(error) = new_style(app, out.mods.alt) { + app.status(error); + } + } Some(AT_DELETE) => { let names = doomed(&selected(app)); if !names.is_empty() { @@ -736,12 +740,9 @@ fn linked_face(thumbs: StyleThumbs<'_>, doc: &Arc, looks: &Arc Result<(), String> { + let command = if ask { "ui.graphicStyleOptions" } else { "graphicStyle.new" }; + app.run(command, json!({})).map(|_| ()) } /// The styles a style dragged from the panel carries: every highlighted style (`sel`) in panel @@ -870,7 +871,7 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Result { let sel = selected(app); match id.strip_prefix(ROW).and_then(|row| row.strip_prefix('.')) { - Some("new") => new_style(app, true), + Some("new") => new_style(app, true)?, Some("duplicate") => duplicate(app, &sel), // Merged in panel order, which `selected` keeps. Some("merge") => return app.run("ui.mergeGraphicStyles", json!({ "names": sel })), @@ -1099,6 +1100,27 @@ mod tests { app.session.active().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect() } + #[test] + fn new_graphic_style_reports_when_no_drawing_can_open_its_dialog() { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + for _ in 0..2 { + let error = app.run("ui.graphicStyles.new", json!({})).unwrap_err(); + assert!(error.contains("no document")); + assert!(open_dialog(&app, graphic_style_options::KIND).is_none()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); + let before = names(&app); + let steps = app.session.active().unwrap().history.undo.len(); + assert_eq!(app.run("ui.graphicStyles.new", json!({})).unwrap(), Value::Null); + let dialog = open_dialog(&app, graphic_style_options::KIND).expect("a reopened drawing can name a new style"); + assert_eq!(names(&app), before, "opening the name dialog creates no style"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + let ctx = app.ui_ctx.clone().unwrap(); + app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, dialog)); + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + } + } + #[test] fn a_dragged_graphic_style_carries_the_source_document_to_the_canvas() { use craft::ui::runtime::drag; From f669763c4e337b55ffd58c0602bf9c090e276c00 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:05:19 -0800 Subject: [PATCH 072/193] Download the File Info metadata template in the browser --- crates/ui-egui/src/dialogs/file_info.rs | 102 +++++++++++++++++++++++- 1 file changed, 101 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index 80439178a8..15b9ac79c7 100644 --- a/crates/ui-egui/src/dialogs/file_info.rs +++ b/crates/ui-egui/src/dialogs/file_info.rs @@ -113,6 +113,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 +138,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 +224,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), @@ -567,6 +571,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 +611,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 +641,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(())) } @@ -662,6 +693,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(); From 3c9d22f62f71a572900528386c9d256916d4c938 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:06:31 -0800 Subject: [PATCH 073/193] Keep New Swatch edits with their opening drawing --- crates/ui-egui/src/dialogs/new_swatch.rs | 95 +++++++++++++++++++++++- 1 file changed, 92 insertions(+), 3 deletions(-) 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(); From 065996cdba6277a01026d83839f1eeda8a29d9f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:11:28 -0800 Subject: [PATCH 074/193] Discard Gradient Stop edits after replacing the gradient --- crates/ui-egui/src/dialogs/gradient_stop.rs | 187 ++++++++++++++++---- 1 file changed, 152 insertions(+), 35 deletions(-) diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 2fe5dbaebc..622a5ba407 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -13,6 +13,8 @@ //! 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::theme::Srgba; @@ -30,7 +32,7 @@ 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_geom::{Point, Rect}; use vectorcraft_tools::params::color_json; @@ -55,8 +57,8 @@ 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. @@ -77,7 +79,7 @@ impl TargetKey { let fill = app.session.fill_active; let (point, index) = match target { Target::Stop(_, index) => (false, *index), - Target::Point(_, index) => (true, *index), + Target::Point(_, _, index) => (true, *index), }; Some(Self { document: doc.uid, @@ -95,24 +97,43 @@ impl TargetKey { } } +/// The gradient in that slot as the popover last saw it, including any live edits it applied. +#[derive(Clone)] +struct TargetOwner { + key: TargetKey, + paint: Arc, +} + +impl TargetOwner { + fn matches(&self, app: &VectorcraftApp, target: &Target) -> bool { + self.key.matches(app, target) && self.paint.as_ref() == target.paint() + } +} + 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, } } } @@ -122,10 +143,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. @@ -172,7 +194,7 @@ struct PopoverFields { } pub(crate) struct PopoverAnswer { - target: TargetKey, + target: TargetOwner, fields: PopoverFields, } @@ -205,7 +227,7 @@ struct Filed { /// The gradient stop popover. pub(crate) struct GradientStopPopover { - target: TargetKey, + target: TargetOwner, /// Where it opened. pub(crate) anchor: Anchor, /// The view it shows. @@ -220,7 +242,7 @@ pub(crate) struct GradientStopPopover { } impl GradientStopPopover { - fn new(anchor: Anchor, target: TargetKey) -> Self { + fn new(anchor: Anchor, target: TargetOwner) -> Self { Self { target, anchor, @@ -443,7 +465,7 @@ pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) { let Some(target) = selected(app) else { return }; let Some(key) = TargetKey::of(app, &target) else { return }; dialogs.with(|host| { - host.open(GradientStopPopover::new(anchor, key)); + host.open(GradientStopPopover::new(anchor, TargetOwner { key, paint: Arc::new(target.paint().clone()) })); }); refresh(app, &ctx, dialog_id(KIND), &target); } @@ -454,10 +476,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(PopoverAnswer { target: key, fields })) => { + Some(DialogResult::Ok(PopoverAnswer { target: owner, fields })) => { if fields != PopoverFields::default() && let Some(target) = selected(app) - && key.matches(app, &target) + && owner.matches(app, &target) { apply(app, &target, &fields); } @@ -466,8 +488,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { Some(_) => return, None => {} } - let Some(key) = dialogs.with(|host| host.get_by_id::(id).map(|popover| popover.target.clone())) else { return }; - let Some(target) = selected(app).filter(|target| key.matches(app, target)) else { + let Some(mut owner) = dialogs.with(|host| host.get_by_id::(id).map(|popover| popover.target.clone())) else { + return; + }; + let Some(target) = selected(app).filter(|target| owner.matches(app, target)) else { dialogs.with(|host| host.cancel_by_id(ctx, id)); return; }; @@ -476,14 +500,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { 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. - dialogs.with(|host| { - if let Some(popover) = host.get_mut_by_id::(id) { - popover.target.index = index; - } - }); + owner.key.index = index; } if let Some((name, color)) = filed.swatch && let Some(target) = selected(app) @@ -499,20 +520,33 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { crate::panels::gradient::stop_eyedropper(app); return; } - if let Some(target) = selected(app) { - refresh(app, ctx, id, &target); + let Some(target) = selected(app).filter(|target| owner.key.matches(app, target)) else { + dialogs.with(|host| host.cancel_by_id(ctx, id)); + return; + }; + // The popover owns the edits applied in this pass and can continue with their resulting paint. + if owner.paint.as_ref() != target.paint() { + owner.paint = Arc::new(target.paint().clone()); } + 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 })), } } @@ -520,8 +554,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); } @@ -535,7 +569,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); @@ -552,6 +586,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::*; @@ -618,7 +654,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"), } } @@ -682,13 +718,94 @@ mod tests { 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 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); From af2894bd55b0c6471ea6f5a975acd59daf3fdfa3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:12:04 -0800 Subject: [PATCH 075/193] Translate the Saturate Intensity label --- crates/ui-egui/src/dialogs/saturate.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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() })] } From 701b807586b3402147a7ce848626acfc6abb2888 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:12:14 -0800 Subject: [PATCH 076/193] Keep buffered typing before opening Hyphenation --- crates/ui-egui/src/dialogs/hyphenation.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/hyphenation.rs b/crates/ui-egui/src/dialogs/hyphenation.rs index e8f9a78ed2..e9f5b04648 100644 --- a/crates/ui-egui/src/dialogs/hyphenation.rs +++ b/crates/ui-egui/src/dialogs/hyphenation.rs @@ -45,12 +45,13 @@ fn rows(lengths: LengthUnits) -> Vec { pub fn open(app: &mut VectorcraftApp) -> Result { 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)) = character::text_editing(app) { + let ids = if let Some((id, start, end)) = editing { if let Some(story) = character::text_story(app) { story_focus = Some(id); story @@ -214,6 +215,25 @@ mod tests { 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(); From 208de1a4786e82e3424bc36efaaeb1e3508f9f15 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:12:42 -0800 Subject: [PATCH 077/193] Ignore file picker results for a drawing reloaded by Revert --- crates/ui-egui/src/file_asks.rs | 73 ++++++++++++++++++++++++++------- 1 file changed, 59 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/file_asks.rs b/crates/ui-egui/src/file_asks.rs index b5df477b42..f70ee645e4 100644 --- a/crates/ui-egui/src/file_asks.rs +++ b/crates/ui-egui/src/file_asks.rs @@ -29,8 +29,8 @@ type Proceed = Box Result>; /// Whose answer a continuation is. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Owner { - /// The active document when it was asked: dropped with [`closed`] when it has closed, made - /// active before the continuation runs. + /// The active document when asked, made active before the continuation runs. Closing or + /// reverting it retires the request. Document, /// Acts on no document (an app preference, a library, a shortcut set): it goes on whatever is open. Free, @@ -39,9 +39,8 @@ pub(crate) enum Owner { /// A pick asked for and not yet answered. struct Waiting { ticket: PickId, - owner: Owner, - /// The active document's uid when asked (`DocState::uid`); `None` for [`Owner::Free`]. - doc: Option, + /// The active drawing's UID and Revert counter when asked, if the request is document-owned. + doc: Option<(u64, u64)>, /// The automation roots in force when asked: the continuation runs under them, not under the /// desktop's access of the frame the answer comes in. scope: ScopeHandle, @@ -161,11 +160,11 @@ fn start( let Some(host) = app.ui_ctx.as_ref().and_then(Host::try_of_ctx) else { return Value::Null }; let ticket = ask(host.files()); let doc = match owner { - Owner::Document => app.session.active().map(|d| d.uid), + Owner::Document => app.session.active().map(|d| (d.uid, d.reverts)), Owner::Free => None, }; let (scope, automated) = (ScopeHandle::capture(), app.automation_asked()); - app.file_asks.waiting.push(Waiting { ticket, owner, doc, scope, automated, current, then: Box::new(then) }); + app.file_asks.waiting.push(Waiting { ticket, doc, scope, automated, current, then: Box::new(then) }); json!({ "pending": "fileDialog" }) } @@ -264,14 +263,17 @@ pub(crate) fn open_params(picked: &Picked) -> Option> { Some(params) } -/// Make the document asked for (`doc`, by uid) active before its continuation runs: another may be -/// active by now, or it may be gone → false when it can't run (the status bar says why). -fn on_document(app: &mut VectorcraftApp, doc: Option) -> bool { - let Some(uid) = doc else { return true }; - let Some(i) = app.session.documents().iter().position(|d| d.uid == uid) else { +/// Make the original drawing active before running a continuation. The status bar explains why +/// a closed drawing or a different loaded generation cannot receive the result. +fn on_document(app: &mut VectorcraftApp, uid: u64, generation: Option) -> bool { + let Some((i, state)) = app.session.documents().iter().enumerate().find(|(_, d)| d.uid == uid) else { app.status(closed()); return false; }; + if generation.is_some_and(|reverts| state.reverts != reverts) { + app.status(tl!("The drawing was reverted while its file dialog was open")); + return false; + } if app.session.active_index() != Some(i) && let Err(e) = app.run("document.activate", json!({ "index": i })) { @@ -319,7 +321,7 @@ pub(crate) fn poll(app: &mut VectorcraftApp) { } _ => {} } - if w.owner == Owner::Document && !on_document(app, w.doc) { + if w.doc.is_some_and(|(uid, reverts)| !on_document(app, uid, Some(reverts))) { continue; } let Waiting { scope, automated, then, .. } = w; @@ -355,7 +357,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { if let Some(DialogResult::Ok(mut answer)) = files && answer.choice == PromptChoice::Proceed && let Some(r) = answer.take_tag::() - && on_document(app, Some(r.doc)) + && on_document(app, r.doc, None) { let all: Vec = r.files.iter().chain(&r.allowed).cloned().collect(); crate::io::save::allow_replacing(app, &all); @@ -364,3 +366,46 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { report(app, result); } } + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + #[test] + fn an_svg_picker_returns_to_its_opening_tab_only_if_that_drawing_was_not_reverted() { + const SVG: &[u8] = br#""#; + for revert in [true, false] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let picker = crate::tests::picks::scripted(&mut 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("svg-picker-original-drawing"); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("file.saveAs", json!({"path": dir.join("filters.vectorcraft")})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let original = app.session.active().unwrap(); + let version = (original.uid, original.reverts); + let pending = app.run("ui.importSvgFilter", json!({})).unwrap(); + assert_eq!(pending["pending"], json!("fileDialog")); + if revert { + 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); + } + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + picker.answer_contents(&[("shadow.svg", SVG)]); + poll(&mut app); + let docs = app.session.documents(); + assert!(docs[1].doc.svg_filters.is_empty()); + if revert { + assert!(docs[0].doc.svg_filters.is_empty()); + assert_eq!(app.session.active_index(), Some(1)); + } else { + assert_eq!(docs[0].doc.svg_filters[0].name, "Shadow"); + assert_eq!(app.session.active_index(), Some(0)); + } + } + } +} From b7a1d9733688eb46db1214b04ac34234b9a68604 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:14:10 -0800 Subject: [PATCH 078/193] Require an open drawing when adding items from a Library panel --- crates/ui-egui/src/panels/library_panel.rs | 30 +++++++++++++----- .../ui-egui/src/panels/library_panel/tests.rs | 31 +++++++++++++++++++ 2 files changed, 53 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index f0eb4a72e2..ee20b56fed 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -180,7 +180,6 @@ pub(crate) struct Kind { find: fn(&VectorcraftApp, &str) -> Found, path: fn(&VectorcraftApp, &str) -> Option, neighbour: fn(&VectorcraftApp, &str, isize) -> Option, - add: fn(&mut VectorcraftApp, &str, Vec), add_label: &'static str, body: fn(&mut VectorcraftApp, &mut Ui, &str), } @@ -195,7 +194,6 @@ fn kind_of() -> Kind { find: K::find, path: K::path, neighbour: neighbour::, - add: K::add, add_label: K::ADD, body: body::, } @@ -213,6 +211,21 @@ fn kind(kind: &str) -> Option { .find(|k| k.kind == kind) } +/// The document command each library's Add action runs. +fn add_command(kind: &str) -> Option<&'static str> { + match kind { + "swatches" => Some("swatch.library.add"), + "brushes" => Some("brush.addFromLibrary"), + "symbols" => Some("symbol.addFromLibrary"), + "graphicStyles" => Some("graphicStyle.addFromLibrary"), + _ => None, + } +} + +fn can_add(app: &VectorcraftApp, kind: &str) -> bool { + add_command(kind).is_some_and(|command| crate::menus::enabled(app, command)) +} + /// The id of the panel of library `id` of `kind` (`library:swatches:pastels`). pub fn panel_id(kind: &str, id: &str) -> String { format!("{PREFIX}{kind}:{id}") @@ -666,7 +679,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { let title = library_name(id, &name).to_string(); // The footer stays under the browser, which scrolls in the room left above it. let footer_out = RefCell::new(None); - let any = !selection.items.is_empty(); + let any = !selection.items.is_empty() && can_add(app, K::KIND); let mut shown = Panel::new(title.clone()) .collection_body() .footer(|ui, _| *footer_out.borrow_mut() = Some(footer_bar::(any).show_footer(ui))) @@ -707,8 +720,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { } } -/// The panel's footer: the libraries menu, previous / next library, and Add to … , on while `any` item or folder is -/// selected. +/// The panel's footer: the libraries menu, previous / next library, and Add to … , on while items or folders are +/// selected and the document can receive them. fn footer_bar(any: bool) -> FooterBar { let icon = |name: &'static str| IconSpec::svg(IconId::new(name)); FooterBar::actions([ @@ -786,7 +799,7 @@ fn menu_entries(app: &VectorcraftApp, panel: &str) -> Vec { params["panel"] = json!(panel); MenuEntry::Row { command: CommandRef::with_params(command, params), label, enabled, checked } }; - let has_selection = !selected(app, panel).items.is_empty(); + let has_selection = !selected(app, panel).items.is_empty() && can_add(app, k.kind); let mut out = vec![row("ui.libraryPanel.add", json!({}), k.add_label, has_selection, None), MenuEntry::Separator]; out.extend(View::ALL.iter().map(|&(v, label)| row("ui.libraryPanel", json!({ "view": v }), label, true, Some(v == view)))); out.extend([ @@ -835,7 +848,7 @@ pub(crate) fn menu_states(app: &VectorcraftApp, panel: &str, states: &mut Comman } /// Runs a library panel command that the engine does not know: `ui.libraryPanel.add {panel}` adds the -/// panel's selection to the document. +/// panel's selection to the document. A refused addition returns its command's error. pub(crate) fn run(app: &mut VectorcraftApp, id: &str, params: &Value) -> Result { if id != "ui.libraryPanel.add" { return Err(format!("`{id}` isn't a library panel command")); @@ -843,7 +856,8 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, params: &Value) -> Result< let given = params.get("panel").and_then(Value::as_str).unwrap_or_default(); let (k, lib) = parse(given).ok_or_else(|| format!("`{given}` isn't a library panel (see window.swatchLibrary)"))?; let names: Vec = selected(app, given).items.into_iter().map(|key| key.name).collect(); - (k.add)(app, lib, names); + let command = add_command(k.kind).ok_or("this library cannot add items to a drawing")?; + app.run(command, json!({ "library": lib, "names": names }))?; Ok(Value::Null) } diff --git a/crates/ui-egui/src/panels/library_panel/tests.rs b/crates/ui-egui/src/panels/library_panel/tests.rs index 68fc0cf0de..da4cb07bec 100644 --- a/crates/ui-egui/src/panels/library_panel/tests.rs +++ b/crates/ui-egui/src/panels/library_panel/tests.rs @@ -182,6 +182,37 @@ fn modifier_clicks_select_and_add_to_swatches_adds_the_selection() { assert!(selected_names(&app, "library:swatches:brights").is_empty()); } +#[test] +fn adding_selected_library_items_requires_an_open_drawing() { + let mut app = app(); + let ctx = context(); + app.run("window.swatchLibrary", json!({"library": "earth-tones"})).unwrap(); + let panel = "library:swatches:earth-tones"; + click(&mut app, &ctx, "Clay 3", Modifiers::COMMAND, 0.0); + assert_eq!(selected_names(&app, panel), ["Clay 3"]); + let draw = |app: &mut VectorcraftApp, ui: &mut Ui| show(app, ui, panel); + let command = CommandRef::with_params("ui.libraryPanel.add", json!({"panel": panel})); + let menu_enabled = |app: &VectorcraftApp| { + let mut states = CommandStates::new(); + menu_states(app, panel, &mut states); + states.get(&command).is_some_and(CommandState::is_enabled) + }; + assert!(control(&mut app, &ctx, &draw, "Add to Swatches").0); + assert!(menu_enabled(&app)); + + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + assert!(!control(&mut app, &ctx, &draw, "Add to Swatches").0); + assert!(!menu_enabled(&app)); + assert_eq!(selected_names(&app, panel), ["Clay 3"], "the library remains browsable"); + assert!(app.run("ui.libraryPanel.add", json!({"panel": panel})).is_err()); + + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + assert!(control(&mut app, &ctx, &draw, "Add to Swatches").0); + assert!(menu_enabled(&app)); + app.run("ui.libraryPanel.add", json!({"panel": panel})).unwrap(); + assert!(app.session.active().unwrap().doc.swatch("Clay 3").is_some()); +} + const SWATCH_IDS: [&str; 9] = [ "web-safe-216", "grays-neutrals", From e1d9fc9657e76d0619ccf9e38d6bba3884f25e32 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:14:10 -0800 Subject: [PATCH 079/193] Refresh Flattener Preview when a different drawing takes the same tab --- .../ui-egui/src/panels/flattener_preview.rs | 44 ++++++++++++++++--- 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/flattener_preview.rs b/crates/ui-egui/src/panels/flattener_preview.rs index c55c06b1c3..82703526b1 100644 --- a/crates/ui-egui/src/panels/flattener_preview.rs +++ b/crates/ui-egui/src/panels/flattener_preview.rs @@ -68,7 +68,7 @@ impl Settings { /// The document as the last Refresh saw it, and what flattening it would do. struct Shot { doc: Arc, - doc_index: usize, + doc_uid: u64, revision: u64, /// The settings it was taken with. options: FlattenOptions, @@ -121,7 +121,8 @@ pub fn refresh(app: &mut VectorcraftApp) -> Result { let set = &app.ui.flattener_preview; let (o, report) = app.session.flattener_report(&set.params()).map_err(|e| e.to_string())?; let (options, overprints) = (set.options.clone(), set.overprints); - let (st, doc_index) = (app.session.active().ok_or("no document open")?, app.session.active_index().unwrap_or(0)); + let st = app.session.active().ok_or("no document open")?; + let doc_uid = st.uid; let mut out = report.to_json(&st.doc, set.highlight); out["options"] = serde_json::to_value(&o).unwrap_or_default(); let mut fit = st.doc.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b)).unwrap_or(DRect::new(0.0, 0.0, 612.0, 792.0)); @@ -132,7 +133,7 @@ pub fn refresh(app: &mut VectorcraftApp) -> Result { let (doc, revision) = (st.doc.clone(), st.revision); let m = &mut app.flattener_preview; m.generation += 1; - m.shot = Some(Shot { doc, doc_index, revision, options, overprints, report, fit, generation: m.generation }); + m.shot = Some(Shot { doc, doc_uid, revision, options, overprints, report, fit, generation: m.generation }); m.view = fitting_view(); Ok(out) } @@ -176,7 +177,7 @@ fn merged(base: &FlattenOptions, over: &Value) -> Value { fn stale(app: &VectorcraftApp) -> bool { let (Some(st), Some(s)) = (app.session.active(), app.flattener_preview.shot.as_ref()) else { return false }; let set = &app.ui.flattener_preview; - s.revision != st.revision || s.options != set.options || s.overprints != set.overprints + s.doc_uid != st.uid || s.revision != st.revision || s.options != set.options || s.overprints != set.overprints } /// Whether the options are no preset's: the preset field then reads `[Custom]`. @@ -191,9 +192,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { super::empty_state(ui, "eye", tl!("No document"), tl!("Open a document to preview its flattening.")); return; } - let index = app.session.active_index().unwrap_or(0); + let uid = app.session.active().map(|st| st.uid); // A document the panel hasn't seen yet gets a snapshot right away. - if app.flattener_preview.shot.as_ref().map(|s| s.doc_index) != Some(index) + if app.flattener_preview.shot.as_ref().map(|s| s.doc_uid) != uid && let Err(e) = refresh(app) { app.status(e); @@ -455,6 +456,37 @@ mod tests { ctx } + #[test] + fn another_drawing_at_the_same_index_and_revision_gets_its_own_preview() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let make_drawing = |app: &mut VectorcraftApp, x| { + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10})).unwrap(); + }; + make_drawing(&mut app, 10); + frame(&mut app); + let first = app.session.active().unwrap(); + let (uid, revision, index) = (first.uid, first.revision, app.session.active_index()); + let old_generation = app.flattener_preview.generation; + let old_art = first.doc.clone(); + + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + frame(&mut app); + make_drawing(&mut app, 70); + let second = app.session.active().unwrap(); + assert_ne!(second.uid, uid); + assert_eq!(second.revision, revision); + assert_eq!(app.session.active_index(), index); + let expected = second.doc.clone(); + assert_ne!(expected.layers, old_art.layers, "the replacement drawing has different artwork"); + + frame(&mut app); + let shot = app.flattener_preview.shot.as_ref().unwrap(); + assert!(Arc::ptr_eq(&shot.doc, &expected), "the preview snapshots the drawing now open"); + assert!(shot.generation > old_generation); + assert!(!stale(&app)); + } + #[test] fn the_panel_takes_a_snapshot_and_highlights_in_red() { let mut app = app(); From 9cfe94a9332ac99dec2a13f6430e05243588d3b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:16:34 -0800 Subject: [PATCH 080/193] Keep Gradient swatch actions aligned with the active drawing --- crates/ui-egui/src/panels/gradient.rs | 17 +++++++------- crates/ui-egui/src/panels/gradient/tests.rs | 26 ++++++++++++++++++++- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index fbe030d45a..ce32696fce 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -266,8 +266,8 @@ pub(crate) fn reset_to_linear_white_black(app: &mut VectorcraftApp) { } /// Save the gradient as a swatch; its stops keep their color models. -fn save_to_swatches(app: &mut VectorcraftApp, g: &GradientPaint) { - app.run("swatch.new", super::swatch_paint_params(&Paint::Gradient(Box::new(g.clone())))).ok(); +fn save_to_swatches(app: &mut VectorcraftApp, g: &GradientPaint) -> Result<(), String> { + app.run("swatch.new", super::swatch_paint_params(&Paint::Gradient(Box::new(g.clone())))).map(drop) } /// The document's gradient swatches (groups included): name and gradient. @@ -658,10 +658,10 @@ fn fill_box(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_grad: b } } Divider::horizontal().show(ui); - save = MenuItem::new(tl!("Save to Swatches")).enabled(is_grad).show(ui).ran; + save = MenuItem::new(tl!("Save to Swatches")).enabled(is_grad && crate::menus::enabled(app, "swatch.new")).show(ui).ran; }); - if save { - save_to_swatches(app, g); + if save && let Err(error) = save_to_swatches(app, g) { + app.status(error); } if let Some(name) = chosen { super::apply_click(app, ui, json!({ "swatch": name })); @@ -903,7 +903,7 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { let has = current(app).is_some(); let toggle = |key: &str, show: &str, hide: &str| CommandState::new().title(if part_hidden(app, key) { show } else { hide }); states.set(MENU_OPTIONS, toggle(HIDE_OPTIONS, tl!("Show Options"), tl!("Hide Options"))); - states.set(MENU_ADD_TO_SWATCHES, CommandState::new().title(tl!("Add to Swatches")).enabled(has)); + states.set(MENU_ADD_TO_SWATCHES, CommandState::new().title(tl!("Add to Swatches")).enabled(has && crate::menus::enabled(app, "swatch.new"))); states.set(MENU_REVERSE, CommandState::new().title(tl!("Reverse Gradient")).enabled(has)); states.set(MENU_RESET, CommandState::new().title(tl!("Reset to White, Black"))); states.set(MENU_PRESETS, toggle(HIDE_PRESETS, tl!("Show Presets"), tl!("Hide Presets"))); @@ -922,9 +922,8 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option set_part_hidden(app, key, hide); } MENU_ADD_TO_SWATCHES => { - if let Some(g) = current(app) { - save_to_swatches(app, &g); - } + let outcome = current(app).ok_or_else(|| tl!("No gradient to save").to_owned()).and_then(|g| save_to_swatches(app, &g)); + return Some(outcome.map(|()| Value::Null)); } MENU_REVERSE => edit(app, json!({"reverse": true}), Live::Released), MENU_RESET => set_stops(app, &Gradient::default().stops, None, Live::Released), diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 040031e59a..00c56f82a2 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -9,6 +9,30 @@ use vectorcraft_engine::Session; use super::*; use crate::tests::panel_harness::{Place, Shown, floated}; +#[test] +fn add_to_swatches_requires_a_drawing_even_when_the_default_gradient_remains() { + let enabled = |app: &VectorcraftApp| { + let mut states = CommandStates::new(); + menu_states(app, &mut states); + states.get(&CommandRef::new(MENU_ADD_TO_SWATCHES)).is_some_and(CommandState::is_enabled) + }; + let mut app = app(json!({"gradient": {}})); + app.run("select.none", json!({})).unwrap(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + assert!(enabled(&app)); + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + assert!(current(&app).is_some(), "the default gradient remains visible without a drawing"); + assert!(!enabled(&app), "there is no drawing to receive a swatch"); + assert!(app.run(MENU_ADD_TO_SWATCHES, json!({})).is_err()); + + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + assert!(enabled(&app)); + let before = app.session.active().unwrap().doc.swatches.len(); + run(&mut app, MENU_ADD_TO_SWATCHES, &json!({})).unwrap().unwrap(); + assert_eq!(app.session.active().unwrap().doc.swatches.len(), before + 1); +} + #[test] fn dropped_colours_recolour_or_add_an_opaque_stop() { let mut g = Gradient::default(); @@ -78,7 +102,7 @@ fn a_gradient_saved_as_a_swatch_keeps_its_stops_models_in_a_cmyk_document() { let g = current(&app).expect("a gradient fill"); let colors = |g: &GradientPaint| g.gradient.stops.iter().map(|s| s.color).collect::>(); assert_eq!(colors(&g), [Color::rgb8(255, 128, 0), Color::cmyk(0.0, 0.0, 0.0, 1.0)]); - save_to_swatches(&mut app, &g); + save_to_swatches(&mut app, &g).unwrap(); let Some(Paint::Gradient(saved)) = app.session.doc().unwrap().doc.swatches.last().map(|w| w.paint.clone()) else { panic!("a gradient swatch") }; assert_eq!(colors(&saved), colors(&g)); } From c53f0a91b3458275a344400a6c8c6553d7bb9932 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:06:07 -0800 Subject: [PATCH 081/193] Reproduce stale Swatches Delete approvals --- crates/ui-egui/src/panels/swatches/tests.rs | 46 +++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 596914f8a3..e86c8a03d9 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -377,6 +377,52 @@ fn delete_asks_then_removes_the_selection_and_unlinks_art() { assert_eq!(deletable(&app, &["[None]".into(), REGISTRATION.into(), "Grays".into()]), ["Grays"]); } +#[test] +fn delete_confirmation_keeps_matching_swatches_in_another_drawing() { + let mut app = app(); + let key = crate::dialogs::confirm::KIND; + let source = app.session.active().unwrap().uid; + delete(&mut app, vec!["Red".into()], false); + assert!(dialog_open(&app, key)); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + assert_ne!(app.session.active().unwrap().uid, source); + let undo = app.session.active().unwrap().history.undo.len(); + assert!(doc(&app).swatch("Red").is_some()); + + confirm(&mut app, key); + assert!(doc(&app).swatch("Red").is_some(), "the other tab keeps its identically named swatch"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(app.session.set_active(0)); + assert!(doc(&app).swatch("Red").is_some(), "the source swatch still needs a fresh confirmation"); +} + +#[test] +fn delete_confirmation_keeps_the_swatch_restored_by_revert() { + let mut app = app(); + let key = crate::dialogs::confirm::KIND; + let file = std::env::temp_dir().join(format!("vectorcraft-swatch-delete-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 saved_color = doc(&app).swatch("Red").unwrap().paint.color(); + let st = app.session.active().unwrap(); + let (uid, reverts) = (st.uid, st.reverts); + + app.run("swatch.edit", json!({"name": "Red", "color": "#00ff00"})).unwrap(); + assert_ne!(doc(&app).swatch("Red").unwrap().paint.color(), saved_color); + delete(&mut app, vec!["Red".into()], false); + 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(&app).swatch("Red").unwrap().paint.color(), saved_color); + let undo = st.history.undo.len(); + + confirm(&mut app, key); + assert_eq!(doc(&app).swatch("Red").expect("the restored swatch stays").paint.color(), saved_color); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); +} + /// Only None and Registration are reserved: a user swatch or color group whose name starts with /// `[` can be deleted, the swatch can be edited, and names the document does not hold are left out. #[test] From 5492a5e50082b3dc1aad4ff58508c78f57eace98 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:06:08 -0800 Subject: [PATCH 082/193] Reproduce stale Graphic Styles Delete approvals --- crates/ui-egui/src/panels/graphic_styles.rs | 50 +++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 1d089378d3..241d545789 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -1150,6 +1150,56 @@ mod tests { assert!(names(&app).is_empty() && confirm::open_question(&app).is_none()); } + #[test] + fn delete_confirmation_keeps_matching_styles_in_another_drawing() { + let mut app = app(); + app.run("graphicStyle.new", json!({"name": "Mine"})).unwrap(); + let source = app.session.active().unwrap().uid; + on_event(&mut app, PresetEvent::Delete("Mine".into()), false); + assert!(asks_delete(&app)); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + assert_ne!(app.session.active().unwrap().uid, source); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 25})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Mine"})).unwrap(); + let before = names(&app); + let undo = app.session.active().unwrap().history.undo.len(); + + answer_dialog(&mut app, dialog_id(confirm::KIND), &[], true); + assert_eq!(names(&app), before, "the other tab keeps its identically named style"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(app.session.set_active(0)); + assert!(doc(&app).graphic_style_index("Mine").is_some(), "the source style still needs a fresh confirmation"); + } + + #[test] + fn delete_confirmation_keeps_the_style_restored_by_revert() { + let mut app = app(); + app.run("graphicStyle.new", json!({"name": "Mine"})).unwrap(); + let file = std::env::temp_dir().join(format!("vectorcraft-style-delete-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 saved = doc(&app); + let index = saved.graphic_style_index("Mine").unwrap(); + let st = app.session.active().unwrap(); + let (uid, reverts) = (st.uid, st.reverts); + + app.run("paint.setFill", json!({"color": "#b32f5f"})).unwrap(); + app.run("graphicStyle.redefine", json!({"name": "Mine"})).unwrap(); + on_event(&mut app, PresetEvent::Delete("Mine".into()), false); + assert!(asks_delete(&app)); + 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(&app).graphic_style_index("Mine"), Some(index)); + let undo = st.history.undo.len(); + + answer_dialog(&mut app, dialog_id(confirm::KIND), &[], true); + assert_eq!(doc(&app).graphic_style_index("Mine"), Some(index), "the restored style stays"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + #[test] fn thumbnails_are_versioned_by_look_and_change_when_a_style_changes() { let mut app = app(); From 32cd38351dda0b7853ef8d676e9d45d9db65b441 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:19:20 -0800 Subject: [PATCH 083/193] Keep Swatches and Graphic Styles Delete approvals on the opening drawing --- crates/ui-egui/src/dialogs/confirm.rs | 29 +++++++++++++++---- crates/ui-egui/src/panels/graphic_styles.rs | 10 ++++++- crates/ui-egui/src/panels/swatches/actions.rs | 8 ++++- crates/ui-egui/src/panels/swatches/tests.rs | 2 ++ 4 files changed, 42 insertions(+), 7 deletions(-) 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/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 241d545789..62a5bc68d4 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -780,7 +780,13 @@ fn delete(app: &mut VectorcraftApp, names: &[String], now: bool) { [n] => crate::i18n::fmt(tl!("Delete the graphic style “{name}”?"), &[("name", n)]), _ => crate::i18n::tn(names.len() as u64, "Delete this {n} graphic style?", "Delete these {n} graphic styles?"), }; - crate::dialogs::confirm::ask(app, &message, tl!("Objects using them keep their look but are no longer linked."), "graphicStyle.delete", params); + crate::dialogs::confirm::ask_in_document_contents( + app, + &message, + tl!("Objects using them keep their look but are no longer linked."), + "graphicStyle.delete", + params, + ); } // ---------- the panel menu ---------- @@ -1167,6 +1173,7 @@ mod tests { answer_dialog(&mut app, dialog_id(confirm::KIND), &[], true); assert_eq!(names(&app), before, "the other tab keeps its identically named style"); assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "This dialog was opened in a different document."); assert!(app.session.set_active(0)); assert!(doc(&app).graphic_style_index("Mine").is_some(), "the source style still needs a fresh confirmation"); } @@ -1198,6 +1205,7 @@ mod tests { answer_dialog(&mut app, dialog_id(confirm::KIND), &[], true); assert_eq!(doc(&app).graphic_style_index("Mine"), Some(index), "the restored style stays"); assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue."); } #[test] diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index b865cf2130..13d912b40c 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -62,7 +62,13 @@ pub(super) fn delete(app: &mut VectorcraftApp, names: Vec, now: bool) { [n] => crate::i18n::fmt(tl!("Delete “{name}”?"), &[("name", n)]), _ => crate::i18n::tn(names.len() as u64, "Delete this {n} swatch or group?", "Delete these {n} swatches and groups?"), }; - crate::dialogs::confirm::ask(app, &message, tl!("Art using a deleted global swatch keeps its colour."), "swatch.delete", params); + crate::dialogs::confirm::ask_in_document_contents( + app, + &message, + tl!("Art using a deleted global swatch keeps its colour."), + "swatch.delete", + params, + ); } /// Duplicates the swatches `names` (`swatch.duplicate`, each copy just after its swatch and in its diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index e86c8a03d9..28ae03a07b 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -392,6 +392,7 @@ fn delete_confirmation_keeps_matching_swatches_in_another_drawing() { confirm(&mut app, key); assert!(doc(&app).swatch("Red").is_some(), "the other tab keeps its identically named swatch"); assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "This dialog was opened in a different document."); assert!(app.session.set_active(0)); assert!(doc(&app).swatch("Red").is_some(), "the source swatch still needs a fresh confirmation"); } @@ -421,6 +422,7 @@ fn delete_confirmation_keeps_the_swatch_restored_by_revert() { confirm(&mut app, key); assert_eq!(doc(&app).swatch("Red").expect("the restored swatch stays").paint.color(), saved_color); assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue."); } /// Only None and Registration are reserved: a user swatch or color group whose name starts with From ace53d3c35262a98ea2aba4061516531a1cfca51 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:21:29 -0800 Subject: [PATCH 084/193] Retire Convert to Indexed Color after Revert --- crates/ui-egui/src/dialogs/indexed_color.rs | 53 ++++++++++++++++++--- 1 file changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/indexed_color.rs b/crates/ui-egui/src/dialogs/indexed_color.rs index b823cd2e71..1f1523fdf6 100644 --- a/crates/ui-egui/src/dialogs/indexed_color.rs +++ b/crates/ui-egui/src/dialogs/indexed_color.rs @@ -25,13 +25,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) { @@ -86,7 +95,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 +107,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 +130,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()); } @@ -265,4 +272,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); + } } From 0042d4b5134b447ae63950a2079789f9f4cfbedf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:21:30 -0800 Subject: [PATCH 085/193] Retire open color adjustments after Revert --- crates/ui-egui/src/dialogs/color_balance.rs | 54 +++++++++++++++++---- 1 file changed, 44 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index 76a5e62ad0..ef5192b032 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); @@ -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"); From c1a23c4185ac39b8d0eb815690d12979b65f8e09 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:23:41 -0800 Subject: [PATCH 086/193] Track each paint affected by Gradient Stop edits --- crates/engine/src/cmd/gradient.rs | 30 +++++++++++++ crates/ui-egui/src/dialogs/gradient_stop.rs | 49 ++++++++++++++++++--- 2 files changed, 72 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index da5bbea659..5a36915747 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -136,6 +136,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, Vec)>> { + const CMD: &str = "paint.editGradient"; + let p = json!({ "stroke": stroke }); + if super::paint::for_tool(self, &p, stroke) { + return Ok(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((id, item, paints)); + } + Ok(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/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 622a5ba407..272c7bd238 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -101,12 +101,19 @@ impl TargetKey { #[derive(Clone)] struct TargetOwner { key: TargetKey, - paint: Arc, + paints: Arc, +} + +struct TargetPaints { + shown: GradientPaint, + edited: Vec<(NodeId, Option, Vec)>, } impl TargetOwner { fn matches(&self, app: &VectorcraftApp, target: &Target) -> bool { - self.key.matches(app, target) && self.paint.as_ref() == target.paint() + self.key.matches(app, target) + && self.paints.shown == *target.paint() + && app.session.gradient_edit_paints(!self.key.fill).is_ok_and(|paints| paints == self.paints.edited) } } @@ -464,8 +471,10 @@ pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) { } 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 }); dialogs.with(|host| { - host.open(GradientStopPopover::new(anchor, TargetOwner { key, paint: Arc::new(target.paint().clone()) })); + host.open(GradientStopPopover::new(anchor, TargetOwner { key, paints })); }); refresh(app, &ctx, dialog_id(KIND), &target); } @@ -520,13 +529,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { crate::panels::gradient::stop_eyedropper(app); return; } - let Some(target) = selected(app).filter(|target| owner.key.matches(app, target)) else { + 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 owns the edits applied in this pass and can continue with their resulting paint. - if owner.paint.as_ref() != target.paint() { - owner.paint = Arc::new(target.paint().clone()); + // The popover can continue with the paints resulting from its own edits in this pass. + if owner.paints.shown != *target.paint() || owner.paints.edited != edited { + owner.paints = Arc::new(TargetPaints { shown: target.paint().clone(), edited }); } dialogs.with(|host| { if let Some(popover) = host.get_mut_by_id::(id) { @@ -750,6 +760,31 @@ mod tests { assert!(!is_open(&app)); } + #[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(); From 4e7d8bc9dd536f901b40778714f44581e8410b96 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:27:38 -0800 Subject: [PATCH 087/193] Reproduce stale Delete Symbol approvals after File Revert --- crates/ui-egui/src/panels/symbols/tests.rs | 48 ++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/crates/ui-egui/src/panels/symbols/tests.rs b/crates/ui-egui/src/panels/symbols/tests.rs index 3f52c73fc8..a0bf50d8dc 100644 --- a/crates/ui-egui/src/panels/symbols/tests.rs +++ b/crates/ui-egui/src/panels/symbols/tests.rs @@ -1438,6 +1438,54 @@ fn a_stale_delete_symbol_question_deletes_nothing() { assert_eq!(art(&app, "Dot"), (1, 0)); } +fn refuses_symbol_approval_after_revert(name: &str, choice: PromptChoice, after_fresh_approval: (usize, usize)) { + let mut app = windowed(leaf_and_dot()); + let file = std::env::temp_dir().join(format!("vectorcraft-symbol-delete-{name}-{choice:?}-{}.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 leaf = instance_of(&app, "Leaf").unwrap(); + let st = app.session.active().unwrap(); + let (uid, reverts) = (st.uid, st.reverts); + + app.run("symbol.place", json!({"name": "Leaf"})).unwrap(); + assert_eq!(art(&app, "Leaf"), (2, 0)); + symbol_delete::ask(&mut app, name, false); + assert_eq!(delete_question(&app), Some(name == "Leaf")); + 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!(instance_of(&app, "Leaf"), Some(leaf)); + assert_eq!(art(&app, "Leaf"), (1, 0)); + let undo = st.history.undo.len(); + + choose(&mut app, choice); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "an old approval keeps the restored symbols"); + assert_eq!(art(&app, "Leaf"), (1, 0), "the restored instance stays unmodified"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + + symbol_delete::ask(&mut app, name, false); + choose(&mut app, choice); + assert!(!symbols(&mut app).iter().any(|symbol| symbol == name)); + assert_eq!(art(&app, "Leaf"), after_fresh_approval); +} + +#[test] +fn old_delete_symbol_yes_keeps_the_symbol_restored_by_revert() { + refuses_symbol_approval_after_revert("Dot", PromptChoice::Proceed, (1, 0)); +} + +#[test] +fn old_expand_instances_keeps_the_instance_restored_by_revert() { + refuses_symbol_approval_after_revert("Leaf", PromptChoice::Proceed, (0, 1)); +} + +#[test] +fn old_delete_instances_keeps_the_instance_restored_by_revert() { + refuses_symbol_approval_after_revert("Leaf", PromptChoice::Alternate, (0, 0)); +} + /// The panel menu's Reset Transformation and the Control bar's Reset are enabled only while a /// selected instance's scale, rotation or shear differs from its symbol's, and give the /// instance its symbol's again. From 4fd139e5af318b5db992df9439bb974a89dbe0be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:28:50 -0800 Subject: [PATCH 088/193] Keep pending Delete Symbol approvals off reverted contents --- crates/ui-egui/src/dialogs/symbol_delete.rs | 37 +++++++++++++-------- crates/ui-egui/src/panels/symbols/tests.rs | 1 + 2 files changed, 24 insertions(+), 14 deletions(-) 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/panels/symbols/tests.rs b/crates/ui-egui/src/panels/symbols/tests.rs index a0bf50d8dc..9c16d0b761 100644 --- a/crates/ui-egui/src/panels/symbols/tests.rs +++ b/crates/ui-egui/src/panels/symbols/tests.rs @@ -1464,6 +1464,7 @@ fn refuses_symbol_approval_after_revert(name: &str, choice: PromptChoice, after_ assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "an old approval keeps the restored symbols"); assert_eq!(art(&app, "Leaf"), (1, 0), "the restored instance stays unmodified"); assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue."); symbol_delete::ask(&mut app, name, false); choose(&mut app, choice); From 906a5446ff9c8f7641c397579a2a9bab6f3d18e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:33:58 -0800 Subject: [PATCH 089/193] Retire Export for Screens approvals after Revert --- .../ui-egui/src/dialogs/export_for_screens.rs | 29 ++++--- crates/ui-egui/src/dialogs/tests_screens.rs | 80 +++++++++++++++++++ 2 files changed, 96 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 0211830949..87065d927d 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -506,7 +506,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) } @@ -515,6 +515,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, } @@ -535,9 +537,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>, } @@ -620,13 +622,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" }); @@ -994,15 +996,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; }; @@ -1024,15 +1027,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/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index af68809f46..3dbc086f6a 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -67,6 +67,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}; @@ -1448,6 +1504,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] From c3576a71430cfb5ae17a3eb96acfaf3828237060 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:00:01 -0800 Subject: [PATCH 090/193] Keep format-specific save and export options in their source drawing --- crates/ui-egui/src/dialogs/export_host.rs | 37 ++++++++++++++++++---- crates/ui-egui/src/dialogs/tests_export.rs | 22 +++++++++++++ 2 files changed, 52 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/export_host.rs b/crates/ui-egui/src/dialogs/export_host.rs index fb68f64c51..217a8ff8c7 100644 --- a/crates/ui-egui/src/dialogs/export_host.rs +++ b/crates/ui-egui/src/dialogs/export_host.rs @@ -64,6 +64,8 @@ pub(crate) enum Export { pub(crate) struct Open { /// The hosted dialog's id. pub id: DialogId, + /// The drawing whose options and output this dialog controls. + document: Option, /// Which dialog it is. pub kind: Export, /// Whether Export Selection opened it: OK then writes the selection alone. @@ -88,6 +90,15 @@ impl ExportDialogs { } } +impl Open { + fn check_source(&self, app: &VectorcraftApp) -> Result<(), String> { + if !matches!(self.kind, Export::Hpgl { .. }) && self.document != app.session.active().map(|doc| doc.uid) { + return Err(tl!("Return to the original drawing to export it").into()); + } + Ok(()) + } +} + /// `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 +107,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 { document } | Export::Hpgl { doc: document } => Some(*document), + Export::EpsCustom { parent } => app.export_dialogs.find(*parent)?.document, + _ => app.session.active().map(|doc| doc.uid), + }; 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 +133,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; @@ -197,14 +214,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/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index 7ab85da4ae..faa04153ea 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). From 96fd81c16c7a2a280ef209b3b0f94d13da6c544a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:29:23 -0800 Subject: [PATCH 091/193] Forget the previous text match after Revert --- crates/ui-egui/src/dialogs/find_replace.rs | 32 +++++++------- .../ui-egui/src/dialogs/find_replace/tests.rs | 42 +++++++++++++++++++ 2 files changed, 60 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs index 61bba50596..cffc3ab7e3 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,13 @@ 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 same_drawing(last: &Map, (uid, reverts): (u64, u64)) -> bool { + last.get("doc").and_then(Value::as_array).is_some_and(|doc| doc.len() == 2 && doc[0].as_u64() == Some(uid) && doc[1].as_u64() == Some(reverts)) } /// The match found belongs to an open dialog: the last search keeps its place, not the match. @@ -127,12 +130,13 @@ 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 current = drawing.is_some_and(|d| same_drawing(o, d)); 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("doc"); + if !current { o.remove("from"); } } @@ -143,7 +147,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 +182,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 +208,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..b4aac82b75 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] From cc7654aa53b9b20a4795f7b6fa0e82b1b64f2abf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:33:51 -0800 Subject: [PATCH 092/193] Keep file format options attached to their original drawing --- crates/ui-egui/src/dialogs/export_host.rs | 7 ++++--- .../ui-egui/src/dialogs/save_options/tests.rs | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/export_host.rs b/crates/ui-egui/src/dialogs/export_host.rs index 217a8ff8c7..2b068a8a7d 100644 --- a/crates/ui-egui/src/dialogs/export_host.rs +++ b/crates/ui-egui/src/dialogs/export_host.rs @@ -92,8 +92,8 @@ impl ExportDialogs { impl Open { fn check_source(&self, app: &VectorcraftApp) -> Result<(), String> { - if !matches!(self.kind, Export::Hpgl { .. }) && self.document != app.session.active().map(|doc| doc.uid) { - return Err(tl!("Return to the original drawing to export it").into()); + if !matches!(self.kind, Export::As { .. } | Export::Hpgl { .. }) && self.document != app.session.active().map(|doc| doc.uid) { + return Err(tl!("Return to the original drawing to continue").into()); } Ok(()) } @@ -108,7 +108,8 @@ pub(super) fn options>(ids: &[&'static str], labels: &[&'s /// 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 { document } | Export::Hpgl { doc: document } => Some(*document), + Export::As { document } => *document, + Export::Hpgl { doc } => Some(*doc), Export::EpsCustom { parent } => app.export_dialogs.find(*parent)?.document, _ => app.session.active().map(|doc| doc.uid), }; diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index 200b91f458..bc181aab23 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. From 89323603d9e8d1abb38c5c564b8d248188e8f48a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:37:07 -0800 Subject: [PATCH 093/193] Preserve SVG Filter encoding from browser files --- crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/svgfilter.rs | 20 +++++++++++------ crates/engine/src/tests/svgfilter.rs | 28 ++++++++++++++++++++++++ crates/ui-egui/src/dialogs/svg_filter.rs | 24 +++++++++++++++++++- 4 files changed, 65 insertions(+), 8 deletions(-) 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/svgfilter.rs b/crates/engine/src/cmd/svgfilter.rs index 43af8bce35..40e5926f48 100644 --- a/crates/engine/src/cmd/svgfilter.rs +++ b/crates/engine/src/cmd/svgfilter.rs @@ -17,7 +17,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 +53,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 +197,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`. +/// The bytes of `p`'s `path`, `svg` text or `dataBase64`, up to [`MAX_IMPORT_BYTES`]. fn import_bytes(p: &Value, cmd: &str) -> Result> { - let bytes = match (text_param(p, "path", cmd)?, text_param(p, "svg", cmd)?) { + 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), _, _) => read_file_head(&absolute_path(path), MAX_IMPORT_BYTES + 1)?, + (None, Some(svg), _) => svg.as_bytes().to_vec(), + (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"))); + } + vectorcraft_format::base64_decode(encoded).ok_or_else(|| bad(cmd, "bad dataBase64"))? + } + _ => return Err(bad(cmd, "give `path`, an SVG file, `svg`, SVG text, or `dataBase64`, file bytes")), }; if bytes.len() > MAX_IMPORT_BYTES { return Err(bad(cmd, format!("the SVG file is larger than {MAX_IMPORT_BYTES} bytes"))); diff --git a/crates/engine/src/tests/svgfilter.rs b/crates/engine/src/tests/svgfilter.rs index 611c9bfd1f..c668366ef9 100644 --- a/crates/engine/src/tests/svgfilter.rs +++ b/crates/engine/src/tests/svgfilter.rs @@ -34,6 +34,34 @@ 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")); + for bytes in [vec![0xff], vec![b' '; (16 << 20) + 1], vectorcraft_svg::compress("")] { + assert!(s.execute("svgFilter.import", &json!({"dataBase64": vectorcraft_format::base64_encode(&bytes)})).is_err()); + assert!(names(&mut s).is_empty()); + assert_eq!(steps(&s), 0); + } +} + #[test] fn filters_are_defined_edited_and_deleted_in_one_undo_step_each() { let mut s = session(); diff --git a/crates/ui-egui/src/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(); From e872b91c009e426e54bf084773c4861f65a88f00 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:37:18 -0800 Subject: [PATCH 094/193] Reproduce stale Kinsoku Shori approval after File Revert --- .../ui-egui/src/dialogs/kinsoku_sets/tests.rs | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs index 887dbbc202..c026cf4c3b 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs @@ -226,6 +226,46 @@ 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)); + cancel(&mut 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. From c0da24c63aed77f3e45314081527a26153e1a364 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:38:27 -0800 Subject: [PATCH 095/193] Name the gradient edit paint snapshot --- crates/engine/src/cmd/gradient.rs | 19 +++++++++++++++---- crates/engine/src/lib.rs | 2 +- crates/ui-egui/src/dialogs/gradient_stop.rs | 3 ++- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 5a36915747..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 @@ -139,11 +150,11 @@ impl Session { /// 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, Vec)>> { + 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(Vec::new()); + return Ok(GradientEditPaints(Vec::new())); } let doc = &self.doc()?.doc; let item = item_target(self, &p, CMD)?.of_kind(self, !stroke); @@ -161,9 +172,9 @@ impl Session { 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((id, item, paints)); + out.push(EditedPaint { id, item, paints }); } - Ok(out) + Ok(GradientEditPaints(out)) } /// The selected gradient stop (`gradient.selectStop`), while the gradient it was selected on 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/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 272c7bd238..f2bf968f04 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -34,6 +34,7 @@ use serde_json::{Value, json}; use vectorcraft_color::gradient::move_stop; 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; @@ -106,7 +107,7 @@ struct TargetOwner { struct TargetPaints { shown: GradientPaint, - edited: Vec<(NodeId, Option, Vec)>, + edited: GradientEditPaints, } impl TargetOwner { From 4ede44168a50bc4c59cb35f42db60175d6b9055d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:41:05 -0800 Subject: [PATCH 096/193] Reject a Symbolism draft after Undo reuses its symbol set ID --- .../ui-egui/src/dialogs/symbolism_options.rs | 41 +++++++++++++++---- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index f60181ea8a..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::{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}; @@ -120,7 +123,7 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { struct DensityTarget { value: Option, document: Option<(u64, u64)>, - sets: Vec, + sets: Vec<(NodeId, Weak)>, } fn density_id() -> egui::Id { @@ -144,10 +147,9 @@ impl DensityTarget { let editable = doc.doc.editable(); self.sets .iter() - .copied() - .filter(|id| { - let id = vectorcraft_doc::NodeId(*id); - doc.doc.node(id).is_some_and(vectorcraft_engine::cmd::is_symbol_set) && editable(id) + .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() }; @@ -158,15 +160,18 @@ impl DensityTarget { } } -/// The selected symbol sets that can be edited (a locked or hidden one keeps its density). -fn selected_sets(app: &VectorcraftApp) -> Vec { +/// 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() } @@ -275,6 +280,24 @@ mod tests { 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(); From 456ecd0bfd809674440f35514d26298f6276d61e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:41:05 -0800 Subject: [PATCH 097/193] Require a drawing for New Swatch in the Color panel --- crates/ui-egui/src/panels/color.rs | 15 +++++++------ crates/ui-egui/src/panels/color/tests.rs | 27 +++++++++++++++++++++++- 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index 441200b9ee..034ae7933a 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -579,7 +579,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } /// Carry out what the panel menu asked of the app. -fn carry_out(app: &mut VectorcraftApp, tgt: &Target, action: ColorPanelAction) { +fn carry_out(app: &mut VectorcraftApp, tgt: &Target, action: ColorPanelAction) -> Result<(), String> { match action { ColorPanelAction::Mode(m) => set_mode(app, tgt, m), ColorPanelAction::Copy(text) => { @@ -590,17 +590,21 @@ fn carry_out(app: &mut VectorcraftApp, tgt: &Target, action: ColorPanelAction) { ColorPanelAction::Invert => recolor(app, tgt, true, false), ColorPanelAction::Complement => recolor(app, tgt, false, false), ColorPanelAction::NewSwatch => { + if app.session.active().is_none() { + return Err(tl!("No document").into()); + } if let Some(c) = tgt.color() { // A tint saves a tint swatch ("Name 40%"); a color keeps its model. let p = match tgt.tint() { Some(t) => json!({"swatch": t.swatch, "tint": t.tint * 100.0}), None => json!({"color": color_json(&c), "keepModel": true}), }; - app.run("swatch.new", p).ok(); + app.run("swatch.new", p)?; } } _ => {} } + Ok(()) } /// The panel menu: Hide Options and Show Recent Colors, the five modes, Invert, Complement, Create @@ -615,6 +619,7 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { let tgt = target_now(app); let has_color = tgt.color().is_some() || mixed_now(app); for (command, state) in ColorPanelMenu::states(LAYOUT, &app.ui.color_panel, &shown(app, &tgt), has_color) { + let state = if command == ColorPanelCommand::NewSwatch && !crate::menus::enabled(app, "swatch.new") { state.enabled(false) } else { state }; states.set(command, state); } } @@ -624,10 +629,8 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option let command = ColorPanelCommand::from_ref(&CommandRef::new(id))?; let tgt = target_now(app); let edited = srgba(&tgt.color().unwrap_or(Color::BLACK)); - if let Some(action) = ColorPanelMenu::run_command(&mut app.ui.color_panel, command, edited) { - carry_out(app, &tgt, action); - } - Some(Ok(Value::Null)) + let outcome = ColorPanelMenu::run_command(&mut app.ui.color_panel, command, edited).map_or(Ok(()), |action| carry_out(app, &tgt, action)); + Some(outcome.map(|()| Value::Null)) } #[cfg(test)] diff --git a/crates/ui-egui/src/panels/color/tests.rs b/crates/ui-egui/src/panels/color/tests.rs index e63fc09e7a..d354702ef2 100644 --- a/crates/ui-egui/src/panels/color/tests.rs +++ b/crates/ui-egui/src/panels/color/tests.rs @@ -1,6 +1,31 @@ use super::*; use vectorcraft_engine::Session; +#[test] +fn create_new_swatch_requires_a_drawing_but_copy_color_remains_available() { + let enabled = |app: &VectorcraftApp, command| { + let mut states = CommandStates::new(); + menu_states(app, &mut states); + states.get(&CommandRef::from(command)).is_some_and(|state| state.is_enabled()) + }; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let new_swatch = CommandRef::from(ColorPanelCommand::NewSwatch).id; + for _ in 0..2 { + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.session.fill_active = true; + app.run("paint.setFill", json!({"color": "#336699"})).unwrap(); + assert!(enabled(&app, ColorPanelCommand::NewSwatch)); + assert!(enabled(&app, ColorPanelCommand::CopyHex)); + let before = app.session.active().unwrap().doc.swatches.len(); + app.run(&new_swatch, json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.swatches.len(), before + 1); + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + assert!(enabled(&app, ColorPanelCommand::CopyHex)); + assert!(!enabled(&app, ColorPanelCommand::NewSwatch)); + assert!(app.run(&new_swatch, json!({})).is_err()); + } +} + fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); @@ -70,7 +95,7 @@ fn create_new_swatch_keeps_the_shown_colors_model_in_a_cmyk_document() { assert_eq!(shown.model(), model, "{fill}"); let count = app.session.doc().unwrap().doc.swatches.len(); let tgt = target_now(&app); - carry_out(&mut app, &tgt, ColorPanelAction::NewSwatch); + carry_out(&mut app, &tgt, ColorPanelAction::NewSwatch).unwrap(); assert_eq!(app.session.doc().unwrap().doc.swatches.len(), count + 1, "{fill}: one new swatch"); let w = newest(&app); assert_eq!(w.paint.color(), Some(shown), "{fill}: the swatch has the shown color, {}", w.name); From a0873ba727f6b09990976a0a833967f50a3b9585 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:41:05 -0800 Subject: [PATCH 098/193] Retire File Info drafts after Revert --- crates/ui-egui/src/dialogs/file_info.rs | 52 +++++++++++++++++++++---- 1 file changed, 45 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index 80439178a8..6a5afd2664 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(|_| ()) }; @@ -232,7 +234,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 +250,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 +392,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; @@ -652,6 +654,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 { From d2f726ecee1f3d84624295aa5cfaed77428df088 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:41:32 -0800 Subject: [PATCH 099/193] Use existing translations in Adjust Color Balance --- crates/ui-egui/src/dialogs/color_balance.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index 76a5e62ad0..b1b23618f4 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -157,7 +157,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 +214,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)), ] } From d6c14e36612333f122496bb179d3d3796fa9169e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:35:19 -0800 Subject: [PATCH 100/193] Exercise Graph Data after File Revert --- crates/ui-egui/src/dialogs/graph_data.rs | 56 ++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 9cf40d3319..ae58ce2ad6 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -922,6 +922,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 { From ab935736c07df97304f8d69d6327543bed836ca2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:48:24 -0800 Subject: [PATCH 101/193] Disable Color Guide save actions without a drawing --- crates/ui-egui/src/panels.rs | 3 +- crates/ui-egui/src/panels/color_guide.rs | 77 +++++++++++++++++++++--- 2 files changed, 68 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index fe36fca6df..1429c8bc0e 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -530,8 +530,7 @@ static PANEL_MENUS: &[PanelMenuSource] = &[ }, run: |app, id, _| { let command = HarmonyCommand::from_ref(&CommandRef::new(id))?; - color_guide::run(app, command); - Some(Ok(Value::Null)) + Some(color_guide::run(app, command).map(|()| Value::Null)) }, }, menu!("stroke", stroke), diff --git a/crates/ui-egui/src/panels/color_guide.rs b/crates/ui-egui/src/panels/color_guide.rs index 07569242ce..dbcab35cc5 100644 --- a/crates/ui-egui/src/panels/color_guide.rs +++ b/crates/ui-egui/src/panels/color_guide.rs @@ -629,12 +629,13 @@ fn picked(app: &VectorcraftApp) -> Vec<(usize, usize)> { /// Save `cells`' colors as swatches (one undo step), each in its own model; a tint of a spot color /// base becomes a tint swatch of it. -fn save_selected(app: &mut VectorcraftApp, cells: &[(usize, usize)]) { +fn save_selected(app: &mut VectorcraftApp, cells: &[(usize, usize)]) -> Result<(), String> { let g = guide(app); let colors = cell_entries(app, &g, cells); if !colors.is_empty() { - app.run("swatch.new", json!({ "colors": colors, "keepModel": true })).ok(); + app.run("swatch.new", json!({ "colors": colors, "keepModel": true }))?; } + Ok(()) } /// Save Color Group to Swatches: `cells` as one swatch group in the order given; with none, the @@ -714,6 +715,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let limit = model.palette.as_ref().map(|l| l.shown.as_slice()).filter(|s| !s.is_empty()); let has_cells = !model.picked.cells().is_empty(); let doc = app.session.active().is_some(); + let can_save_swatches = crate::menus::enabled(app, "swatch.new"); + let can_save_group = crate::menus::enabled(app, "swatch.newGroup"); let (tip, limited) = limit_tip(app); let shared: &VectorcraftApp = app; let (mut cell, mut base_clicked, mut footer_picked, mut limit_picked) = (None, false, None, None); @@ -723,8 +726,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .footer(|ui, _| { let actions = [ FooterAction::new(icon("library"), tip.clone()).pressed(limited).popup(PopupKind::Menu), - FooterAction::new(icon("dc-folder"), tl!("Save color group to Swatch panel").to_string()), - FooterAction::new(icon("dc-new-item"), tl!("Save selected colors as swatches").to_string()).enabled(has_cells), + FooterAction::new(icon("dc-folder"), tl!("Save color group to Swatch panel").to_string()).enabled(can_save_group), + FooterAction::new(icon("dc-new-item"), tl!("Save selected colors as swatches").to_string()).enabled(has_cells && can_save_swatches), FooterAction::new(icon("palette"), tl!("Edit or Apply Colors").to_string()).enabled(doc), ]; let out = FooterBar::actions(actions).at_start(LIMIT + 1).show_footer(ui); @@ -766,7 +769,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let cells = picked(app); match footer_picked { Some(EDIT) => edit_or_apply(app), - Some(SAVE_SELECTED) => save_selected(app, &cells), + Some(SAVE_SELECTED) => { + if let Err(error) = save_selected(app, &cells) { + app.status(error); + } + } Some(SAVE_GROUP) => save_group(app, &cells), _ => {} } @@ -780,10 +787,20 @@ pub(crate) fn menu_rows() -> Vec { /// The state of each menu command. pub(crate) fn menu_states(app: &VectorcraftApp) -> Vec<(HarmonyCommand, CommandState)> { HarmonyMenu::states(&panel_state(app.ui.color_guide_panel.rule, app.ui.color_guide), &app.ui.color_guide_panel.picked) + .into_iter() + .map(|(command, state)| { + let state = + if command == HarmonyCommand::SaveAsSwatches && !crate::menus::enabled(app, "swatch.new") { state.enabled(false) } else { state }; + (command, state) + }) + .collect() } /// Carry out menu command `command`. -pub(crate) fn run(app: &mut VectorcraftApp, command: HarmonyCommand) { +pub(crate) fn run(app: &mut VectorcraftApp, command: HarmonyCommand) -> Result<(), String> { + if command == HarmonyCommand::SaveAsSwatches && app.session.active().is_none() { + return Err(tl!("No document").into()); + } let mut state = panel_state(app.ui.color_guide_panel.rule, app.ui.color_guide); let action = HarmonyMenu::run_command(&mut state, &app.ui.color_guide_panel.picked, command); app.ui.color_guide = state.options; @@ -792,13 +809,14 @@ pub(crate) fn run(app: &mut VectorcraftApp, command: HarmonyCommand) { // keeps its model and a spot tint stays a tint swatch. Some(HarmonyMenuAction::SaveAsSwatches(_)) => { let cells = picked(app); - save_selected(app, &cells); + save_selected(app, &cells)?; } Some(HarmonyMenuAction::Options) => { app.run("ui.colorGuideOptions", json!({})).ok(); } _ => {} } + Ok(()) } #[cfg(test)] @@ -817,6 +835,45 @@ mod tests { out.textures_delta.clear(); } + #[test] + fn save_actions_follow_the_drawing_when_it_closes_and_reopens() { + use crate::tests::panel_harness::Panel; + + let app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + let mut panel = Panel::new(app, show); + panel.room(egui::vec2(360.0, 900.0)).frame(); + let group = "Save color group to Swatch panel"; + let selected = "Save selected colors as swatches"; + let menu_enabled = |app: &VectorcraftApp| { + menu_states(app).into_iter().find(|(command, _)| *command == HarmonyCommand::SaveAsSwatches).unwrap().1.is_enabled() + }; + let save_as_swatches = craft::keymap::CommandRef::from(HarmonyCommand::SaveAsSwatches).id; + assert!(!panel.enabled(group)); + assert!(!panel.enabled(selected)); + assert!(!menu_enabled(&panel.app())); + assert!(panel.app().run(&save_as_swatches, json!({})).is_err()); + + for _ in 0..2 { + panel.app().run("file.new", json!({"width": 100, "height": 100})).unwrap(); + choose_linked_base(&mut panel.app(), Color::rgb(0.2, 0.4, 0.7), None); + panel.frame(); + panel.click("#1a335a"); + assert!(!panel.app().ui.color_guide_panel.picked.cells().is_empty()); + assert!(panel.enabled(group)); + assert!(panel.enabled(selected)); + assert!(menu_enabled(&panel.app())); + let before = panel.app().session.active().unwrap().doc.swatches.len(); + panel.app().run(&save_as_swatches, json!({})).unwrap(); + assert!(panel.app().session.active().unwrap().doc.swatches.len() > before); + + panel.app().session.execute("file.close", &json!({"index": 0})).unwrap(); + panel.frame(); + assert!(!panel.enabled(group)); + assert!(!panel.enabled(selected)); + assert!(!menu_enabled(&panel.app())); + } + } + /// The guide of the base without a library limit, as the panel makes it. fn guide_of(app: &VectorcraftApp) -> Guide { Guide::new(base_color(app), app.ui.color_guide_panel.rule, &app.ui.color_guide) @@ -908,7 +965,7 @@ mod tests { let before = app.session.doc().unwrap().doc.swatches.len(); let cells = &[(0, 0), (1, 4), (0, 8)].to_vec(); let undo = app.session.doc().unwrap().history.undo.len(); - save_selected(&mut app, cells); + save_selected(&mut app, cells).unwrap(); let st = app.session.doc().unwrap(); assert_eq!(st.doc.swatches.len(), before + 3); assert_eq!(st.history.undo.len(), undo + 1, "one undo step"); @@ -925,7 +982,7 @@ mod tests { let ctx = crate::testing::ui_context(); frame(&mut app, &ctx); let cells = &[(0, 0), (0, 6)].to_vec(); - save_selected(&mut app, cells); + save_selected(&mut app, cells).unwrap(); let g = guide_of(&app); assert!(matches!(g.grid[0][6], Color::Rgb { .. }), "{:?}", g.grid[0][6]); let sw = &app.session.doc().unwrap().doc.swatches; @@ -1476,7 +1533,7 @@ mod tests { let c = g.centre(); let undo = app.session.doc().unwrap().history.undo.len(); let cells = &[(0, c + 1), (0, c - 1), (0, c + 3)].to_vec(); - save_selected(&mut app, cells); + save_selected(&mut app, cells).unwrap(); let st = app.session.doc().unwrap(); assert_eq!(st.history.undo.len(), undo + 1, "one undo step"); let made: Vec<_> = st.doc.swatches[st.doc.swatches.len() - 3..].to_vec(); From 579aa6cf5f634de43e2c6a4831c363fb88ac2d28 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:50:50 -0800 Subject: [PATCH 102/193] Restore localized Paragraph alignment and spacing controls --- crates/ui-egui/src/panels/paragraph.rs | 39 ++++++- crates/ui-egui/src/panels/paragraph/tests.rs | 114 +++++++++++++++++++ 2 files changed, 147 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 26102b5311..6b93911427 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -8,8 +8,9 @@ // PLAN: assumed import paths for the framework items below (behavior::{IconId, Mixed}, keymap::CommandRef, // text::ui::character, ui::{buttons, choice::Select, controls::Checkbox, menu, popover, runtime::access::PopupKind}). use craft::behavior::{IconId, Mixed}; +use craft::i18n::WordSet as _; use craft::keymap::CommandRef; -use craft::text::ui::character::{DirectionRow, ParagraphChange, ParagraphControls, ParagraphDirection, ParagraphValues, TextAlign}; +use craft::text::ui::character::{DirectionRow, ParagraphChange, ParagraphControls, ParagraphDirection, ParagraphValues, ParagraphWords, TextAlign}; use craft::ui::buttons::{IconButton, PopupMark, ToggleButton}; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Entry, MemoProps, Props as _, Show as _, ShowContainer as _, Trigger}; @@ -21,6 +22,7 @@ use craft::ui::popover::Popover; use craft::ui::primitives::{Glyph, IconSpec}; use craft::ui::runtime::access::PopupKind; use craft::ui::runtime::commands::{CommandState, CommandStates}; +use craft::ui::runtime::env::{WordRows, WordsOverride, with_env}; use craft::ui::style::UiTokens; use egui::{Color32, Painter, Rect, Stroke, Ui, vec2}; use serde_json::{Value, json}; @@ -821,6 +823,30 @@ fn kinsoku_row(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// Maps the toolkit's different English names to the translations already in the app catalogs. +fn localized_control_words() -> WordRows { + [ + ("paragraph.left", ALIGNMENTS[0].2), + ("paragraph.center", ALIGNMENTS[1].2), + ("paragraph.right", ALIGNMENTS[2].2), + ("paragraph.justifyLeft", ALIGNMENTS[3].2), + ("paragraph.justifyCenter", ALIGNMENTS[4].2), + ("paragraph.justifyRight", ALIGNMENTS[5].2), + ("paragraph.justifyAll", ALIGNMENTS[6].2), + ("paragraph.spaceBefore", "Space Before Paragraph"), + ("paragraph.spaceAfter", "Space After Paragraph"), + ] + .into_iter() + .filter_map(|(id, source)| { + let translated = tl!(source); + if translated == source { + return None; + } + ParagraphWords::word(id).map(|word| (word, translated)) + }) + .fold(WordRows::new(), |rows, (word, translated)| rows.row(word, translated)) +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some((_, para)) = text_style(app) else { super::empty_state(ui, "pilcrow", tl!("No text selected"), tl!("Select a text object to edit its paragraph attributes.")); @@ -831,11 +857,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Paragraph direction, with the Middle Eastern (Indic) options. let direction = if app.session.prefs.show_indic_options { DirectionRow::Explicit } else { DirectionRow::Hidden }; // Indents and paragraph spacing are distances (General); type sizes follow Units ▸ Type. - let out = ParagraphControls::new(tl!("Paragraph"), &shown) - .unit(doc_unit(app.session.general_unit())) - .hyphenate(!hidden) - .direction_row(direction) - .show_with(ui, |ui| lists_row(app, ui)); + let controls = + ParagraphControls::new(tl!("Paragraph"), &shown).unit(doc_unit(app.session.general_unit())).hyphenate(!hidden).direction_row(direction); + let words = localized_control_words(); + let show = |ui: &mut Ui| controls.show_with(ui, |ui| lists_row(app, ui)); + let out = + if words.iter().next().is_some() { with_env(ui, |overrides| overrides.words = Some(WordsOverride::Overlay(words)), show) } else { show(ui) }; for event in &out.edits { edits::apply_event(app, event, &EditPath::Scope, &mut |app, change, _| apply(app, change)); } diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 0d56471f6d..6bdf50ca0b 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -25,6 +25,120 @@ fn editing_text(text: &str) -> (VectorcraftApp, Value) { (app, id) } +/// The minimum-width Paragraph dock keeps translated alignment and spacing controls usable. +#[test] +fn compact_paragraph_dock_keeps_localized_alignment_and_spacing_usable() { + use craft::behavior::dock::{DockEdge, Node, Workspace}; + use egui::accesskit::Role; + use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2}; + use std::sync::Arc; + + let width = crate::panel_docking::PANEL_MIN_WIDTH; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1000.0)); + let mut untranslated = Vec::new(); + for lang in ["en", "de", "fr", "pt-br"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.interface_language = lang.into(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = + app.run("text.create", json!({"x": 20, "y": 50, "text": "First\nSecond", "area": {"width": 180, "height": 100}})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("window.panel", json!({"panel": "paragraph"})).unwrap(); + app.run("window.panel.dock", json!({"panel": "paragraph", "column": true})).unwrap(); + app.run("window.panel.activate", json!({"panel": "paragraph"})).unwrap(); + + let ws = &app.ui.dock_workspace; + let mut layout = ws.layout().clone(); + let path = layout.dock_path(DockEdge::End).unwrap(); + let mut node = layout.root.as_mut().unwrap(); + for second_child in path { + let Node::Split { first, second, .. } = node else { panic!("end dock path") }; + node = if second_child { second } else { first }; + } + let Node::Dock { columns, .. } = node else { panic!("end dock") }; + let column = columns.iter_mut().find(|column| column.groups.iter().any(|group| group.panels.iter().any(|p| p == "paragraph"))).unwrap(); + assert!(!column.iconic); + column.width = Some(width); + let next = Workspace::from_parts(layout, ws.hidden().to_vec(), ws.floated().to_vec()); + Arc::make_mut(&mut app.ui.dock_workspace).replace(next); + + let ctx = crate::testing::ui_context(); + ctx.enable_accesskit(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, mut events: Vec, modifiers| { + time += 0.05; + events.insert(0, Event::ModifiersChanged(modifiers)); + let input = egui::RawInput { time: Some(time), events, screen_rect: Some(screen), ..Default::default() }; + crate::testing::app_frame(app, &ctx, input).platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes) + }; + for _ in 0..7 { + frame(&mut app, Vec::new(), Modifiers::NONE); + } + let nodes = frame(&mut app, Vec::new(), Modifiers::NONE); + let rect = + |node: &egui::accesskit::Node| node.bounds().map(|b| Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))); + let title = crate::i18n::t("Paragraph"); + let (_, body_node) = nodes.iter().find(|(_, node)| node.role() == Role::TabPanel && node.label() == Some(title)).unwrap(); + let body = rect(body_node).unwrap(); + assert!((body.width() - width).abs() < 1.0, "{lang}: {body:?}"); + + let mut descendants = Vec::new(); + let mut todo = body_node.children().to_vec(); + while let Some(id) = todo.pop() { + let Some((_, node)) = nodes.iter().find(|(key, _)| *key == id) else { continue }; + todo.extend(node.children()); + if let (Some(label), Some(bounds)) = (node.label(), rect(node)) { + descendants.push((label, node.role(), bounds)); + } + } + let mut control = |names: [&str; 2], role: Option| { + let (label, _, bounds) = descendants + .iter() + .find(|(label, kind, _)| { + role.is_none_or(|expected| *kind == expected) && names.iter().any(|name| *label == *name || *label == crate::i18n::t(name)) + }) + .unwrap_or_else(|| panic!("{lang}: no {names:?} with role {role:?}")); + assert!(bounds.is_positive() && body.expand(0.5).contains_rect(*bounds), "{lang}: {label} {bounds:?} outside {body:?}"); + let expected = crate::i18n::t(names[1]); + if expected != names[1] && *label != expected { + untranslated.push(format!("{lang}: {label:?}, expected {expected:?}")); + } + bounds.center() + }; + for names in [ + ["Left align text", "Align left"], + ["Right align text", "Align right"], + ["Justify last left", "Justify with last line aligned left"], + ["Justify last centered", "Justify with last line aligned center"], + ["Justify last right", "Justify with last line aligned right"], + ["Justify all", "Justify all lines"], + ] { + control(names, None); + } + let center = control(["Center text", "Align center"], None); + let before = control(["Add space before paragraph", "Space Before Paragraph"], Some(Role::SpinButton)); + let after = control(["Add space after paragraph", "Space After Paragraph"], Some(Role::SpinButton)); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let key = |key, modifiers, pressed| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }; + frame(&mut app, vec![Event::PointerMoved(center), button(center, true)], Modifiers::NONE); + frame(&mut app, vec![button(center, false)], Modifiers::NONE); + frame(&mut app, Vec::new(), Modifiers::NONE); + assert_eq!(selected(&app), [Justify::Center], "{lang}: pointer changed alignment"); + for (at, input) in [(before, "12"), (after, "18")] { + frame(&mut app, vec![Event::PointerMoved(at), button(at, true)], Modifiers::NONE); + frame(&mut app, vec![button(at, false)], Modifiers::NONE); + frame(&mut app, vec![key(Key::A, Modifiers::COMMAND, true)], Modifiers::COMMAND); + frame(&mut app, vec![key(Key::A, Modifiers::COMMAND, false), Event::Text(input.to_owned())], Modifiers::NONE); + frame(&mut app, vec![key(Key::Enter, Modifiers::NONE, true)], Modifiers::NONE); + frame(&mut app, vec![key(Key::Enter, Modifiers::NONE, false)], Modifiers::NONE); + } + assert_eq!(shared_para_field(&app, |p| p.space_before), Some(12.0), "{lang}: keyboard updated before"); + assert_eq!(shared_para_field(&app, |p| p.space_after), Some(18.0), "{lang}: keyboard updated after"); + crate::i18n::set_current(crate::i18n::Lang::EN); + } + assert!(untranslated.is_empty(), "lost Paragraph translations: {untranslated:?}"); +} + fn select_range(app: &mut VectorcraftApp, start: usize, end: usize) { app.session.set_tool_option("select", &json!({"start": start, "end": end})); } From eb153ab46e34017b233aeaff90d375cedf5b6aaa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:35:19 -0800 Subject: [PATCH 103/193] Keep Graph Data tied to the drawing it opened on --- crates/ui-egui/src/dialogs/graph_data.rs | 53 ++++++++++++++---------- 1 file changed, 32 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index ae58ce2ad6..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(), From be9a97a9c76eb075cbfc1cba0ab56b5e352a3249 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:38:29 -0800 Subject: [PATCH 104/193] Refuse older Kinsoku Shori drafts after File Revert --- crates/ui-egui/src/dialogs/kinsoku_sets.rs | 27 ++++++++++++------- .../ui-egui/src/dialogs/kinsoku_sets/tests.rs | 3 ++- 2 files changed, 19 insertions(+), 11 deletions(-) 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 c026cf4c3b..7d1755f51c 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs @@ -256,7 +256,8 @@ fn old_ok_keeps_restored_kinsoku_rules_and_the_current_tab() { 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)); - cancel(&mut 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(); From e8f812659033f8924767ac77fc618cba71bf9a61 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:58:45 -0800 Subject: [PATCH 105/193] Reproduce Symbol Options applying to changed art and reverted definitions --- crates/ui-egui/src/dialogs/symbol_options.rs | 67 +++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/symbol_options.rs b/crates/ui-egui/src/dialogs/symbol_options.rs index 470f78e55e..89e2e0135a 100644 --- a/crates/ui-egui/src/dialogs/symbol_options.rs +++ b/crates/ui-egui/src/dialogs/symbol_options.rs @@ -195,10 +195,12 @@ 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 editing_symbol_options_does_not_rename_another_drawings_symbol() { @@ -225,4 +227,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_eq!(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"); + } } From 79d9e1e1ab6f73a5f7bba8273c19286a93ba50a4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:59:31 -0800 Subject: [PATCH 106/193] Guard Symbol Options against later selections and reverted drawings --- crates/ui-egui/src/dialogs/symbol_options.rs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/symbol_options.rs b/crates/ui-egui/src/dialogs/symbol_options.rs index 89e2e0135a..e4282e51e6 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,23 @@ 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 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(); @@ -243,7 +255,7 @@ mod document_tests { let undo = app.session.active().unwrap().history.undo.len(); answer_dialog(&mut app, id, &[], true); - assert_eq!(app.session.active().unwrap().doc, before, "OK cannot turn the later selection into a symbol"); + 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(); From 480e9283a27fa6f23ff46b0f34819cc70a5ff4d2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:59:41 -0800 Subject: [PATCH 107/193] Effect Gallery: restore a readable artwork preview --- crates/ui-egui/src/dialogs/effect_gallery.rs | 124 ++++++++++++++++++- 1 file changed, 120 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index a515addb0e..6c84bd7a74 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -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}; @@ -45,7 +45,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; @@ -356,7 +356,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 +616,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(); From d021629d10d1e58f93662252fc98bba4a83c0447 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:00:24 -0800 Subject: [PATCH 108/193] Disable Load Profile without a desktop path picker --- crates/ui-egui/src/panels/separations.rs | 28 ++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index 6da7bcfb54..53961fb0ab 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -15,7 +15,7 @@ use craft::ui::buttons::Button; use craft::ui::choice::{Checkbox, Radio, RadioGroup}; use craft::ui::contract::{ Bind, CollectionEvent, ColumnSpec, Entry, Lazy, Props as _, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, - ToggleColumn, clicked, + ToggleColumn, TooltipSpec, clicked, }; use craft::ui::display::Text; use craft::ui::layout_components::{Row, Stack}; @@ -249,7 +249,12 @@ fn settings_rows(app: &mut VectorcraftApp, ui: &mut Ui) { } } Row::new().show(ui, |ui, _| { - if clicked(&Button::new(tl!("Load Profile…")).id_salt("load-profile").show(ui)) { + let load = tl!("Load Profile…"); + let picker = Button::new(load) + .id_salt("load-profile") + .enabled(app.host.files().can_pick()) + .tooltip(TooltipSpec::new(load).disabled_text(tl!("Loading color profiles requires a desktop file picker."))); + if clicked(&picker.show(ui)) { load_profile(app); } if clicked(&Button::new(tl!("Gamut Check")).id_salt("gamut-check").show(ui)) { @@ -458,6 +463,25 @@ mod tests { use crate::tests::panel_harness::Panel; use vectorcraft_engine::Session; + #[test] + fn load_profile_only_offers_a_picker_that_returns_a_path() { + use craft::host::ScriptedFiles; + use std::sync::Arc; + + for browser in [false, true] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + let files = ScriptedFiles::held(); + let files = Arc::new(if browser { files.in_browser() } else { files }); + crate::tests::picks::install_files(&mut app, files.clone()); + let mut panel = Panel::new(app, settings_rows); + assert_eq!(panel.enabled("Load Profile…"), !browser); + assert!(panel.enabled("Gamut Check")); + panel.click("Load Profile…"); + assert_eq!(files.requests().len(), usize::from(!browser)); + } + } + #[test] fn browser_profile_pick_reports_why_it_cannot_load() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); From cdb62fb7fa21d4b6c54e6a327c370c6010f1788b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:00:25 -0800 Subject: [PATCH 109/193] Disable JavaScript Files Choose without a path picker --- crates/ui-egui/src/dialogs/javascript_files.rs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) 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)); } } From 50be08fb0b8bc6f163f2f1a0359c194ffba971d0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:08:51 -0800 Subject: [PATCH 110/193] Require fresh Save for Web approval after Revert --- crates/ui-egui/src/dialogs/save_for_web.rs | 32 ++++++++++------- .../ui-egui/src/dialogs/save_for_web/tests.rs | 36 +++++++++++++++++++ 2 files changed, 55 insertions(+), 13 deletions(-) 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] From 8390031f73f53997dc23c48f8053ea32cfbc2152 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:09:49 -0800 Subject: [PATCH 111/193] Open browser-picked swatch libraries from Recolor Artwork --- crates/ui-egui/src/dialogs/recolor.rs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index a377869b5b..1ed93cc403 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}; @@ -1632,11 +1631,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 +3205,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(); From ea28f6e827f7124396e0d78cceaaba80bea6209d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:17:09 -0800 Subject: [PATCH 112/193] Retire the Dimension color picker after Revert --- crates/ui-egui/src/dialogs/dimension.rs | 57 +++++++++++++++++++++++-- 1 file changed, 53 insertions(+), 4 deletions(-) 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. From f86528b23096e38bb60d99137e84e49ffc47283b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:17:09 -0800 Subject: [PATCH 113/193] Retire Bullets and Numbering drafts after Revert --- .../ui-egui/src/dialogs/bullets_numbering.rs | 46 ++++++++++++++++--- 1 file changed, 40 insertions(+), 6 deletions(-) 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(); From d5f7883d1495ad13ba0f9cf9f004ab94f2968a6c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:17:09 -0800 Subject: [PATCH 114/193] Require a fresh New Brush opening after Revert --- crates/ui-egui/src/dialogs/brush_options.rs | 10 ++++-- crates/ui-egui/src/dialogs/new_brush.rs | 35 +++++++++++++++++++-- 2 files changed, 40 insertions(+), 5 deletions(-) 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/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 Date: Thu, 26 Nov 2026 18:17:09 -0800 Subject: [PATCH 115/193] Require fresh New Color Group choices after Revert --- crates/ui-egui/src/dialogs/new_color_group.rs | 37 ++++++++++++++++++- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_color_group.rs b/crates/ui-egui/src/dialogs/new_color_group.rs index 421d3a3d59..56073beaf9 100644 --- a/crates/ui-egui/src/dialogs/new_color_group.rs +++ b/crates/ui-egui/src/dialogs/new_color_group.rs @@ -18,7 +18,7 @@ pub const KIND: &str = "newColorGroup"; /// art is selected and no swatches are. pub fn open(app: &mut VectorcraftApp, swatches: Vec) -> 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())); From a97ae973ceb1a9112b08d714d62aa8819d004c49 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:19:14 -0800 Subject: [PATCH 116/193] Keep linked Canvas swatch drops in their source drawing --- crates/ui-egui/src/canvas/drops.rs | 11 ++++- crates/ui-egui/src/canvas/drops/tests.rs | 57 ++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 2 deletions(-) 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; From 57492ee0869b377aac47cd1d2d7a73092bf41c22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:24:47 -0800 Subject: [PATCH 117/193] Keep Live Paint Gap Options with its opened drawing contents --- crates/ui-egui/src/dialogs/live_paint_gaps.rs | 62 ++++++++++++++++--- 1 file changed, 53 insertions(+), 9 deletions(-) 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(); From 20bbbcde5bbea80fb2a9e85aec5006a582bc6254 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:22:38 -0800 Subject: [PATCH 118/193] Effects: translate built-in settings labels --- crates/ui-egui/src/dialogs/effect_params.rs | 71 ++++++++++++++++++++- 1 file changed, 68 insertions(+), 3 deletions(-) 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("レベル数")]); + } +} From 52a43e75b02b4da9256506cd37fa6e635e2b154b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:27:17 -0800 Subject: [PATCH 119/193] Reproduce Smart Punctuation applying past Selected Text Only --- .../ui-egui/src/dialogs/smart_punctuation.rs | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/crates/ui-egui/src/dialogs/smart_punctuation.rs b/crates/ui-egui/src/dialogs/smart_punctuation.rs index 9e68c0507b..f7d3ae4d08 100644 --- a/crates/ui-egui/src/dialogs/smart_punctuation.rs +++ b/crates/ui-egui/src/dialogs/smart_punctuation.rs @@ -208,4 +208,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!(answer.is_err()); + + 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!(answer.is_err()); + + 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); + } } From 9173525fca772610ee03a5a9fa3e33202b9b1f00 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:28:08 -0800 Subject: [PATCH 120/193] Bind Smart Punctuation Selected Text Only to the opening selection --- .../ui-egui/src/dialogs/smart_punctuation.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/smart_punctuation.rs b/crates/ui-egui/src/dialogs/smart_punctuation.rs index f7d3ae4d08..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() @@ -228,7 +239,7 @@ mod tests { 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!(answer.is_err()); + 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); @@ -244,7 +255,7 @@ mod tests { 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!(answer.is_err()); + assert_eq!(answer, Err("The selected text changed. Restore the selection to continue.".into())); set(&app, "scope", json!("document")); ok(&mut app); From 165233bb579f80c18bd6699539dd35cf3c62cb9c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:29:01 -0800 Subject: [PATCH 121/193] Keep Define Grid options with the drawing contents that opened them --- .../ui-egui/src/dialogs/perspective_grid.rs | 16 +++++---- .../ui-egui/src/dialogs/tests_perspective.rs | 33 +++++++++++++++++++ 2 files changed, 43 insertions(+), 6 deletions(-) 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/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(); From 5d6df038c6986d18e8eae294186d0d0936779b41 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:33:12 -0800 Subject: [PATCH 122/193] Scope Envelope Warp and Mesh previews to the opening drawing contents --- crates/ui-egui/src/dialogs/envelope.rs | 50 +++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/envelope.rs b/crates/ui-egui/src/dialogs/envelope.rs index a7079a2021..b9daed9358 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); @@ -218,6 +218,9 @@ fn accept(app: &mut VectorcraftApp, result: &ParamResult) -> 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; @@ -517,6 +520,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(); From 3e104f461e22cd9728b397edfae8dcb8609aee17 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:41:40 -0800 Subject: [PATCH 123/193] Keep Justification drafts off restored paragraphs --- crates/ui-egui/src/dialogs/justification.rs | 46 ++++++++++++++++++--- 1 file changed, 41 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/justification.rs b/crates/ui-egui/src/dialogs/justification.rs index 5b97daaedd..221cabd889 100644 --- a/crates/ui-egui/src/dialogs/justification.rs +++ b/crates/ui-egui/src/dialogs/justification.rs @@ -37,7 +37,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 +51,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) } } @@ -116,7 +116,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; @@ -146,8 +147,13 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let id = super::host::open_held(app, dialog, |app, result| { let Some(open) = app.justification.take() else { return Ok(()) }; if !open.in_opening_document(app) { + let message = if app.session.active().is_some_and(|st| st.uid == open.document.0) { + tl!("The document was reverted. Reopen this dialog to continue.") + } else { + tl!("This dialog was opened in a different document.") + }; app.justification = Some(open); - return Err(tl!("This dialog was opened in a different document.").to_owned()); + return Err(message.to_owned()); } let p = params(app, &result.fields, &open); if !changes(&p) { @@ -213,7 +219,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(); @@ -512,4 +518,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); + } } From d72977eca9f8c0fda8a1b07c21388cf5ce0a4e53 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:41:41 -0800 Subject: [PATCH 124/193] Require fresh Graph Type options after File Revert --- crates/ui-egui/src/dialogs/graph_type.rs | 37 ++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) 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"); + } } From 789bd7a21094d3443a98b6e65fee8cc26437cb94 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:41:41 -0800 Subject: [PATCH 125/193] Retire Flare Tool Options tied to restored artwork --- crates/ui-egui/src/dialogs/flare_options.rs | 37 +++++++++++++++++++-- 1 file changed, 34 insertions(+), 3 deletions(-) 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); + } } From b1e9dbb349d452f7b7de40cee9afdf0a5e91387f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:42:57 -0800 Subject: [PATCH 126/193] Keep New Document orientation reachable in compact web windows --- crates/ui-egui/src/dialogs/new_document.rs | 65 +++++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) 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); + } } From f8f5755b6e1b75656b30f3e7230ae737404dc83b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:45:16 -0800 Subject: [PATCH 127/193] Guard Graph Column and Marker drafts after File Revert --- crates/ui-egui/src/dialogs/graph_design.rs | 70 +++++++++++++++++++--- 1 file changed, 61 insertions(+), 9 deletions(-) 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)] { From c94fc92484bd7cc0ec3628a591776cec5be259df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:45:16 -0800 Subject: [PATCH 128/193] Keep Recolor Artwork previews with their opening drawing contents --- crates/ui-egui/src/dialogs/recolor.rs | 59 ++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index a377869b5b..4d9e350ec4 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -260,6 +260,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 +271,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 +342,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 +381,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) } @@ -3281,6 +3285,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"]})); From 9f73c4e3908e42f0895f5a70219366be4ce7151e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:49:24 -0800 Subject: [PATCH 129/193] Restore localized reference-point corner names in dialogs --- .../src/dialogs/objects_on_path_options.rs | 140 ++++++++++++++++++ crates/ui-egui/src/dialogs/tool_options.rs | 27 +++- 2 files changed, 165 insertions(+), 2 deletions(-) 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/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