From 007356257f27b46c7ae546955e335903a56fa233 Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Mon, 16 Nov 2026 22:19:03 +0100 Subject: [PATCH 01/34] #8188: .ai import keeps a stroke's arrowheads A stroke's arrowheads are symbols of the file that its style's stroke dictionary names (BSArrowBeginSymbol / BSArrowEndSymbol, with BSArrowBeginScale / BSArrowEndScale). The importer didn't read them, so lines came in without their heads. The style parser now records those symbol references, and the reader turns each arrowhead symbol into a custom arrowhead: the symbol's level, 1 pt sample of the line gives the axis and where the line stops under the head, the rest of its art is the head, tip at its rightmost point. A custom arrowhead can now carry that stop. The head goes on the path with its tip on the end or past it (Extend), whichever gives the object its drawn art's bounds; otherwise, and for heads that can't be read faithfully, the object keeps its drawn look. --- crates/doc/src/appearance/layers.rs | 6 +- crates/doc/src/appearance/stroke_style.rs | 30 +++- crates/doc/src/appearance/tests.rs | 13 +- crates/effects/src/stroke/arrow.rs | 3 +- crates/engine/src/cmd/stroke.rs | 2 +- crates/engine/tests/import_fuzz.rs | 48 ++++++ crates/eps/src/import/ai.rs | 1 + crates/eps/src/import/ai/arrowhead.rs | 174 +++++++++++++++++++ crates/eps/src/import/ai/read.rs | 9 +- crates/eps/src/import/ai/read/containers.rs | 2 + crates/eps/src/import/ai/read/directives.rs | 9 + crates/eps/src/import/ai/read/document.rs | 2 +- crates/eps/src/import/ai/read/ops.rs | 137 +++++++++++++-- crates/eps/src/import/ai/style.rs | 90 ++++++++++ crates/eps/src/import/ai/style/tests.rs | 21 ++- crates/eps/src/import/ai/tests.rs | 181 ++++++++++++++++++++ docs/file-format-parity.md | 3 +- docs/mcp.md | 4 +- 18 files changed, 707 insertions(+), 28 deletions(-) create mode 100644 crates/eps/src/import/ai/arrowhead.rs diff --git a/crates/doc/src/appearance/layers.rs b/crates/doc/src/appearance/layers.rs index f8a58758d8..882ba348ca 100644 --- a/crates/doc/src/appearance/layers.rs +++ b/crates/doc/src/appearance/layers.rs @@ -183,12 +183,14 @@ impl StrokeLayer { rotation: None, } } + /// The least weight an arrowhead is drawn at, in points ([`Self::arrow_weight`]). + pub const LEAST_ARROW_WEIGHT: f64 = 0.25; /// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least - /// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide (see + /// [`Self::LEAST_ARROW_WEIGHT`]. A head of weight `hw` fits a box about `4·hw` long and wide (see /// [`Arrowhead::reach`] and [`Arrowhead::half_width`]). pub fn arrow_weight(&self, end: bool) -> f64 { let pct = if end { self.arrow_scale.1 } else { self.arrow_scale.0 }; - (self.width * pct / 100.0).max(0.25) + (self.width * pct / 100.0).max(Self::LEAST_ARROW_WEIGHT) } /// How far the start (`end == false`) or end arrowhead can reach from its end point (0 /// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap. diff --git a/crates/doc/src/appearance/stroke_style.rs b/crates/doc/src/appearance/stroke_style.rs index 18b226c676..7a39d6cbb2 100644 --- a/crates/doc/src/appearance/stroke_style.rs +++ b/crates/doc/src/appearance/stroke_style.rs @@ -68,6 +68,10 @@ pub struct CustomArrowhead { /// across it, positive to the right of the direction the head points. A head is 4 units wide, /// as the built-in heads are, and a unit is the head's weight. pub path: PathData, + /// Where the stroke ends under the head, in head units back from the tip, when the head says + /// so ([`Self::with_stop`]); `None`: halfway along its length ([`Self::stop`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stop: Option, } #[derive(Deserialize)] @@ -75,11 +79,17 @@ struct CustomArrowheadData { name: String, #[serde(default)] path: PathData, + #[serde(default)] + stop: Option, } impl From for CustomArrowhead { fn from(d: CustomArrowheadData) -> Self { - CustomArrowhead::new(d.name, d.path) + let head = CustomArrowhead::new(d.name, d.path); + match d.stop { + Some(stop) => head.with_stop(stop), + None => head, + } } } @@ -94,7 +104,17 @@ impl CustomArrowhead { /// than [`Self::MAX_UNITS`] from the tip is dropped: the head then draws nothing. pub fn new(name: String, path: PathData) -> Self { let path = if Self::fits(&path) { path } else { PathData::default() }; - CustomArrowhead { name, path } + CustomArrowhead { name, path, stop: None } + } + /// The head with the stroke ending `stop` head units back from its tip (an arrowhead an + /// Illustrator file defines draws its line to a point of its own). A stop that is not finite, + /// is negative or is farther than [`Self::MAX_UNITS`] is left out: the stroke then ends + /// halfway along the head. + /// A head whose outline was dropped ([`Self::new`]) draws nothing and keeps no stop. + pub fn with_stop(mut self, stop: f64) -> Self { + let fits = !self.path.subpaths.is_empty() && stop.is_finite() && (0.0..=Self::MAX_UNITS).contains(&stop); + self.stop = fits.then_some(stop); + self } /// Whether outline `path` has at most [`Self::MAX_ANCHORS`] anchors and as many subpaths, with /// finite points within [`Self::MAX_UNITS`] only. @@ -116,10 +136,10 @@ impl CustomArrowhead { pub fn half_width(&self) -> f64 { self.bounds().map_or(0.0, |b| b.y0.abs().max(b.y1.abs())) } - /// Where the stroke ends under the head, in head units back from the tip: halfway along the - /// head's length. + /// Where the stroke ends under the head, in head units back from the tip: its own stop + /// ([`Self::with_stop`]), else halfway along the head's length. pub fn stop(&self) -> f64 { - self.bounds().map_or(0.0, |b| b.x1.max(0.0) / 2.0) + self.stop.unwrap_or_else(|| self.bounds().map_or(0.0, |b| b.x1.max(0.0) / 2.0)) } } diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index cb5f8fed66..c4cbe5ab18 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -381,6 +381,15 @@ fn custom_arrowheads_carry_their_art_and_measure_it() { assert_eq!(head.half_width(), 2.0); let Arrowhead::Custom(c) = &head else { panic!("custom") }; assert_eq!(c.stop(), 1.5, "the line stops halfway along the head"); + // A head with a stop of its own (an Illustrator file's arrowhead) keeps it, saved and read back. + let stopped = (**c).clone().with_stop(0.5); + assert_eq!(stopped.stop(), 0.5); + let back: CustomArrowhead = serde_json::from_value(serde_json::to_value(&stopped).unwrap()).unwrap(); + assert_eq!(back, stopped); + assert!(!serde_json::to_string(&**c).unwrap().contains("stop"), "a head without one writes none"); + for odd in [f64::NAN, -0.5, CustomArrowhead::MAX_UNITS + 1.0] { + assert_eq!((**c).clone().with_stop(odd).stop(), 1.5, "{odd} is left out"); + } // Saved with the stroke, art and all, beside the built-in heads' names. let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); (st.start_arrow, st.end_arrow) = (Some(Arrowhead::Triangle), Some(head.clone())); @@ -402,7 +411,7 @@ fn custom_arrowheads_out_of_bounds_draw_nothing() { let mut path = c.path.clone(); path.subpaths[0].anchors[1] = vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1e9, 0.0)); // A file can hold what `new` drops: reading it drops it too. - let json = serde_json::to_value(CustomArrowhead { name: "Wedge".into(), path }).unwrap(); + let json = serde_json::to_value(CustomArrowhead { name: "Wedge".into(), path, stop: None }).unwrap(); let far: CustomArrowhead = serde_json::from_value(json).unwrap(); assert_eq!((far.name.as_str(), far.path.subpaths.len()), ("Wedge", 0)); assert_eq!((far.reach(), far.half_width(), far.stop()), (0.0, 0.0, 0.0)); @@ -413,7 +422,7 @@ fn custom_arrowheads_out_of_bounds_draw_nothing() { let mut hollow = c.path.clone(); hollow.subpaths.extend(std::iter::repeat_n(vectorcraft_geom::SubPath::new(vec![], false), CustomArrowhead::MAX_ANCHORS)); assert!(!CustomArrowhead::fits(&hollow), "too many subpaths"); - let json = serde_json::to_value(CustomArrowhead { name: "Hollow".into(), path: hollow }).unwrap(); + let json = serde_json::to_value(CustomArrowhead { name: "Hollow".into(), path: hollow, stop: None }).unwrap(); let hollow: CustomArrowhead = serde_json::from_value(json).unwrap(); assert!(hollow.path.subpaths.is_empty(), "too many subpaths, read back"); } diff --git a/crates/effects/src/stroke/arrow.rs b/crates/effects/src/stroke/arrow.rs index d188bcafd6..1047e4d0dd 100644 --- a/crates/effects/src/stroke/arrow.rs +++ b/crates/effects/src/stroke/arrow.rs @@ -5,7 +5,8 @@ //! corner. With [`ArrowAlign::Tip`] the tip sits on the end point and the stroke is shortened by //! the inset; with [`ArrowAlign::Extend`] the path keeps its length and the tip sits the inset //! past the end point. Heads added after the first ten are drawn in local units ([`local`]), as are -//! custom heads, whose stroke ends halfway along their length. +//! custom heads, whose stroke ends at their own stop or else halfway along their length +//! ([`vectorcraft_doc::CustomArrowhead::stop`]). use std::borrow::Cow; diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index e8fb1349c3..737fbee6de 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads → {objects: how many objects took the stroke options}", has_doc, stroke_set ), diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 7fc7285dbb..1ab40972c0 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -8125,3 +8125,51 @@ proptest! { prop_assert_eq!(paths, 2, "{:?}", notes); } } + +proptest! { + #![proptest_config(config())] + + /// A stroke's arrowheads (#8188): its arrowhead entries with any scale of any kind, naming a + /// symbol the file defines, one it doesn't or one named in Chinese, the symbol's art any run of + /// paths (frames, samples of the line, heads, open and closed, filled, stroked or neither), at + /// any weight, the style section cut anywhere, the line drawn as any look. Read as a `.ai` and + /// as an EPS, then rendered. + #[test] + fn ai_arrowhead_strokes_never_panic( + scale in prop_oneof![arb_num(), Just("50".to_string())], + kind in prop::sample::select(vec!["Real", "Int", "Bool"]), + named in prop::sample::select(vec!["W", "Missing", "\u{6954}"]), + both in any::(), + art in prop::collection::vec(prop::sample::select(vec![ + "-10 5 m\n10 5 L\n10 -5 L\n-10 -5 L\nn\n", + "0 G\n1 w\n-9 0 m\n4 0 l\nS\n", + "0 G\n0.5 w\n-9 0 m\n4 0 l\nS\n", + "0 g\n2 3 m\n8 0 l\n2 -3 l\nf\n", + "0 G\n1 w\n2 3 m\n8 0 l\n2 -3 l\nS\n", + "0 g\n1e300 0 m\n-1e300 1 l\nf\n", + "0 g\n0 0 m\n0 0 l\nf\n", + ]), 0..6), + width in arb_num(), + cut in 0usize..2000, + look in prop::sample::select(vec!["0 G\n2 w\n0 50 m\n96 50 l\nS\n0 g\n94 53 m\n100 50 l\n94 47 l\nf\n", "0 G\n2 w\n0 50 m\n100 50 l\nS\n", ""]), + ) { + use vectorcraft_testkit::ai; + let symbol = format!("%AI5_Begin_NonPrinting\n%AI14_BeginSymbol\n(W)\n0 A\n0 Xw\n0 Ae\nu\n{}U\n%AI10_EndSymbol\n%AI5_End_NonPrinting--\n", art.concat()); + let start = if both { format!("{scale} /{kind} (BSArrowBeginScale) ,\n/GObjRef : ({named}) /SymbolArt ; (BSArrowBeginSymbol) ,\n") } else { String::new() }; + let styles = format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Arrowed) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/Dictionary : /NotRecorded ,\n\ + {start}{scale} /{kind} (BSArrowEndScale) ,\n/GObjRef : ({named}) /SymbolArt ; (BSArrowEndSymbol) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n\ + /StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j {width} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n%AI9_EndArtStyles\n\ + %AI9_BeginArtStyleList\n(Arrowed)\n%AI9_EndArtStyleList\n" + ); + let styles: String = styles.chars().take(cut).collect(); + let line = format!("0 Ae\nu\n{look}U\n%_0 50 m\n%_100 50 L\n%_N\n1 (Arrowed) XW\n"); + let data = ai::editing_data(200.0, 100.0, &format!("{symbol}{styles}{}", ai::layer("L", &line))); + survive("arrowhead strokes", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + let eps = ai::eps(data.as_bytes(), ai::page_ps()); + survive("arrowhead strokes in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + } +} diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 1a73f64a50..c882a2627b 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -17,6 +17,7 @@ //! objects and points. Anything it doesn't read is an error: the caller opens the file the way it //! did before (the printed page, or the PDF), with a warning saying why. +mod arrowhead; mod blend; mod brush; mod envelope; diff --git a/crates/eps/src/import/ai/arrowhead.rs b/crates/eps/src/import/ai/arrowhead.rs new file mode 100644 index 0000000000..11d098c759 --- /dev/null +++ b/crates/eps/src/import/ai/arrowhead.rs @@ -0,0 +1,174 @@ +//! Arrowheads a file defines: the art of a symbol that a stroke's arrowhead entry names +//! ([`super::style::StrokeArrows`]), read into a head ([`head`]). +//! +//! Not publicly documented. As the files have it, an arrowhead symbol's art (y down here, as the +//! document's symbols are) points right along a straight, level sample of the line it ends: an +//! open stroked path with no fill whose anchors and handles all lie on that line, 1 pt wide. The +//! sample ends where the line stops under the head. The rest of the art that paints is the head; +//! its tip is its rightmost point, and a symbol unit is one point on a 1 pt stroke at 100 %, so a +//! unit is the head's weight as it is for VectorCraft's own heads. Art that paints nothing (the +//! frame of the symbol's box, hidden or fully transparent art) is left out. + +use vectorcraft_doc::{AppearanceItem, CustomArrowhead, Node, NodeKind, StrokeLayer}; +use vectorcraft_geom::{Affine, FillRule, PathData, Point}; + +/// The most anchors an arrowhead symbol's art is read with, outlined strokes included, before its +/// shapes are united. +const MAX_ART_ANCHORS: usize = 65_536; +/// How deep the groups of an arrowhead symbol's art are read. +const MAX_DEPTH: usize = 16; + +/// The head that symbol art `art` (in the document's symbol space) draws, named `name`. `None` when +/// the art doesn't have exactly one sample of the line, its sample isn't 1 pt wide, it holds +/// anything but paths, compound paths and groups (a clip group, say), has an effect, a brush or a +/// group with fills or strokes of its own, paints no head, or is too detailed for one; or when the +/// line would stop past the head's tip or farther back than a head can reach +/// ([`CustomArrowhead::MAX_UNITS`]). +pub(super) fn head(name: &str, art: &Node) -> Option { + let mut parts = Parts::default(); + match &art.kind { + // The members of the symbol's group are its art's top level, where the sample is. + NodeKind::Group { children, clip: false } if art.visible && !paints(art) && art.appearance.effects.is_empty() => { + for c in children { + parts.member(c, true, 1)?; + } + } + _ => parts.member(art, true, 0)?, + } + let [(axis, line_end)] = parts.lines.as_slice() else { return None }; + if parts.shapes.is_empty() { + return None; + } + let refs: Vec<(&PathData, FillRule)> = parts.shapes.iter().map(|(p, r)| (p, *r)).collect(); + let area = vectorcraft_pathops::try_unite_all(&refs).ok()?; + let b = area.bounds().filter(|b| b.is_finite() && b.height() > 1e-9)?; + let tip = b.x1; + // Head units: x back from the tip, y across to the right of the way the head points (down). + let h = CustomArrowhead::new(name.to_string(), area.transformed(Affine::new([-1.0, 0.0, 0.0, 1.0, tip, -axis]))); + let h = h.with_stop(tip - line_end); + (!h.path.subpaths.is_empty() && h.stop.is_some()).then_some(h) +} + +/// What an arrowhead symbol's art is made of. +#[derive(Default)] +struct Parts { + /// Each sample of the line: the line's y, and the x where the sample ends. + lines: Vec<(f64, f64)>, + /// The areas the head paints. + shapes: Vec<(PathData, FillRule)>, + anchors: usize, +} + +impl Parts { + /// Read `n`, a member of the art (`top`: of its top level) `depth` groups down. `None` when it + /// is something [`head`] doesn't read. + fn member(&mut self, n: &Node, top: bool, depth: usize) -> Option<()> { + if depth > MAX_DEPTH { + return None; + } + // Hidden or fully transparent art paints nothing. + if !n.visible || n.opacity <= 0.0 { + return Some(()); + } + if !n.appearance.effects.is_empty() { + return None; + } + match &n.kind { + NodeKind::Group { children, clip: false } => { + if paints(n) { + return None; + } + children.iter().try_for_each(|c| self.member(c, false, depth + 1)) + } + NodeKind::Path { guide: true, .. } => Some(()), + NodeKind::Path { path, rule, .. } => self.painted(n, path, *rule, top), + NodeKind::Compound { children, rule } => { + let mut subpaths = vec![]; + for c in children { + subpaths.extend(c.path_data()?.subpaths.iter().cloned()); + } + self.painted(n, &PathData::new(subpaths), *rule, false) + } + _ => None, + } + } + + /// Read the fills and strokes of path or compound path `n`, its outline `path` filled under + /// `rule` (`top`: a member of the art's top level, which may be the sample of the line). + fn painted(&mut self, n: &Node, path: &PathData, rule: FillRule, top: bool) -> Option<()> { + self.room(path.anchor_count())?; + let mut filled = false; + let mut strokes: Vec<&StrokeLayer> = vec![]; + for item in &n.appearance.items { + match item { + AppearanceItem::Fill(f) if f.visible && f.opacity > 0.0 && !f.paint.is_none() => { + if !f.effects.is_empty() { + return None; + } + filled = true; + } + AppearanceItem::Stroke(s) if s.visible && s.opacity > 0.0 && !s.paint.is_none() && s.width > 0.0 => { + if !s.effects.is_empty() || s.brush.is_some() { + return None; + } + strokes.push(s); + } + _ => {} + } + } + if top + && !filled + && let [line] = strokes.as_slice() + && let Some(sample) = sample_line(path) + { + // The sample is 1 pt, the weight of a head at one unit; another weight (art stored + // at another scale, as a Large Canvas file's) gives the units no known size. + if (line.width - 1.0).abs() > 1e-6 { + return None; + } + self.lines.push(sample); + return Some(()); + } + if filled { + self.shapes.push((path.clone(), rule)); + } + for s in strokes { + let outline = vectorcraft_effects::stroke::outline_region(path, rule, s); + self.room(outline.anchor_count())?; + if !outline.subpaths.is_empty() { + self.shapes.push((outline, FillRule::NonZero)); + } + } + Some(()) + } + + /// Count `anchors` more; `None` past [`MAX_ART_ANCHORS`]. + fn room(&mut self, anchors: usize) -> Option<()> { + self.anchors = self.anchors.saturating_add(anchors); + (self.anchors <= MAX_ART_ANCHORS).then_some(()) + } +} + +/// Does `n` (a group) have fills or strokes of its own that paint? +fn paints(n: &Node) -> bool { + n.appearance.items.iter().any(|i| match i { + AppearanceItem::Fill(f) => f.visible && !f.paint.is_none(), + AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none(), + }) +} + +/// `path` as a sample of the line, when it is one open subpath of two anchors or more whose anchors +/// and handles all lie level with its first anchor: that y, and the x where it ends (its +/// rightmost anchor). +fn sample_line(path: &PathData) -> Option<(f64, f64)> { + let [sub] = path.subpaths.as_slice() else { return None }; + if sub.closed || sub.anchors.len() < 2 { + return None; + } + let y = sub.anchors.first()?.p.y; + let level = |q: Point| q.x.is_finite() && (q.y - y).abs() <= 1e-6 * (1.0 + y.abs()); + if !y.is_finite() || !sub.anchors.iter().all(|a| level(a.p) && level(a.h_in) && level(a.h_out)) { + return None; + } + Some((y, sub.anchors.iter().map(|a| a.p.x).fold(f64::NEG_INFINITY, f64::max))) +} diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 67928785ad..465ef512c6 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -122,8 +122,8 @@ use vectorcraft_color::swatch::Swatch; use vectorcraft_color::{BlendMode, Paint}; use vectorcraft_doc::cmyk::Inks; use vectorcraft_doc::{ - Appearance, AppearanceItem, Artboard, ColorMode, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, LineCap, LineJoin, - LinkInfo, Node, NodeId, NodeKind, OpacityMask, PageBox, PatternDef, StrokeLayer, Unit, + Appearance, AppearanceItem, Artboard, ColorMode, CustomArrowhead, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, + LineCap, LineJoin, LinkInfo, Node, NodeId, NodeKind, OpacityMask, PageBox, PatternDef, StrokeLayer, Unit, }; use vectorcraft_geom::{AnchorKind, FillRule, PathData}; @@ -537,6 +537,10 @@ struct Reader<'a> { symbol_bounds: HashMap, /// The symbols read, by their name in the file → their name in the document. symbol_names: HashMap, + /// The heads of the arrowhead symbols the art styles' strokes name, by the symbol's name in + /// the file (`None`: not a symbol read, or not one read as a head), read with the styles + /// ([`Reader::read_arrowheads`]). + arrowheads: HashMap>>, /// The names the symbols read have in the document, and for each name read more than once, /// the number its next copy is tried with. symbol_taken: HashSet, @@ -793,6 +797,7 @@ impl<'a> Reader<'a> { unread: Vec::new(), symbol_bounds: HashMap::new(), symbol_names: HashMap::new(), + arrowheads: HashMap::new(), symbol_taken: HashSet::new(), symbol_suffix: HashMap::new(), symbol_art_bounds: HashMap::new(), diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 9db1470093..f949ce5ed1 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -723,6 +723,8 @@ impl<'a> Reader<'a> { if std::mem::replace(&mut self.symbols_checked, true) { return; } + // The symbols are all read now: the heads of those defined after the styles. + self.read_arrowheads(); // Each symbol's name in the file (none for one named as an earlier one), and the names its // instances use. let files: HashMap<&str, &str> = self.symbol_names.iter().map(|(file, named)| (named.as_str(), file.as_str())).collect(); diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index 8ca3781717..68977f171a 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -128,6 +128,7 @@ impl<'a> Reader<'a> { // section inside it would replace the file's own. if self.subreader_depth == 0 { self.styles = crate::import::ai::style::art_styles_in(section, &mut self.names); + self.read_arrowheads(); } return Ok(()); } @@ -398,6 +399,7 @@ impl<'a> Reader<'a> { sub.gradients = std::mem::take(&mut self.gradients); sub.global_names = std::mem::take(&mut self.global_names); sub.styles = std::mem::take(&mut self.styles); + sub.arrowheads = std::mem::take(&mut self.arrowheads); sub.nodes = self.nodes; sub.template = self.template; self.lend_budgets(&mut sub); @@ -408,6 +410,7 @@ impl<'a> Reader<'a> { self.names.absorb(std::mem::take(&mut sub.names)); self.global_names = std::mem::take(&mut sub.global_names); self.styles = std::mem::take(&mut sub.styles); + self.arrowheads = std::mem::take(&mut sub.arrowheads); // Unread art in the definition, hidden or not, leaves the tile incomplete. let whole = read.is_ok() && sub.unsupported.is_empty() @@ -429,6 +432,7 @@ impl<'a> Reader<'a> { sub.gradients = std::mem::take(&mut self.gradients); sub.global_names = std::mem::take(&mut self.global_names); sub.styles = std::mem::take(&mut self.styles); + sub.arrowheads = std::mem::take(&mut self.arrowheads); sub.nodes = self.nodes; sub.template = self.template; self.lend_budgets(&mut sub); @@ -444,6 +448,7 @@ impl<'a> Reader<'a> { self.gradients = std::mem::take(&mut sub.gradients); self.global_names = std::mem::take(&mut sub.global_names); self.styles = std::mem::take(&mut sub.styles); + self.arrowheads = std::mem::take(&mut sub.arrowheads); self.names.absorb(std::mem::take(&mut sub.names)); let whole = read.is_ok() && sub.unsupported.is_empty() @@ -597,6 +602,7 @@ impl<'a> Reader<'a> { sub.gradients = std::mem::take(&mut self.gradients); sub.global_names = std::mem::take(&mut self.global_names); sub.styles = std::mem::take(&mut self.styles); + sub.arrowheads = std::mem::take(&mut self.arrowheads); sub.pattern_tiles = std::mem::take(&mut self.pattern_tiles); sub.v7_patterns.clone_from(&self.v7_patterns); sub.nodes = self.nodes; @@ -607,6 +613,7 @@ impl<'a> Reader<'a> { self.gradients = std::mem::take(&mut sub.gradients); self.global_names = std::mem::take(&mut sub.global_names); self.styles = std::mem::take(&mut sub.styles); + self.arrowheads = std::mem::take(&mut sub.arrowheads); self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles); self.names.absorb(std::mem::take(&mut sub.names)); // Art stopped by a trailer, or with an array, type, image, placed file, gradient mesh or @@ -788,6 +795,7 @@ impl<'a> Reader<'a> { // version 7 form, lent. sub.gradients = std::mem::take(&mut self.gradients); sub.styles = std::mem::take(&mut self.styles); + sub.arrowheads = std::mem::take(&mut self.arrowheads); sub.pattern_tiles = std::mem::take(&mut self.pattern_tiles); sub.v7_patterns = std::mem::take(&mut self.v7_patterns); sub.global_names = std::mem::take(&mut self.global_names); @@ -799,6 +807,7 @@ impl<'a> Reader<'a> { self.nodes = sub.nodes; self.gradients = std::mem::take(&mut sub.gradients); self.styles = std::mem::take(&mut sub.styles); + self.arrowheads = std::mem::take(&mut sub.arrowheads); self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles); self.v7_patterns = std::mem::take(&mut sub.v7_patterns); self.global_names = std::mem::take(&mut sub.global_names); diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 258d7d584b..840b9053bf 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1164,7 +1164,7 @@ impl<'a> Reader<'a> { continue; } let Some(st) = self.styles.get(&name) else { continue }; - let Some(mut appearance) = appearance_from_art_style(st, &self.gradients) else { continue }; + let Some(mut appearance) = appearance_from_art_style(st, &self.gradients, &self.arrowheads) else { continue }; // A Large Canvas copy's styles are at its art's scale ([`Self::ensure_space`]). if let Some(s) = self.large_canvas.filter(|s| *s != 1.0) { appearance.scale_strokes(s); diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 721a6988ba..f3f2b1d9cc 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -2,9 +2,12 @@ use super::containers::close; use super::document::slot_of; use super::types::{BLENDS, FLIP, Frame, GRAPH_UNENDED, IGNORED, Kind, MAX_DEPTH, MAX_NODES, MAX_TAG_TEXT, MAX_TAGS, Place, URL_TAG, line_width}; use super::{ - Affine, Appearance, AppearanceItem, Arc, BlendMode, BrushesKept, Dash, FillLayer, FillRule, Global, Gradient, GradientDef, HashMap, HashSet, - Instance, Knockout, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, ShownNames, StrokeLayer, V, obj, paint, + Affine, Appearance, AppearanceItem, Arc, BlendMode, BrushesKept, CustomArrowhead, Dash, FillLayer, FillRule, Global, Gradient, GradientDef, + HashMap, HashSet, Instance, Knockout, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, ShownNames, StrokeLayer, V, + obj, paint, }; +use vectorcraft_doc::{ArrowAlign, Arrowhead}; +use vectorcraft_geom::PathData; impl<'a> Reader<'a> { // ---- operators ------------------------------------------------------------------------- @@ -710,6 +713,30 @@ impl<'a> Reader<'a> { self.note_state(); } + /// Read the heads of the arrowhead symbols the art styles' strokes name into + /// [`Reader::arrowheads`] ([`crate::import::ai::arrowhead::head`]), each symbol once. Called + /// when the styles are read and again when the symbols have all been read ([`Self::check_symbols`]), + /// for a file that defines its symbols after its styles: a name with no symbol read yet is + /// left for then. + pub(super) fn read_arrowheads(&mut self) { + use crate::import::ai::style::StyleItem; + for st in self.styles.values() { + for item in &st.items { + let StyleItem::Stroke { arrows: Some(arrows), .. } = item else { continue }; + for name in arrows.symbols() { + if self.arrowheads.contains_key(name) { + continue; + } + let symbol = self.symbol_names.get(name).and_then(|named| self.doc.symbols.iter().find(|s| &s.name == named)); + if let Some(s) = symbol { + let head = crate::import::ai::arrowhead::head(name, &s.art).map(Arc::new); + self.arrowheads.insert(name.to_string(), head); + } + } + } + } + } + /// Brings [`Reader::brushes_kept`] up to date with the brushes and brush art read so far. fn note_brushes_kept(&mut self) { use super::super::brush; @@ -821,6 +848,7 @@ impl<'a> Reader<'a> { brushes: &self.brush_drafts, kept: &self.brushes_kept.kept, bending: &self.brushes_kept.bending, + arrowheads: &self.arrowheads, space, }, ) @@ -1047,6 +1075,8 @@ struct StylePaints<'a> { kept: &'a [bool], /// The art an Art brush draws as the file does, with its length ([`super::super::brush::bending_art`]). bending: &'a HashMap, + /// The heads of the arrowhead symbols strokes name ([`Reader::arrowheads`]). + arrowheads: &'a HashMap>>, space: Affine, } @@ -1332,7 +1362,7 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p return None; } } - stroke_layer(item)? + stroke_layer(item, paints.arrowheads)? } }; if let Some(look) = st.looks.get(n) { @@ -1345,7 +1375,73 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p } else { object.appearance.contents_index }; - Some(Appearance { items, effects: st.effects.clone(), contents_index }) + heads_placed(object, look, Appearance { items, effects: st.effects.clone(), contents_index }, paints.space) +} + +/// What `appearance` paints on path or compound path `object`: its fills' outline and its strokes' +/// areas, heads included, measured exactly (a node's visual bounds allow a head its whole reach on +/// every side). `None` for another object or an appearance that paints nothing. +fn painted_bounds(object: &Node, appearance: &Appearance) -> Option { + let (path, rule) = match &object.kind { + NodeKind::Path { path, rule, .. } => (path.clone(), *rule), + NodeKind::Compound { children, rule } => { + (PathData::new(children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect()), *rule) + } + _ => return None, + }; + let mut out = None; + for item in &appearance.items { + let painted = match item { + AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() => path.bounds(), + AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() => vectorcraft_effects::stroke::outline_region(&path, rule, s).bounds(), + _ => None, + }; + out = vectorcraft_geom::union_opt(out, painted); + } + out +} + +/// `appearance` (on `object`, whose drawn look is `look`, in a space `space` takes to the +/// document) with its strokes' arrowheads placed as the look draws them: the tips on the ends of +/// the path, or past them by the line's length under each head (Extend), whichever gives the +/// object the look's bounds within a quarter of the least distance a head moves between the two +/// (at least 0.05 pt, at most 0.5 pt). `None` +/// when neither does: the file draws the heads elsewhere (on other subpaths, say). +fn heads_placed(object: &Node, look: &Node, mut appearance: Appearance, space: Affine) -> Option { + let k = space.determinant().abs().sqrt(); + let k = if k.is_finite() && k > 0.0 { k } else { 1.0 }; + // How far each head moves between the placements: its line's length under it. + let mut shift = f64::INFINITY; + for item in &appearance.items { + let AppearanceItem::Stroke(s) = item else { continue }; + for (head, end) in [(&s.start_arrow, false), (&s.end_arrow, true)] { + if let Some(Arrowhead::Custom(c)) = head { + shift = shift.min(c.stop() * s.arrow_weight(end) * k); + } + } + } + if shift.is_infinite() { + return Some(appearance); + } + let want = look.visual_bounds()?; + // Well under the distance between the placements, and under half a point: a look without + // those heads, or with them elsewhere, is off by more. + let tolerance = (shift / 4.0).clamp(0.05, 0.5); + for align in [ArrowAlign::Tip, ArrowAlign::Extend] { + for item in &mut appearance.items { + if let AppearanceItem::Stroke(s) = item { + s.arrow_align = align; + } + } + let mut scaled = appearance.clone(); + scaled.scale_strokes(k); + let got = painted_bounds(object, &scaled)?; + let off = [got.x0 - want.x0, got.y0 - want.y0, got.x1 - want.x1, got.y1 - want.y1].iter().fold(0.0f64, |m, d| m.max(d.abs())); + if off <= tolerance { + return Some(appearance); + } + } + None } /// A graphic style's appearance from art style `st`, on no object: `None` when the style isn't one @@ -1353,7 +1449,11 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p /// A style that is one paint is its fill and stroke ([`crate::import::ai::style::ArtStyle::one_paint`]). /// A style keeps only its gradients' names and angles, so each one's gradient, by VectorCraft's own /// rule, is fitted to the bounds of whatever object the style is applied to, at its angle. -pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle, gradients: &HashMap) -> Option { +pub(super) fn appearance_from_art_style( + st: &crate::import::ai::style::ArtStyle, + gradients: &HashMap, + arrowheads: &HashMap>>, +) -> Option { use crate::import::ai::style::StyleItem; if !st.plain { return None; @@ -1368,7 +1468,7 @@ pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle, StyleItem::Fill(paint) => AppearanceItem::Fill(FillLayer::new(paint.clone())), // A graphic style's brush isn't checked against the file's brushes: it is left out. StyleItem::Stroke { brush: Some(_), .. } => return None, - StyleItem::Stroke { .. } => stroke_layer(item)?, + StyleItem::Stroke { .. } => stroke_layer(item, arrowheads)?, StyleItem::Gradient { name, angle } => AppearanceItem::Fill(FillLayer::new(named_gradient(name.as_deref()?, *angle, gradients)?)), StyleItem::Pattern { .. } => return None, }; @@ -1445,7 +1545,7 @@ pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&P .collect(); // No gradient is taken by name: on an object, one that isn't its own is placed where its drawn // look has it. - let mut appearance = appearance_from_art_style(&st, &HashMap::new())?; + let mut appearance = appearance_from_art_style(&st, &HashMap::new(), &HashMap::new())?; for (item, brush) in appearance.items.iter_mut().zip(brushes) { if let (AppearanceItem::Stroke(s), Some(brush)) = (item, brush) { s.brush = Some(brush); @@ -1461,12 +1561,27 @@ pub(crate) fn style_moves_with(section: &[u8], name: &str, object: &Node) -> boo crate::import::ai::style::art_styles(section).remove(name).is_some_and(|st| !st.moves_outline() || moves_with(object, &st)) } -/// A style's stroke as an appearance item (`None` for a fill). -fn stroke_layer(item: &crate::import::ai::style::StyleItem) -> Option { - let crate::import::ai::style::StyleItem::Stroke { paint, width, cap, join, miter, dash, profile, align, brush } = item else { return None }; +/// A style's stroke as an appearance item, its arrowheads the heads of `arrowheads` by symbol +/// name, each tip on its end of the path (where [`heads_placed`] finds the file draws them on an +/// object; a graphic style keeps that). `None` for a fill, or for a stroke +/// whose arrowhead symbol has no head there or whose head's weight would be under the least one +/// draws at ([`StrokeLayer::arrow_weight`]), so the head would draw larger than in the file. +fn stroke_layer(item: &crate::import::ai::style::StyleItem, arrowheads: &HashMap>>) -> Option { + let crate::import::ai::style::StyleItem::Stroke { paint, width, cap, join, miter, dash, profile, align, brush, arrows } = item else { + return None; + }; let mut layer = StrokeLayer::new(paint.clone(), line_width(*width)); (layer.cap, layer.join, layer.miter_limit, layer.dash, layer.profile, layer.align) = (*cap, *join, *miter, dash.clone(), profile.clone(), *align); layer.brush = brush.as_ref().map(|(name, _)| name.clone()); + if let Some(arrows) = arrows { + let head = |end: &Option<(String, f64)>| -> Option<(Option, f64)> { + let Some((name, pct)) = end else { return Some((None, 100.0)) }; + let head = arrowheads.get(name)?.clone()?; + (layer.width * pct / 100.0 >= StrokeLayer::LEAST_ARROW_WEIGHT).then_some((Some(Arrowhead::Custom(head)), *pct)) + }; + let ((start, start_pct), (end, end_pct)) = (head(&arrows.start)?, head(&arrows.end)?); + (layer.start_arrow, layer.end_arrow, layer.arrow_scale, layer.arrow_align) = (start, end, (start_pct, end_pct), ArrowAlign::Tip); + } Some(AppearanceItem::Stroke(layer)) } @@ -1651,6 +1766,7 @@ mod tests { brushes: &brushes, kept: &[true], bending: &bending, + arrowheads: &HashMap::new(), space: Affine::IDENTITY, }; let look = Node::group(NodeId(1), vec![square(2, Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))]); @@ -1697,6 +1813,7 @@ mod tests { brushes: &[], kept: &[], bending: &bending, + arrowheads: &HashMap::new(), space: Affine::IDENTITY, }; let look = Node::group(NodeId(1), vec![square(2, Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))]); diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index e0068a52be..50b590702d 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -229,6 +229,8 @@ impl ArtStyle { } } +// A stroke takes about 300 bytes and the other items about 100; a style holds a few of each. +#[allow(clippy::large_enum_variant)] #[derive(Clone, Debug, PartialEq)] pub(super) enum StyleItem { Fill(Paint), @@ -257,9 +259,35 @@ pub(super) enum StyleItem { align: StrokeAlign, /// A brush: its name, and its settings for this object. brush: Option<(String, PathBrush)>, + /// Its arrowheads, as symbols of the file (`None`: it has none). + arrows: Option>, }, } +/// A stroke's arrowheads: each end's symbol (`/GObjRef : (name) /SymbolArt ; (BSArrowBeginSymbol)` +/// or `(BSArrowEndSymbol)` in the stroke's dictionary) by its name in the file, with its scale in +/// percent (`BSArrowBeginScale`, `BSArrowEndScale`; 100 without one). The symbol's art is the head +/// and a sample of the line it ends, which `read::ops` reads into a head once the symbols are read. +#[derive(Clone, Debug, Default, PartialEq)] +pub(super) struct StrokeArrows { + pub start: Option<(String, f64)>, + pub end: Option<(String, f64)>, +} + +impl StrokeArrows { + /// The names of the symbols, start first. + pub fn symbols(&self) -> impl Iterator { + [&self.start, &self.end].into_iter().flatten().map(|(name, _)| name.as_str()) + } +} + +/// The arrowhead entries of a stroke's dictionary that [`stroke_arrows`] reads. Beside heads, any +/// other entry whose key starts with `BSArrow` isn't read, so the stroke keeps its drawn look. +const ARROW_ENTRIES: [&str; 4] = ["BSArrowBeginSymbol", "BSArrowEndSymbol", "BSArrowBeginScale", "BSArrowEndScale"]; + +/// The scales an arrowhead takes, in percent. +const ARROW_SCALES: std::ops::RangeInclusive = 1.0..=1000.0; + /// A fill's or stroke's own state in the stack. #[derive(Clone, Debug, PartialEq)] pub(super) struct ItemLook { @@ -319,6 +347,9 @@ struct Filter { /// The plug-in object it refers to (`/GObjRef : (name) (plug-in) /PluginObject`): its name and /// plug-in name. plugin_object: Option<(String, String)>, + /// The symbols its dictionary refers to (`/GObjRef : (name) /SymbolArt ; (key) ,`): each one's + /// name, by key. + symbols: HashMap, /// `mode opacity … Xy`. xy: Option<(usize, f32)>, /// `… isolate knockout … Xy`. @@ -351,6 +382,7 @@ impl Default for Filter { pattern: None, fill_last: LastPaint::None, plugin_object: None, + symbols: HashMap::new(), xy: None, xy_group: None, data: None, @@ -524,6 +556,11 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap dict_array = Some(vec![]), + // A symbol the dictionary refers to: `/GObjRef : (name) /SymbolArt ; (key) ,`. + b"SymbolArt" => { + symbol_entry(&mut lex, &mut operands, &mut other_entry, names, filters.last_mut().filter(|_| in_basic)); + continue; + } b"PluginObject" if in_basic => { let mut texts = operands.iter().rev().filter_map(|v| names.text(v)); if let (Some(plugin), Some(name), Some(f)) = (texts.next(), texts.next(), filters.last_mut()) { @@ -882,6 +919,7 @@ impl OnePaint { profile: None, align: StrokeAlign::Center, brush: None, + arrows: None, }), _ => return Err(()), } @@ -1477,11 +1515,61 @@ fn stroke_item(f: &Filter, align: StrokeAlign) -> Result, ()> profile: width_profile(&f.arrays), align, brush: None, + arrows: stroke_arrows(f)?, })), _ => Err(()), } } +/// The arrowheads of stroke filter `f` ([`StrokeArrows`]; `None` without any). `Err` for heads +/// beside an arrowhead entry [`ARROW_ENTRIES`] doesn't name, a scale that isn't a number in +/// [`ARROW_SCALES`], or a symbol entry with no symbol's name. +fn stroke_arrows(f: &Filter) -> Result>, ()> { + let end = |symbol: &str, scale: &str| -> Result, ()> { + if !f.kinds.contains_key(symbol) { + return Ok(None); + } + let name = f.symbols.get(symbol).ok_or(())?; + let pct = match f.kinds.get(scale) { + None => Some(100.0), + Some(Kind::Real) => entry(f, scale, Kind::Real)?, + Some(_) => entry(f, scale, Kind::Int)?, + }; + Ok(Some((name.clone(), pct.filter(|p| ARROW_SCALES.contains(p)).ok_or(())?))) + }; + let arrows = StrokeArrows { start: end("BSArrowBeginSymbol", "BSArrowBeginScale")?, end: end("BSArrowEndSymbol", "BSArrowEndScale")? }; + if arrows.start.is_none() && arrows.end.is_none() { + return Ok(None); + } + // Another arrowhead entry may change how the heads draw. + if f.kinds.keys().any(|k| k.starts_with("BSArrow") && !ARROW_ENTRIES.contains(&k.as_str())) { + return Err(()); + } + Ok(Some(Box::new(arrows))) +} + +/// A symbol the dictionary of `filter`, the basic filter being read, refers to, +/// `/GObjRef : (name) /SymbolArt ; (key) ,`, whose `/SymbolArt` `lex` has just read (`operands`: +/// the values before it, read by `names`): the symbol's name by its key in [`Filter::symbols`], the +/// key an entry of another kind. Outside a basic filter (`None`) nothing is read. +fn symbol_entry(lex: &mut Lexer, operands: &mut Vec, other_entry: &mut Option>, names: &mut Names, filter: Option<&mut Filter>) { + let Some(f) = filter else { return }; + let symbol = operands.iter().rev().find_map(|v| names.text(v)); + (*other_entry, *operands) = (None, vec![]); + let at = lex.offset(); + let (close, key) = (lex.next_token().map(|t| t.tok), lex.next_token().map(|t| t.tok)); + // Anything else is read as it comes (a `/KnownStyle` starting the next style, say). + let (Some(Tok::Word(b";")), Some(Tok::Str(key))) = (close, key) else { + lex.seek(at); + return; + }; + let key = String::from_utf8_lossy(&key).into_owned(); + f.repeated |= f.kinds.insert(key.clone(), Kind::Other).is_some(); + if let Some(symbol) = symbol { + f.symbols.insert(key, symbol); + } +} + /// A Stroke Offset filter `f`: a stroke whose own style is in its dictionary, aligned inside its /// path when `StrokeOffsetInside` is 1 and outside when it is 0 (its `DisplayString` says which). /// `Err` when that switch is missing or not a switch, or for a stroke [`paint_item`] doesn't read. @@ -1544,6 +1632,7 @@ fn calligraphic_stroke(f: &Filter) -> Option { profile: None, align: StrokeAlign::Center, brush: Some((name.clone(), PathBrush::Calligraphic(super::brush::calligraphic(values, variation, codes)))), + arrows: None, }) } @@ -1627,6 +1716,7 @@ fn art_stroke(f: &Filter) -> Option { profile: None, align: StrokeAlign::Center, brush: Some((name.clone(), PathBrush::Art(settings))), + arrows: None, }) } diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index c4b006fe2a..331e733e92 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -1545,8 +1545,10 @@ fn a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on() { }; let stroke = "0 R\n0 1 1 0 K\n1 J 2 j 3 w 4 M [2 1]0 d\n"; let Some(Ok(items)) = one(&format!("0 O\n0 0 1 0 k\n{stroke}1 1 Xd\n")) else { panic!("{:?}", one(stroke)) }; - let [StyleItem::Fill(fill), StyleItem::Stroke { paint, width, cap, join, miter, dash, profile: None, align: StrokeAlign::Center, brush: None }] = - items.as_slice() + let [ + StyleItem::Fill(fill), + StyleItem::Stroke { paint, width, cap, join, miter, dash, profile: None, align: StrokeAlign::Center, brush: None, arrows: _ }, + ] = items.as_slice() else { panic!("{items:?}") }; @@ -1587,3 +1589,18 @@ fn a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on() { assert_eq!(one(&paint), Some(Err(())), "{paint}"); } } + +/// A `/SymbolArt` entry cut short (no `; (key)` after it) leaves what follows to be read: here the +/// next style. +#[test] +fn a_symbol_entry_cut_short_leaves_the_next_style_read() { + let stroke = "/BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + /StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j 1 w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n"; + let text = format!( + "/KnownStyle :\n(Cut) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n{stroke}/GObjRef : (W) /SymbolArt\n\ + /KnownStyle :\n(Next) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n{stroke}; /Dict ;\n /Part ,\n;\n" + ); + let styles = art_styles(text.as_bytes()); + assert!(styles.contains_key("Cut") && styles.contains_key("Next"), "{:?}", styles.keys().collect::>()); + assert!(matches!(styles["Next"].items.as_slice(), [StyleItem::Stroke { arrows: None, .. }]), "{:?}", styles["Next"].items); +} diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index ca625a13c2..bf5143b15d 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -6254,6 +6254,187 @@ fn a_default_style_with_a_stroke_aligned_outside_comes_in() { assert_eq!(a[0].extras().graphic_style, Some(1)); } +/// An arrowhead symbol's art: an unpainted frame, a 1 pt sample of the line from x = −9 to 4 on +/// y = 0, and the head, a filled wedge from x = 2 back to its tip at x = 8, 3 either side. +const WEDGE_ART: &str = "-10 5 m\n10 5 L\n10 -5 L\n-10 -5 L\n-10 5 L\nn\n0 G\n1 w\n-9 0 m\n4 0 l\nS\n0 g\n2 3 m\n8 0 l\n2 -3 l\nf\n"; + +/// The end arrowhead entries of a stroke's dictionary: symbol `Wedge` at 50 %. +const END_WEDGE: &str = "50 /Real (BSArrowEndScale) ,\n/GObjRef : (Wedge) /SymbolArt ; (BSArrowEndSymbol) ,\n"; + +/// An art style named `name`: a black stroke of weight `width` whose stroke dictionary holds +/// `entries`, as a stroke's arrowheads are written. +fn arrow_style(name: &str, entries: &str, width: f64) -> String { + format!( + "/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\ + /Dictionary : /NotRecorded ,\n1 /Int (BSAdvStrokeDictionaryVersion) ,\n{entries}; (kAIBeautifulStrokesParamsDictKey) ,\n\ + /StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j {width} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n" + ) +} + +/// The drawn look of a 2 pt line from (0, 50) to (100, 50) with [`END_WEDGE`] (weight 1) on its end, +/// the tip on the end: the line to 4 before it, under the head from x = 94 to 100, 3 either side. +const END_WEDGE_LOOK: &str = "0 G\n2 w\n0 50 m\n96 50 l\nS\n0 g\n94 53 m\n100 50 l\n94 47 l\nf\n"; + +/// A line from (0, 50) to (100, 50) drawn as `look`, read as itself with the art style `name`. +fn arrowed_line(name: &str, look: &str) -> String { + format!("0 Ae\nu\n{look}U\n%_0 50 m\n%_100 50 L\n%_N\n1 ({name}) XW\n") +} + +/// A file with the arrowhead symbol `Wedge` (art `symbol_art`), the art style `Arrowed` +/// ([`arrow_style`] with `entries` and `width`), listed, and a line drawn with it as `look`. +fn arrowed_file(symbol_art: &str, entries: &str, width: f64, look: &str) -> String { + named_arrowed_file("Wedge", symbol_art, entries, width, look) +} + +/// [`arrowed_file`] with the symbol named `name`. +fn named_arrowed_file(name: &str, symbol_art: &str, entries: &str, width: f64, look: &str) -> String { + format!( + "{}{}{}", + symbols(&symbol(name, symbol_art, 5)), + styles_and_list(&[arrow_style("Arrowed", entries, width)], &["Arrowed"]), + layer(&arrowed_line("Arrowed", look)) + ) +} + +/// The object `r` reads, its path, and its stroke. +fn arrowed(r: &Structure) -> (Arc, vectorcraft_doc::StrokeLayer) { + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look: {:#?} {:?}", a[0], r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let s = a[0].appearance.stroke().expect("a stroke").clone(); + (a[0].clone(), s) +} + +/// The bounds of the area stroke `s` paints along path `n` (its heads included). +fn painted(n: &Node, s: &vectorcraft_doc::StrokeLayer) -> Rect { + let NodeKind::Path { path, rule, .. } = &n.kind else { panic!("a path") }; + vectorcraft_effects::stroke::outline_region(path, *rule, s).bounds().unwrap() +} + +#[test] +fn a_strokes_arrowhead_symbols_are_its_arrowheads() { + // GUARDS: a stroke's arrowheads (#8188) were left out: the line came in without its heads. + use vectorcraft_doc::{ArrowAlign, Arrowhead}; + let r = read_ok(&arrowed_file(WEDGE_ART, END_WEDGE, 2.0, END_WEDGE_LOOK)); + let (object, s) = arrowed(&r); + assert_eq!((s.width, s.arrow_scale, s.arrow_align), (2.0, (100.0, 50.0), ArrowAlign::Tip)); + assert!(s.start_arrow.is_none(), "{:?}", s.start_arrow); + let Some(Arrowhead::Custom(head)) = &s.end_arrow else { panic!("a head of the symbol's art: {:?}", s.end_arrow) }; + assert_eq!(head.name, "Wedge"); + // In head units, one a symbol unit: 6 long from the tip, 3 either side, the line stopping 4 + // back from the tip, where the sample ends. + let b = head.path.bounds().expect("an outline"); + for (got, want) in [(b.x0, 0.0), (b.x1, 6.0), (b.y0, -3.0), (b.y1, 3.0), (head.stop(), 4.0)] { + assert!((got - want).abs() < 1e-6, "{b:?}, stop {}", head.stop()); + } + // Drawn with the tip on the line's end: a head of weight 1 (2 pt at 50 %), 6 pt long. + let end = object.path_data().unwrap().subpaths[0].anchors.last().unwrap().p; + let drawn = painted(&object, &s); + assert!((drawn.x1 - end.x).abs() < 1e-6 && (drawn.height() - 6.0).abs() < 1e-6, "{drawn:?} for an end at {end:?}"); + // The listed graphic style has the head too. + let style = r.doc.graphic_styles[0].appearance.stroke().expect("the style's stroke"); + assert!(matches!(&style.end_arrow, Some(Arrowhead::Custom(h)) if h == head), "{:?}", style.end_arrow); +} + +#[test] +fn a_strokes_start_arrowhead_points_back_and_keeps_its_side() { + use vectorcraft_doc::Arrowhead; + // A head with one barb, below the line in the symbol (its space is y down): on the right of + // the way it points. At the start of a 1 pt line drawn left to right it points left, the barb + // above the line (the file's y up), the line starting 4 in. + let barb = "0 G\n1 w\n-9 0 m\n4 0 l\nS\n0 g\n2 3 m\n8 0 l\n2 0 l\nf\n"; + let entries = "/GObjRef : (Wedge) /SymbolArt ; (BSArrowBeginSymbol) ,\n"; + let look = "0 G\n1 w\n4 50 m\n100 50 l\nS\n0 g\n6 53 m\n0 50 l\n6 50 l\nf\n"; + let r = read_ok(&arrowed_file(barb, entries, 1.0, look)); + let (object, s) = arrowed(&r); + assert_eq!(s.arrow_scale, (100.0, 100.0)); + assert!(s.end_arrow.is_none()); + let Some(Arrowhead::Custom(head)) = &s.start_arrow else { panic!("{:?}", s.start_arrow) }; + let b = head.path.bounds().unwrap(); + assert!(b.y0.abs() < 1e-6 && (b.y1 - 3.0).abs() < 1e-6, "right of the way it points: {b:?}"); + // Drawn: the tip on the start, and 3 pt of head on the barb's side of the line (above it: the + // document's y down) against the line's half point on the other. + let start = object.path_data().unwrap().subpaths[0].anchors.first().unwrap().p; + let drawn = painted(&object, &s); + assert!((drawn.x0 - start.x).abs() < 1e-6, "{drawn:?} for a start at {start:?}"); + assert!((start.y - drawn.y0 - 3.0).abs() < 1e-6 && (drawn.y1 - start.y - 0.5).abs() < 1e-6, "{drawn:?} for a start at {start:?}"); +} + +#[test] +fn a_stroke_takes_both_heads_at_their_own_scales() { + use vectorcraft_doc::Arrowhead; + // The start at 100 % written as a whole number (weight 2: 12 long, 6 either side, the line 8 + // in), the end at 50 %, both of a symbol named in Chinese ("wedge"). + let entries = "100 /Int (BSArrowBeginScale) ,\n/GObjRef : (楔) /SymbolArt ; (BSArrowBeginSymbol) ,\n\ + 50 /Real (BSArrowEndScale) ,\n/GObjRef : (楔) /SymbolArt ; (BSArrowEndSymbol) ,\n"; + let look = "0 G\n2 w\n8 50 m\n96 50 l\nS\n0 g\n12 56 m\n0 50 l\n12 44 l\nf\n94 53 m\n100 50 l\n94 47 l\nf\n"; + let r = read_ok(&named_arrowed_file("楔", WEDGE_ART, entries, 2.0, look)); + let (object, s) = arrowed(&r); + assert_eq!(s.arrow_scale, (100.0, 50.0)); + for head in [&s.start_arrow, &s.end_arrow] { + assert!(matches!(head, Some(Arrowhead::Custom(h)) if h.name == "楔"), "{head:?}"); + } + let drawn = painted(&object, &s); + assert!((drawn.width() - 100.0).abs() < 1e-6 && (drawn.height() - 12.0).abs() < 1e-6, "{drawn:?}"); +} + +#[test] +fn heads_drawn_past_the_path_extend_it() { + use vectorcraft_doc::ArrowAlign; + // The file draws the head's tip 4 past the end (the line's length under it at weight 1): the + // line keeps its length. + let look = "0 G\n2 w\n0 50 m\n100 50 l\nS\n0 g\n98 53 m\n104 50 l\n98 47 l\nf\n"; + let r = read_ok(&arrowed_file(WEDGE_ART, END_WEDGE, 2.0, look)); + let (object, s) = arrowed(&r); + assert_eq!(s.arrow_align, ArrowAlign::Extend); + let end = object.path_data().unwrap().subpaths[0].anchors.last().unwrap().p; + assert!((painted(&object, &s).x1 - end.x - 4.0).abs() < 1e-6); +} + +#[test] +fn arrowheads_this_does_not_read_keep_the_drawn_look() { + let two_lines = format!("{WEDGE_ART}0 G\n1 w\n-9 0 m\n4 0 l\nS\n"); + let no_line = "0 g\n2 3 m\n8 0 l\n2 -3 l\nf\n"; + let thin_line = WEDGE_ART.replace("1 w", "0.5 w"); + let missing = "/GObjRef : (Elsewhere) /SymbolArt ; (BSArrowEndSymbol) ,\n"; + let unknown = format!("{END_WEDGE}1 /Int (BSArrowSomethingElse) ,\n"); + let too_large = "2000 /Real (BSArrowEndScale) ,\n/GObjRef : (Wedge) /SymbolArt ; (BSArrowEndSymbol) ,\n"; + let line_only = "0 G\n2 w\n0 50 m\n100 50 l\nS\n"; + let cases: [(&str, &str, &str, f64, &str); 8] = [ + ("a symbol the file doesn't define", WEDGE_ART, missing, 2.0, END_WEDGE_LOOK), + ("an arrowhead entry this doesn't read", WEDGE_ART, &unknown, 2.0, END_WEDGE_LOOK), + ("a scale out of range", WEDGE_ART, too_large, 2.0, END_WEDGE_LOOK), + ("a head lighter than the least weight drawn", WEDGE_ART, END_WEDGE, 0.25, END_WEDGE_LOOK), + ("a symbol without a sample of the line", no_line, END_WEDGE, 2.0, END_WEDGE_LOOK), + ("a symbol with two samples of the line", &two_lines, END_WEDGE, 2.0, END_WEDGE_LOOK), + ("a sample of the line that isn't 1 pt", &thin_line, END_WEDGE, 2.0, END_WEDGE_LOOK), + ("heads drawn neither on nor past the ends", WEDGE_ART, END_WEDGE, 2.0, line_only), + ]; + for (why, symbol_art, entries, width, look) in cases { + let r = read_ok(&arrowed_file(symbol_art, entries, width, look)); + let a = art(&r.doc); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{why}: {:?} {a:#?}", r.warnings); + assert!(!matches!(a[0].kind, NodeKind::Path { .. }), "{why}: the look, not the object"); + // A graphic style with an arrowhead it doesn't read isn't read either, rather than read + // without its heads. + let headless = |i: &AppearanceItem| matches!(i, AppearanceItem::Stroke(s) if s.end_arrow.is_none()); + let styles: Vec<_> = r.doc.graphic_styles.iter().filter(|g| g.name == "Arrowed").collect(); + assert!(styles.iter().all(|g| !g.appearance.items.iter().any(headless)), "{why}: {styles:?}"); + } +} + +#[test] +fn an_arrowhead_entry_without_heads_leaves_the_stroke_read() { + // Only beside heads does an arrowhead entry this doesn't read keep the drawn look. + let r = read_ok(&arrowed_file(WEDGE_ART, "1 /Int (BSArrowSomethingElse) ,\n", 2.0, "0 G\n2 w\n0 50 m\n100 50 l\nS\n")); + let (_, s) = arrowed(&r); + assert!(s.start_arrow.is_none() && s.end_arrow.is_none()); +} + #[test] fn a_symbol_defined_before_the_art_styles_reads_its_styled_objects() { // GUARDS: objects in a symbol defined ahead of `%AI9_BeginArtStyles` (as Illustrator 24 writes diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 9c46a01f77..fa4d25b9f2 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.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; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.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; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.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; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; 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; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (`.ai` import: a stroke's arrowheads, the symbols its style names, come in as custom arrowheads with their tip on, or past, the path's end, as the drawn art places it, and the line stopping where the symbol's sample of it ends, #8188; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.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; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.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; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.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; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; 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; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **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). @@ -344,6 +344,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-16 | 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), 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), 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`, `a_symbol_entry_cut_short_leaves_the_next_style_read` in `crates/eps/src/import/ai/style/tests.rs`, fuzzed by `ai_arrowhead_strokes_never_panic`; scores unchanged | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) came in with butt caps, miter joins and a miter limit of 10 whatever the file stroked it with, while paths kept the graphics state's. The characters' stroke now takes the line cap (`J`), line join (`j`) and miter limit (`M`) of the graphics state, as a path's stroke does, and glyphs stroked with other ones start a run of their own, also a glyph filled and then stroked otherwise than the run its fill joined, so the glyphs before it keep their stroke (#7741). Test `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`. Scores and estimates unchanged. | | 2026-11-13 | minor | `.ai` and EPS import: layers that don't draw as the page, even with the drawn art of every live envelope put back, no longer put back the drawn art of every envelope of type. Each live envelope of type is weighed in the page check's own drawing of the pages it lies on, on the pixels that it and its drawn art ink there (the two drawn together on a layer of their own, without the rest of the layers; a pixel inks with an alpha above 8 of 255): it keeps its drawn art and its type, hidden, with the note, where the layers with it differ from the page in more of those pixels than its own check allows against its drawn art (10% of them, or 3% differing with all their neighbours, away from type), or where the envelopes of type that stay live, in the order they were read, would together differ there in more of a page than half of what the page check allows (a budget of the same size as the one their own checks share, kept apart from it). Art that differs elsewhere on the page no longer costs them their editable type; art that differs on their pixels still does. An envelope of type that a clip group or a clipping sublayer clips, an opacity mask masks, or a group with an appearance of its own, another envelope, a repeat or a blend holds keeps its drawn art as before, wherever it lies: drawn on its own it would be weighed elsewhere than it draws, and what holds it can draw it onto the page from off it. An envelope on no page stays live, as the page check doesn't see it, unless the page holds all the art that prints (an EPS's page that is its art's box, where art past the page is compared too): there one reaching past the page keeps its drawn art. Past 12 of them on the pages, all keep it. This holds where the editing data is trusted, where the objects that differ come in as the page's art (the placed files' other placement weighed on its own, as it draws them elsewhere under or over the envelopes; layers that draw as the page with only the envelopes the page holds put back are used as they are; where none of the objects that differ can then come in as the page's art, because an object holds type, the drawn art of every envelope of type is put back and that is tried again, as before), and for a `.ai` whose layers would open alone, which still opens alone: its envelopes of type are all settled again as they were with the page, in the same order and with the same checks, so each that opens live draws as it was weighed, and those the page held get their drawn art back. Where putting the drawn art of every live envelope back makes the layers draw as the page, it is still put back (#5065). In 224 users' files (used locally, never committed): envelopes of type that open live go from 174 to 186, in 8 files, none fewer in any file; no file changes between its layers and its PDF part; 7 renders change, by at most 0.7% of their pixels at 40 ppi (1 closer to the page, 1 alike, 5 further, by at most 0.7 of a percentage point, where VectorCraft's own envelope draws a little apart from the drawn art, within its check); the note for type in an envelope goes from 6 files. Of the 14 envelopes of type that had opened live and lost it to the page check, 2 keep their drawn art: one where the page draws something else where it is, and one in a file that comes in as its PDF part (#7141). Tests `build::candidate_tests::the_page_holds_back_only_envelopes_of_type_where_it_differs_from_them`, `envelopes_of_type_stay_live_within_half_of_what_the_page_check_allows`, `an_envelope_of_type_differing_in_more_of_its_pixels_than_its_check_allows_is_held_back`, `envelopes_of_type_the_layers_dont_draw_in_place_are_held_back`, `on_a_page_that_holds_all_the_art_an_envelope_of_type_past_it_is_held_back`, `objects_come_in_as_the_page_art_with_every_envelope_of_type_put_back_where_a_live_one_holds_a_difference`, `tests_native::layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_doesnt_hold`, `trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_page_doesnt_hold_live`, `layers_with_objects_that_come_in_as_the_page_art_keep_an_envelope_of_type_that_draws_as_the_page_live`, `trusted_layers_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `trusted_layers_leave_an_envelope_of_type_the_page_draws_otherwise_its_drawn_art`, `build::candidate_tests::the_other_placement_of_placed_files_is_weighed_on_its_own`, `layers_that_draw_as_the_page_with_the_held_envelopes_of_type_put_back_are_used_so` | | 2026-11-13 | minor | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke instead of being left out, adding no text (#6971; `empty_actual_text_keeps_the_glyphs_art` in `crates/pdf/src/tests/actual_text.rs`). Scores and estimates unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index bee07110e6..a05bca8319 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5610,7 +5610,9 @@ Arrowheads… is not confined. `stroke.set {endArrow: {"custom": name}}` puts a custom head on a stroke. The stroke keeps a copy of the head's art, so the document draws it, saves it and exports it to SVG and PDF the same way without the arrowheads file. -`document.inspect` reports such a head as `{"Custom": {name, path}}`, which `stroke.set` takes back unchanged. It +`document.inspect` reports such a head as `{"Custom": {name, path}}`, which `stroke.set` takes back unchanged. A head +read from an Illustrator file also carries `stop`, where the stroke ends under it in head units back from the tip +(0 to 64; without it, the stroke ends halfway along the head). It refuses a `path` that fills no area (non-zero rule; parts thinner than a millionth of a head unit count as none) or has more than 4,096 anchors, more than 4,096 subpaths or a point more than 64 head units from the tip. The help page [Apply stroke on an object](https://helpx.adobe.com/illustrator/using/stroke-object.html) describes defining custom From 75c0bbd5d404cd160aa3bb7dcdf350b05669b694 Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Mon, 16 Nov 2026 23:14:55 +0100 Subject: [PATCH 02/34] #8188: arrowheads from partly transparent, masked or ambiguous art keep the drawn look Review follow-ups: - A symbol whose art is partly transparent or has an opacity mask makes no head: the head would come in opaque and whole. - When both placements give the drawn art's bounds (a line ending inside the bounds of its other segments) and the heads move 0.2 pt or more between them, the object keeps its drawn look. - A comment line inside a /SymbolArt entry is skipped. --- crates/eps/src/import/ai/arrowhead.rs | 82 +++++++++++++++++++++++-- crates/eps/src/import/ai/read/ops.rs | 20 +++++- crates/eps/src/import/ai/style.rs | 9 ++- crates/eps/src/import/ai/style/tests.rs | 12 ++++ crates/eps/src/import/ai/tests.rs | 19 ++++++ docs/file-format-parity.md | 2 +- 6 files changed, 133 insertions(+), 11 deletions(-) diff --git a/crates/eps/src/import/ai/arrowhead.rs b/crates/eps/src/import/ai/arrowhead.rs index 11d098c759..f1a30c08af 100644 --- a/crates/eps/src/import/ai/arrowhead.rs +++ b/crates/eps/src/import/ai/arrowhead.rs @@ -20,15 +20,16 @@ const MAX_DEPTH: usize = 16; /// The head that symbol art `art` (in the document's symbol space) draws, named `name`. `None` when /// the art doesn't have exactly one sample of the line, its sample isn't 1 pt wide, it holds -/// anything but paths, compound paths and groups (a clip group, say), has an effect, a brush or a -/// group with fills or strokes of its own, paints no head, or is too detailed for one; or when the +/// anything but paths, compound paths and groups (a clip group, say), has an effect, a brush, an +/// opacity mask, partial opacity or a group with fills or strokes of its own, paints no head, or is +/// too detailed for one; or when the /// line would stop past the head's tip or farther back than a head can reach /// ([`CustomArrowhead::MAX_UNITS`]). pub(super) fn head(name: &str, art: &Node) -> Option { let mut parts = Parts::default(); match &art.kind { // The members of the symbol's group are its art's top level, where the sample is. - NodeKind::Group { children, clip: false } if art.visible && !paints(art) && art.appearance.effects.is_empty() => { + NodeKind::Group { children, clip: false } if art.visible && plain(art) && !paints(art) => { for c in children { parts.member(c, true, 1)?; } @@ -70,7 +71,7 @@ impl Parts { if !n.visible || n.opacity <= 0.0 { return Some(()); } - if !n.appearance.effects.is_empty() { + if !plain(n) { return None; } match &n.kind { @@ -102,13 +103,13 @@ impl Parts { for item in &n.appearance.items { match item { AppearanceItem::Fill(f) if f.visible && f.opacity > 0.0 && !f.paint.is_none() => { - if !f.effects.is_empty() { + if !f.effects.is_empty() || f.opacity < 1.0 { return None; } filled = true; } AppearanceItem::Stroke(s) if s.visible && s.opacity > 0.0 && !s.paint.is_none() && s.width > 0.0 => { - if !s.effects.is_empty() || s.brush.is_some() { + if !s.effects.is_empty() || s.brush.is_some() || s.opacity < 1.0 { return None; } strokes.push(s); @@ -149,6 +150,12 @@ impl Parts { } } +/// Does `n` draw as its shapes alone: fully opaque, with no effects and no opacity mask applied? +/// A head is one opaque shape, so partly transparent or masked art isn't read as one. +fn plain(n: &Node) -> bool { + n.opacity >= 1.0 && n.appearance.effects.is_empty() && n.extras().mask.as_ref().is_none_or(|m| m.disabled) +} + /// Does `n` (a group) have fills or strokes of its own that paint? fn paints(n: &Node) -> bool { n.appearance.items.iter().any(|i| match i { @@ -172,3 +179,66 @@ fn sample_line(path: &PathData) -> Option<(f64, f64)> { } Some((y, sub.anchors.iter().map(|a| a.p.x).fold(f64::NEG_INFINITY, f64::max))) } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, Node, NodeId, OpacityMask}; + use vectorcraft_geom::{PathData, Point, SubPath}; + + use super::head; + + fn path(id: u64, points: &[(f64, f64)], closed: bool, appearance: Appearance) -> Arc { + let points: Vec = points.iter().map(|(x, y)| Point::new(*x, *y)).collect(); + Arc::new(Node::path(NodeId(id), PathData::single(SubPath::polyline(&points, closed)), appearance)) + } + + /// A 1 pt sample of the line from x = −9 to 4 on y = 0. + fn sample() -> Arc { + path(1, &[(-9.0, 0.0), (4.0, 0.0)], false, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)) + } + + /// A filled wedge from x = 2 back to its tip at x = 8, 3 either side. + fn wedge() -> Arc { + path(2, &[(2.0, -3.0), (8.0, 0.0), (2.0, 3.0)], true, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0)) + } + + fn art(members: Vec>) -> Node { + Node::group(NodeId(10), members) + } + + #[test] + fn a_wedge_and_its_sample_make_a_head() { + let h = head("W", &art(vec![sample(), wedge()])).expect("a head"); + assert_eq!(h.stop(), 4.0); + } + + #[test] + fn partly_transparent_or_masked_art_makes_no_head() { + // The head would come in opaque and whole, with the bounds of the art. + let half = |n: Arc| Arc::new(Node { opacity: 0.5, ..(*n).clone() }); + let mut faint_fill = (*wedge()).clone(); + let mut ap = (*faint_fill.appearance).clone(); + if let Some(f) = ap.fill_mut() { + f.opacity = 0.5; + } + faint_fill.appearance = ap.into(); + let mut masked = (*wedge()).clone(); + masked.extras_mut().mask = Some(Box::new(OpacityMask { art: sample(), clip: true, invert: false, disabled: false, linked: true })); + let cases = [ + ("a head at half opacity", art(vec![sample(), half(wedge())])), + ("a fill at half opacity", art(vec![sample(), Arc::new(faint_fill)])), + ("a group at half opacity", art(vec![sample(), half(Arc::new(art(vec![wedge()])))])), + ("the art at half opacity", Node { opacity: 0.5, ..art(vec![sample(), wedge()]) }), + ("a head with an opacity mask", art(vec![sample(), Arc::new(masked.clone())])), + ]; + for (why, a) in cases { + assert!(head("W", &a).is_none(), "{why}"); + } + // A disabled mask isn't applied. + masked.extras_mut().mask.as_mut().unwrap().disabled = true; + assert!(head("W", &art(vec![sample(), Arc::new(masked)])).is_some()); + } +} diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index f3f2b1d9cc..4f063bbeec 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1406,7 +1406,8 @@ fn painted_bounds(object: &Node, appearance: &Appearance) -> Option { /// the path, or past them by the line's length under each head (Extend), whichever gives the /// object the look's bounds within a quarter of the least distance a head moves between the two /// (at least 0.05 pt, at most 0.5 pt). `None` -/// when neither does: the file draws the heads elsewhere (on other subpaths, say). +/// when neither does (the file draws the heads elsewhere: on other subpaths, say), or when both do +/// and the heads move 0.2 pt or more between them (the bounds can't tell which the file draws). fn heads_placed(object: &Node, look: &Node, mut appearance: Appearance, space: Affine) -> Option { let k = space.determinant().abs().sqrt(); let k = if k.is_finite() && k > 0.0 { k } else { 1.0 }; @@ -1427,6 +1428,7 @@ fn heads_placed(object: &Node, look: &Node, mut appearance: Appearance, space: A // Well under the distance between the placements, and under half a point: a look without // those heads, or with them elsewhere, is off by more. let tolerance = (shift / 4.0).clamp(0.05, 0.5); + let mut fits = vec![]; for align in [ArrowAlign::Tip, ArrowAlign::Extend] { for item in &mut appearance.items { if let AppearanceItem::Stroke(s) = item { @@ -1438,10 +1440,22 @@ fn heads_placed(object: &Node, look: &Node, mut appearance: Appearance, space: A let got = painted_bounds(object, &scaled)?; let off = [got.x0 - want.x0, got.y0 - want.y0, got.x1 - want.x1, got.y1 - want.y1].iter().fold(0.0f64, |m, d| m.max(d.abs())); if off <= tolerance { - return Some(appearance); + fits.push(align); } } - None + // Both fit when the bounds can't tell the placements apart (the end inside the bounds of the + // line's other segments), unless the heads move so little that either draws alike. + let align = match fits.as_slice() { + [one] => *one, + [first, _] if shift < 0.2 => *first, + _ => return None, + }; + for item in &mut appearance.items { + if let AppearanceItem::Stroke(s) = item { + s.arrow_align = align; + } + } + Some(appearance) } /// A graphic style's appearance from art style `st`, on no object: `None` when the style isn't one diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 50b590702d..7e0ada7071 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -1557,7 +1557,14 @@ fn symbol_entry(lex: &mut Lexer, operands: &mut Vec, other_entry: &mut Option let symbol = operands.iter().rev().find_map(|v| names.text(v)); (*other_entry, *operands) = (None, vec![]); let at = lex.offset(); - let (close, key) = (lex.next_token().map(|t| t.tok), lex.next_token().map(|t| t.tok)); + // A comment line is no part of the entry. + let mut next = || loop { + match lex.next_token().map(|t| t.tok) { + Some(Tok::Comment(_)) => continue, + tok => return tok, + } + }; + let (close, key) = (next(), next()); // Anything else is read as it comes (a `/KnownStyle` starting the next style, say). let (Some(Tok::Word(b";")), Some(Tok::Str(key))) = (close, key) else { lex.seek(at); diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index 331e733e92..2210ccdbc0 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -1604,3 +1604,15 @@ fn a_symbol_entry_cut_short_leaves_the_next_style_read() { assert!(styles.contains_key("Cut") && styles.contains_key("Next"), "{:?}", styles.keys().collect::>()); assert!(matches!(styles["Next"].items.as_slice(), [StyleItem::Stroke { arrows: None, .. }]), "{:?}", styles["Next"].items); } + +/// A comment line inside a `/SymbolArt` entry is skipped: the entry is still read. +#[test] +fn a_comment_inside_a_symbol_entry_is_skipped() { + let text = "/KnownStyle :\n(Arrowed) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + /GObjRef : (W) /SymbolArt\n%a comment\n; (BSArrowEndSymbol) ,\n\ + /StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j 1 w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n;\n"; + let styles = art_styles(text.as_bytes()); + let [StyleItem::Stroke { arrows: Some(arrows), .. }] = styles["Arrowed"].items.as_slice() else { panic!("{:?}", styles["Arrowed"].items) }; + assert_eq!(arrows.end, Some(("W".to_string(), 100.0))); +} diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index bf5143b15d..7d8a213f80 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -6427,6 +6427,25 @@ fn arrowheads_this_does_not_read_keep_the_drawn_look() { } } +#[test] +fn heads_whose_placement_the_drawn_bounds_leave_open_keep_the_drawn_look() { + // The line bends back so its end, and a head on it either on the end or 4 past it, lie inside + // the bounds of its earlier segments: those bounds can't tell the two placements apart. + let path = "%_0 50 m\n%_0 0 L\n%_200 0 L\n%_200 100 L\n%_100 100 L\n%_100 50 L\n%_N\n"; + let look = "0 G\n2 w\n0 50 m\n0 0 l\n200 0 l\n200 100 l\n100 100 l\n100 54 l\nS\n0 g\n97 56 m\n100 50 l\n103 56 l\nf\n"; + let line = format!("0 Ae\nu\n{look}U\n{path}1 (Arrowed) XW\n"); + let file = format!( + "{}{}{}", + symbols(&symbol("Wedge", WEDGE_ART, 5)), + styles_and_list(&[arrow_style("Arrowed", END_WEDGE, 2.0)], &["Arrowed"]), + layer(&line) + ); + let r = read_ok(&file); + let a = art(&r.doc); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?} {a:#?}", r.warnings); + assert!(!matches!(a[0].kind, NodeKind::Path { .. }), "the look, not the object"); +} + #[test] fn an_arrowhead_entry_without_heads_leaves_the_stroke_read() { // Only beside heads does an arrowhead entry this doesn't read keep the drawn look. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index fa4d25b9f2..8bbd2d46be 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -344,7 +344,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| -| 2026-11-16 | 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), 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), 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`, `a_symbol_entry_cut_short_leaves_the_next_style_read` in `crates/eps/src/import/ai/style/tests.rs`, fuzzed by `ai_arrowhead_strokes_never_panic`; scores unchanged | +| 2026-11-16 | 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 the heads move 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` 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-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) came in with butt caps, miter joins and a miter limit of 10 whatever the file stroked it with, while paths kept the graphics state's. The characters' stroke now takes the line cap (`J`), line join (`j`) and miter limit (`M`) of the graphics state, as a path's stroke does, and glyphs stroked with other ones start a run of their own, also a glyph filled and then stroked otherwise than the run its fill joined, so the glyphs before it keep their stroke (#7741). Test `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`. Scores and estimates unchanged. | | 2026-11-13 | minor | `.ai` and EPS import: layers that don't draw as the page, even with the drawn art of every live envelope put back, no longer put back the drawn art of every envelope of type. Each live envelope of type is weighed in the page check's own drawing of the pages it lies on, on the pixels that it and its drawn art ink there (the two drawn together on a layer of their own, without the rest of the layers; a pixel inks with an alpha above 8 of 255): it keeps its drawn art and its type, hidden, with the note, where the layers with it differ from the page in more of those pixels than its own check allows against its drawn art (10% of them, or 3% differing with all their neighbours, away from type), or where the envelopes of type that stay live, in the order they were read, would together differ there in more of a page than half of what the page check allows (a budget of the same size as the one their own checks share, kept apart from it). Art that differs elsewhere on the page no longer costs them their editable type; art that differs on their pixels still does. An envelope of type that a clip group or a clipping sublayer clips, an opacity mask masks, or a group with an appearance of its own, another envelope, a repeat or a blend holds keeps its drawn art as before, wherever it lies: drawn on its own it would be weighed elsewhere than it draws, and what holds it can draw it onto the page from off it. An envelope on no page stays live, as the page check doesn't see it, unless the page holds all the art that prints (an EPS's page that is its art's box, where art past the page is compared too): there one reaching past the page keeps its drawn art. Past 12 of them on the pages, all keep it. This holds where the editing data is trusted, where the objects that differ come in as the page's art (the placed files' other placement weighed on its own, as it draws them elsewhere under or over the envelopes; layers that draw as the page with only the envelopes the page holds put back are used as they are; where none of the objects that differ can then come in as the page's art, because an object holds type, the drawn art of every envelope of type is put back and that is tried again, as before), and for a `.ai` whose layers would open alone, which still opens alone: its envelopes of type are all settled again as they were with the page, in the same order and with the same checks, so each that opens live draws as it was weighed, and those the page held get their drawn art back. Where putting the drawn art of every live envelope back makes the layers draw as the page, it is still put back (#5065). In 224 users' files (used locally, never committed): envelopes of type that open live go from 174 to 186, in 8 files, none fewer in any file; no file changes between its layers and its PDF part; 7 renders change, by at most 0.7% of their pixels at 40 ppi (1 closer to the page, 1 alike, 5 further, by at most 0.7 of a percentage point, where VectorCraft's own envelope draws a little apart from the drawn art, within its check); the note for type in an envelope goes from 6 files. Of the 14 envelopes of type that had opened live and lost it to the page check, 2 keep their drawn art: one where the page draws something else where it is, and one in a file that comes in as its PDF part (#7141). Tests `build::candidate_tests::the_page_holds_back_only_envelopes_of_type_where_it_differs_from_them`, `envelopes_of_type_stay_live_within_half_of_what_the_page_check_allows`, `an_envelope_of_type_differing_in_more_of_its_pixels_than_its_check_allows_is_held_back`, `envelopes_of_type_the_layers_dont_draw_in_place_are_held_back`, `on_a_page_that_holds_all_the_art_an_envelope_of_type_past_it_is_held_back`, `objects_come_in_as_the_page_art_with_every_envelope_of_type_put_back_where_a_live_one_holds_a_difference`, `tests_native::layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_doesnt_hold`, `trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_page_doesnt_hold_live`, `layers_with_objects_that_come_in_as_the_page_art_keep_an_envelope_of_type_that_draws_as_the_page_live`, `trusted_layers_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `trusted_layers_leave_an_envelope_of_type_the_page_draws_otherwise_its_drawn_art`, `build::candidate_tests::the_other_placement_of_placed_files_is_weighed_on_its_own`, `layers_that_draw_as_the_page_with_the_held_envelopes_of_type_put_back_are_used_so` | | 2026-11-13 | minor | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke instead of being left out, adding no text (#6971; `empty_actual_text_keeps_the_glyphs_art` in `crates/pdf/src/tests/actual_text.rs`). Scores and estimates unchanged. | From fb333e757d0e748e1faad3d7205dabdadcdf02b4 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 17:07:34 -0800 Subject: [PATCH 03/34] #8068: sample Image Trace ignore color from the source --- crates/tools/src/xform/eyedropper.rs | 114 ++++- crates/ui-egui/src/app/commands.rs | 1 + crates/ui-egui/src/canvas.rs | 14 +- crates/ui-egui/src/canvas/drag.rs | 3 + crates/ui-egui/src/dialogs/tools.rs | 5 + crates/ui-egui/src/panels/image_trace.rs | 170 ++++++- crates/ui-egui/src/state.rs | 13 + .../tests/image_trace_ignore_sampler.rs | 419 ++++++++++++++++++ docs/ui-parity.md | 2 + 9 files changed, 736 insertions(+), 5 deletions(-) create mode 100644 crates/ui-egui/tests/image_trace_ignore_sampler.rs diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 2f99c8ca0a..0543797a9a 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -16,6 +16,9 @@ //! //! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into //! the open dialog (`brushKeyColor` UI request) and switches back. +//! +//! Image Trace's Ignore Color eyedropper passes its bound document point to the panel, which +//! samples the original image pixels; this tool changes neither paint nor selection. use std::collections::HashSet; @@ -28,7 +31,7 @@ use vectorcraft_geom::{Affine, Point, Rect}; use super::paint_owner; use crate::params::color_json; -use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; #[derive(Default)] pub struct EyedropperTool { @@ -38,6 +41,8 @@ pub struct EyedropperTool { text_selection: crate::text::TypeTool, /// Brush Options › Key Color (Hue Shift): sample into the dialog, then [`Self::stop`]. brush_key_color: bool, + /// Image Trace > Ignore Color: the panel's opaque document/object/revision binding. + image_trace_ignore_color: Option, } /// The colour of `paint` at `p` (gradients are sampled along their vector, radial ones honouring @@ -462,6 +467,13 @@ impl Tool for EyedropperTool { if ev.kind != PointerKind::Down { return vec![]; } + if let Some(binding) = self.image_trace_ignore_color.take() { + let back = self.stop.take().unwrap_or_else(|| "selection".to_string()); + return vec![ + Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "point": [ev.pos.x, ev.pos.y] })), + Action::SwitchTool(back), + ]; + } let opts = sample_options(cx); if self.brush_key_color { let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] }; @@ -496,6 +508,23 @@ impl Tool for EyedropperTool { out } + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key != ToolKey::Escape { + return vec![]; + } + let Some(binding) = self.image_trace_ignore_color.take() else { return vec![] }; + let back = self.stop.take().unwrap_or_else(|| "selection".to_string()); + vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "cancel": true })), Action::SwitchTool(back)] + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + self.image_trace_ignore_color.is_some() && key == ToolKey::Escape + } + + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + self.image_trace_ignore_color.is_some() + } + /// Expose a transient text range alongside gradient-stop and brush-key sampling state. fn options(&self) -> Value { let selected = self.text_selection.options(); @@ -503,6 +532,9 @@ impl Tool for EyedropperTool { if let Some(o) = options.as_object_mut() { o.insert("stop".into(), json!(self.stop)); o.insert("brushKeyColor".into(), json!(self.brush_key_color)); + if let Some(binding) = &self.image_trace_ignore_color { + o.insert("imageTraceIgnoreColor".into(), binding.clone()); + } } options } @@ -512,6 +544,7 @@ impl Tool for EyedropperTool { match key { "stop" => self.stop = value.as_str().map(str::to_string), "brushKeyColor" => self.brush_key_color = value.as_bool().unwrap_or(false), + "imageTraceIgnoreColor" => self.image_trace_ignore_color = (!value.is_null()).then(|| value.clone()), "textSelection" => self.text_selection.set_option(key, value), _ => {} } @@ -636,6 +669,85 @@ mod tests { assert_eq!(t.options(), json!({ "stop": null, "brushKeyColor": false })); } + /// The panel samples the bound original raster, even on empty canvas or with modifiers held. + #[test] + fn image_trace_sampling_forwards_its_binding_and_document_point_once() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let binding = json!({"doc": 7, "target": id.0, "revision": 11}); + for mods in [Mods::default(), Mods { alt: true, ..Default::default() }, Mods { alt: true, shift: true, ..Default::default() }] { + let mut t = EyedropperTool::default(); + t.set_option("stop", &json!("gradient")); + t.set_option("imageTraceIgnoreColor", &binding); + assert_eq!(t.options()["imageTraceIgnoreColor"], binding); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Move, -25.5, 400.25)).is_empty()); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, -25.5, 400.25)).is_empty()); + assert_eq!( + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, -25.5, 400.25).with_mods(mods)), + vec![ + Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "point": [-25.5, 400.25]})), + Action::SwitchTool("gradient".into()), + ] + ); + assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false})); + assert!(!t.claims_key(&cx, ToolKey::Escape)); + assert!(!t.ends_on_escape(&cx)); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + } + } + + /// Escape's UI request is claimed only while this one-shot target is armed. + #[test] + fn image_trace_escape_cancels_its_binding_and_restores_the_tool_once() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let binding = json!({"doc": 7, "target": id.0, "revision": 11}); + let mut t = EyedropperTool::default(); + assert!(!t.claims_key(&cx, ToolKey::Escape)); + assert!(!t.ends_on_escape(&cx)); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + t.set_option("stop", &json!("selection")); + t.set_option("imageTraceIgnoreColor", &binding); + assert!(t.claims_key(&cx, ToolKey::Escape)); + assert!(t.ends_on_escape(&cx)); + assert!(!t.claims_key(&cx, ToolKey::Enter)); + assert!(t.key(&cx, ToolKey::Enter, Mods::default()).is_empty()); + assert_eq!(t.options()["imageTraceIgnoreColor"], binding); + assert_eq!( + t.key(&cx, ToolKey::Escape, Mods::default()), + vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "cancel": true})), Action::SwitchTool("selection".into())] + ); + assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false})); + assert!(!t.claims_key(&cx, ToolKey::Escape)); + assert!(!t.ends_on_escape(&cx)); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + } + + /// A cleared Image Trace request leaves the existing brush/stop options and keys alone. + #[test] + fn clearing_image_trace_sampling_preserves_existing_brush_and_stop_options() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = EyedropperTool::default(); + t.set_option("brushKeyColor", &json!(true)); + t.set_option("stop", &json!("selection")); + let original = t.options(); + t.set_option("imageTraceIgnoreColor", &json!({"doc": 7, "target": 8, "revision": 11})); + t.set_option("imageTraceIgnoreColor", &Value::Null); + assert_eq!(t.options(), original); + assert!(!t.claims_key(&cx, ToolKey::Escape)); + assert!(!t.ends_on_escape(&cx)); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + assert_eq!(t.options(), original); + assert_eq!( + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)), + vec![Action::Dialog("brushKeyColor".into(), json!({"color": color_json(&Color::WHITE)})), Action::SwitchTool("selection".into())] + ); + } + /// The hex of the colour a `paint.sampleColor` action samples. fn sampled_hex(a: &[Action]) -> String { let [Action::Exec(c, p)] = a else { panic!("one action: {a:?}") }; diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 8cf742e499..38c947c57c 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -467,6 +467,7 @@ impl VectorcraftApp { } self.ui.flyout = None; switched?; + crate::panels::image_trace::cancel_ignore_sampler(self, false); if let Some(g) = vectorcraft_tools::catalog::group_of(id) && let Some(slot) = self.ui.group_tool.get_mut(g) { diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 19cae2d9cc..9e007a0890 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -248,6 +248,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The meshes of the tools' shared paths. Likewise, a frame that does not draw the tools' // overlays drops them. let mut shared_paths = std::mem::take(&mut app.canvas.shared_paths); + let sampler_cancelled = crate::panels::image_trace::refresh_ignore_sampler(app); // A release ends the Image Trace panel's eye-button hold, also when the panel is no longer // drawn, so a later press elsewhere does not show the source image. if app.ui.trace_hold_source.is_some() && !ui.input(|i| i.pointer.any_down()) { @@ -295,7 +296,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { scroll_bars(app, ui, rect, outer, &t); } let resp = ui.interact(rect, egui::Id::unique("canvas"), Sense::click_and_drag()); - canvas_input(app, ui, &resp, rect); + input_after_sampler_refresh(app, ui, &resp, rect, sampler_cancelled); let v = *app.view().unwrap_or(&View::default()); let xf = Xf::at(rect, &v, app.canvas_ui_zoom); // While the view pans, zooms or turns under the pointer, the art under it isn't hit-tested. @@ -461,6 +462,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// A press arriving with an invalidated sampler is consumed, not given to its restored tool. +fn input_after_sampler_refresh(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect, cancelled: bool) { + if !cancelled || !ui.input(|i| i.pointer.any_pressed()) { + canvas_input(app, ui, resp, rect); + } +} + /// The pointer on the canvas: the tool's input, unless the context menu or the 3D gizmo has the press. pub(crate) fn canvas_input(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) { @@ -634,8 +642,8 @@ fn cache_key( rich_black: app.session.prefs.black_on_screen == "rich", // A tool's drag on the canvas, during an interaction (not a dialog's preview). dragging: app.session.in_interaction() && ui.data(|d| d.get_temp::(drag_id())) == Some(Drag::Tool), - // The Image Trace panel's eye button, while it is held. - trace_source: app.ui.trace_hold_source.clone(), + // The sampler keeps its bound original visible between clicks, independently of the eye. + trace_source: crate::panels::image_trace::ignore_sampler_source(app, st.uid).or_else(|| app.ui.trace_hold_source.clone()), // Preferences › Performance › Use Monitor Profile for Canvas. display: app.display_profile.key(app.session.prefs.monitor_profile_display), backdrop: backdrop(app, st, app.outline_view()), diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 68f06c70cc..f733fa68f8 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -378,6 +378,9 @@ pub(crate) fn end_art_move(app: &mut VectorcraftApp, ctx: &egui::Context) { /// Send a pointer event to the active tool and act on UI requests (dialogs, tool switches). pub fn dispatch(app: &mut VectorcraftApp, ev: &PointerEvent, view: vectorcraft_engine::ViewInfo) { + if ev.kind == PointerKind::Down && crate::panels::image_trace::discard_stale_ignore_click(app) { + return; + } // A press lent to a selection tool (Cmd/Ctrl held) does not use the tool of a held key. if ev.kind == PointerKind::Down && app.session.lent_tool_id(&ev.mods).is_none() { crate::shortcuts::note_tool_use(app); diff --git a/crates/ui-egui/src/dialogs/tools.rs b/crates/ui-egui/src/dialogs/tools.rs index 6dbcfe28ce..4700d3bc33 100644 --- a/crates/ui-egui/src/dialogs/tools.rs +++ b/crates/ui-egui/src/dialogs/tools.rs @@ -124,6 +124,11 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) { } // Double-clicking a stop on the gradient annotator: its popover, next to the stop's chip. "gradientStop" => Dialog::new(kind, json!({"index": p.get("index").cloned().unwrap_or(json!(0)), "x": x, "y": y, "tab": "color"})), + // Image Trace's Ignore Color eyedropper updates the panel, not the document's paint. + "imageTraceIgnoreColor" => { + crate::panels::image_trace::apply_ignore_color_sample(app, &p); + return; + } // Brush Options › Key Color eyedropper: update the open dialog, do not replace it. "brushKeyColor" => { if let Some(c) = p.get("color") { diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index bca4192b61..1ecb349821 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -232,6 +232,155 @@ fn hold_source(app: &mut VectorcraftApp, ctx: &egui::Context, down: bool) { } } +/// The retained original image of a live trace, or the selected placed image itself. +fn source_image(n: &Node) -> Option<&vectorcraft_doc::ImageObject> { + let source = if is_trace(n) { n.children()?.first()?.as_ref() } else { n }; + match &source.kind { + NodeKind::Image(image) => Some(image), + _ => None, + } +} + +fn sampler_binding(s: &crate::state::TraceIgnoreSampler) -> Value { + json!({ "doc": s.doc, "target": s.target.0, "revision": s.revision }) +} + +fn sampler_valid(app: &VectorcraftApp, s: &crate::state::TraceIgnoreSampler) -> bool { + let Some(doc) = app.session.active() else { return false }; + doc.uid == s.doc + && doc.revision == s.revision + && target_key(app) == Some((s.doc, s.target)) + && doc.doc.node(s.target).and_then(source_image).is_some_and(|image| doc.doc.images.contains_key(&image.key)) +} + +fn sampler_tool_active(app: &VectorcraftApp, s: &crate::state::TraceIgnoreSampler) -> bool { + app.session.tool_id() == "eyedropper" && app.session.tool_options()["imageTraceIgnoreColor"] == sampler_binding(s) +} + +/// Clear only this temporary mode. An explicit tool choice keeps the tool the user chose. +pub(crate) fn cancel_ignore_sampler(app: &mut VectorcraftApp, restore: bool) { + let Some(s) = app.ui.trace_ignore_sampler.take() else { return }; + if sampler_tool_active(app, &s) { + app.session.set_tool_option("imageTraceIgnoreColor", &Value::Null); + app.session.set_tool_option("stop", &Value::Null); + } + if restore && app.session.tool_id() == "eyedropper" { + app.return_to_tool(&s.back); + } + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } +} + +/// Also runs when the panel is closed: document changes and tool changes end the source preview. +pub(crate) fn refresh_ignore_sampler(app: &mut VectorcraftApp) -> bool { + let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return false }; + if !sampler_valid(app, s) { + cancel_ignore_sampler(app, true); + } else if !sampler_tool_active(app, s) { + cancel_ignore_sampler(app, false); + } else { + return false; + } + true +} + +/// A stale sampler's click must not become a paint/selection click in the restored tool. +pub(crate) fn discard_stale_ignore_click(app: &mut VectorcraftApp) -> bool { + let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return false }; + if sampler_valid(app, s) && sampler_tool_active(app, s) { + return false; + } + let restore = app.session.tool_id() == "eyedropper"; + cancel_ignore_sampler(app, restore); + true +} + +/// Render the bound live trace's original without changing its stored View or the eye's hold. +pub(crate) fn ignore_sampler_source(app: &VectorcraftApp, doc: u64) -> Option>> { + let s = app.ui.trace_ignore_sampler.as_ref()?; + (s.doc == doc && sampler_valid(app, s) && sampler_tool_active(app, s) && target(app).0).then(|| Arc::new(vec![s.target])) +} + +fn start_ignore_sampler(app: &mut VectorcraftApp, ctx: &egui::Context) { + if app.ui.trace_ignore_sampler.is_some() { + cancel_ignore_sampler(app, true); + return; + } + let Some((doc, target)) = target_key(app) else { return }; + let Some(revision) = app.session.active().map(|d| d.revision) else { return }; + let s = crate::state::TraceIgnoreSampler { doc, target, revision, back: app.session.tool_id().to_string() }; + if !sampler_valid(app, &s) { + return; + } + if let Err(e) = app.try_select_tool("eyedropper") { + app.status(e); + return; + } + if !sampler_valid(app, &s) { + app.return_to_tool(&s.back); + return; + } + app.session.set_tool_option("imageTraceIgnoreColor", &sampler_binding(&s)); + app.session.set_tool_option("stop", &json!(s.back.as_str())); + // Bind the reply to this panel's state, also when it is drawn without the full app frame. + app.ui_ctx = Some(ctx.clone()); + app.ui.trace_ignore_sampler = Some(s); + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } +} + +/// Match Image Trace's input bytes, not the current canvas result or the working-space colour. +fn sampled_ignore_color(app: &VectorcraftApp, s: &crate::state::TraceIgnoreSampler, p: &Value) -> Option { + let point = vectorcraft_geom::Point::new(p["point"][0].as_f64()?, p["point"][1].as_f64()?); + if !point.x.is_finite() || !point.y.is_finite() { + return None; + } + let doc = &app.session.active()?.doc; + let image = source_image(doc.node(s.target)?)?; + if image.xf.determinant().abs() < 1e-12 { + return None; + } + let pixel = image.xf.inverse() * point; + let [r, g, b, alpha] = doc.images.get(&image.key)?.sample_object(pixel.x, pixel.y, (image.width, image.height), 1)?; + (alpha != 0).then(|| format!("#{r:02x}{g:02x}{b:02x}")) +} + +/// Handle the one-shot tool's reply after it has consumed its transient binding. +pub(crate) fn apply_ignore_color_sample(app: &mut VectorcraftApp, p: &Value) { + let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return }; + if p["binding"] != sampler_binding(s) { + return; + } + let valid = sampler_valid(app, s); + let s = s.clone(); + cancel_ignore_sampler(app, false); + if !valid || p["cancel"] == true { + return; + } + let Some(color) = sampled_ignore_color(app, &s, p) else { return }; + // The canvas UI establishes this context before a real panel click can arm the sampler. + let Some(ctx) = app.ui_ctx.clone() else { return }; + let all = presets(app, &ctx); + let mut st: TraceUi = pstate(&ctx, "image-trace"); + let (is_trace, _, stored) = target(app); + follow_preset_changes(app, &mut st, &all); + let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect(); + sync_with_object(&mut st, stored, Some((s.doc, s.target)), &all, &changes); + st.params["ignoreColor"] = json!(color); + st.preset = "Custom".into(); + let preview = app.ui.image_trace_preview; + if is_trace || !preview { + st.preview_off = !preview; + } + if is_trace && preview { + trace(app, &ctx, &mut st); + } + set_pstate(&ctx, "image-trace", st); + ctx.request_repaint(); +} + /// The selected Image Trace object's View row (Control bar, Properties). pub(crate) fn view_row(app: &mut VectorcraftApp, ui: &mut Ui, current: TraceView, width: f32) { widgets::dim_label(ui, tl!("View:")); @@ -807,17 +956,36 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.horizontal(|ui| { let on = st.params["ignoreWhite"].as_bool().unwrap_or(false); if widgets::check(ui, tl!("Ignore Color"), on, true) { + if on { + cancel_ignore_sampler(app, true); + } st.params["ignoreWhite"] = json!(!on); st.preset = "Custom".into(); retrace = true; } if on { let mut rgb = ignore_color(&st.params); - if ui.color_edit_button_srgb(&mut rgb).changed() { + let picker = ui.color_edit_button_srgb(&mut rgb); + if picker.clicked() { + cancel_ignore_sampler(app, true); + } + if picker.changed() { st.params["ignoreColor"] = json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])); st.preset = "Custom".into(); retrace = true; } + if widgets::icon_button_enabled( + ui, + "pipette", + tl!("Eyedropper: click the source image to sample the ignored color"), + app.ui.trace_ignore_sampler.is_some(), + is_trace || is_image, + 22.0, + ) + .clicked() + { + start_ignore_sampler(app, ui.ctx()); + } } }); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d3698aaeef..3fd913830e 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -6,6 +6,15 @@ use vectorcraft_geom::Point; use crate::theme::Brightness; +/// A one-shot Image Trace Ignore Color sampler, bound to the unchanged selected source. +#[derive(Clone, Debug)] +pub struct TraceIgnoreSampler { + pub doc: u64, + pub target: vectorcraft_doc::NodeId, + pub revision: u64, + pub back: String, +} + /// Per-document view (camera). #[derive(Clone, Copy, Debug, Serialize, Deserialize)] pub struct View { @@ -847,6 +856,9 @@ pub struct UiState { /// panel's eye button is held down ([`vectorcraft_render::RenderOptions::trace_source`]). #[serde(skip)] pub trace_hold_source: Option>>, + /// Ignore Color's one-shot canvas sampler; independent of the eye button's press lifetime. + #[serde(skip)] + pub trace_ignore_sampler: Option, /// Layers panel › Panel Options… (row size, thumbnails, Show Layers Only, Locate Selected Objects). #[serde(default)] pub layers_panel: crate::panels::layers::PanelOptions, @@ -1271,6 +1283,7 @@ impl Default for UiState { psd_import: Value::Null, home: None, trace_hold_source: None, + trace_ignore_sampler: None, layers_panel: Default::default(), navigator_panel: Default::default(), layers_filter: Default::default(), diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs new file mode 100644 index 0000000000..225bfec39e --- /dev/null +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -0,0 +1,419 @@ +//! Image Trace Ignore Color's real panel button, tool callback and canvas presentation. +//! All APIs used here exist on the pre-fix base; the first regression fails on the missing button. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::time::{Duration, Instant}; + +use egui::{Event, PointerButton, Pos2, RawInput, Rect, vec2}; +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeId, NodeKind, TraceView}; +use vectorcraft_engine::Session; +use vectorcraft_geom::Point; +use vectorcraft_tools::{PointerEvent, PointerKind}; +use vectorcraft_ui_egui::{CacheKey, VectorcraftApp, canvas, trace_runs}; + +const SAMPLE_TIP: &str = "Eyedropper: click the source image to sample the ignored color"; + +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> egui::FullOutput { + let mut raw = RawInput { events, focused: true, screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1400.0))), ..Default::default() }; + // raw_input_hook already begins the host iteration; do not begin a second one. + app.raw_input_hook(ctx, &mut raw); + ctx.run_ui(raw, |ui| { + app.tick(ui.ctx()); + app.ui(ui); + }) +} + +fn settle(app: &mut VectorcraftApp, ctx: &egui::Context) { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + trace_runs::poll(app); + frame(app, ctx, vec![]).textures_delta.clear(); + if !trace_runs::any_running(app) { + break; + } + assert!(Instant::now() < deadline, "the tiny fixture's background trace did not finish"); + std::thread::sleep(Duration::from_millis(5)); + } + for _ in 0..2 { + frame(app, ctx, vec![]).textures_delta.clear(); + } +} + +fn click_control(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { + let mut found = None; + for _ in 0..3 { + let mut out = frame(app, ctx, vec![]); + if let Some(update) = &out.platform_output.accesskit_update { + found = update.nodes.iter().find(|(_, node)| node.label() == Some(label)).and_then(|(_, node)| node.bounds()); + } + out.textures_delta.clear(); + if found.is_some() { + break; + } + } + let bounds = found.unwrap_or_else(|| panic!("missing accessible Image Trace control: {label}")); + let at = egui::pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![Event::PointerMoved(at)]).textures_delta.clear(); + frame(app, ctx, vec![press(true)]).textures_delta.clear(); + frame(app, ctx, vec![press(false)]).textures_delta.clear(); + settle(app, ctx); +} + +fn fixture(live_trace: bool, rgb: [u8; 3], preview: bool) -> (VectorcraftApp, egui::Context) { + vectorcraft_ui_egui::i18n::set_current(vectorcraft_ui_egui::i18n::Lang::EN); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let pixels: Vec = (0..400).flat_map(|i| if i % 20 < 10 { [rgb[0], rgb[1], rgb[2], 255] } else { [255; 4] }).collect(); + let image = + craft_image_codecs::Image::from_raw(20, 20, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, pixels).unwrap(); + let png = craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + app.run( + "file.place", + json!({"name": "sampler-original.png", "dataBase64": vectorcraft_format::base64_encode(&png), "link": false, "at": [200, 150]}), + ) + .unwrap(); + if live_trace { + app.run( + "imageTrace.make", + json!({"preset": "Default", "params": {"mode": "blackAndWhite", "threshold": 127, "noise": 1, "ignoreWhite": false}}), + ) + .unwrap(); + } + app.select_tool("selection"); + app.ui.image_trace_preview = preview; + app.ui.image_trace_advanced = true; + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.session.prefs.monitor_profile_display = false; + app.canvas.worker_started = true; // the existing same-thread CPU canvas route + // An ordinary dock column gives Advanced the full window height without an auxiliary OS viewport. + app.run("window.panel.dock", json!({"panel": "imageTrace", "side": "End", "collapsed": false})).unwrap(); + app.run("window.panel.activate", json!({"panel": "imageTrace"})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + for _ in 0..8 { + frame(&mut app, &ctx, vec![]).textures_delta.clear(); + } + click_control(&mut app, &ctx, "Ignore Color"); + (app, ctx) +} + +fn selected(app: &VectorcraftApp) -> Node { + let state = app.session.active().unwrap(); + state.doc.node(state.selection.objects[0]).unwrap().clone() +} + +fn settings(app: &VectorcraftApp) -> Value { + selected(app).extras().trace.as_deref().unwrap().clone() +} + +fn source_point(app: &VectorcraftApp, x: f64) -> Point { + let selected = selected(app); + let original = selected.children().and_then(|children| children.first()).map_or(&selected, |child| child.as_ref()); + let NodeKind::Image(image) = &original.kind else { panic!("selected source image") }; + image.xf * Point::new(f64::from(image.width) * x, f64::from(image.height) * 0.5) +} + +fn sample(app: &mut VectorcraftApp, ctx: &egui::Context, point: Point) { + click_control(app, ctx, SAMPLE_TIP); + assert_eq!(app.session.tool_id(), "eyedropper", "the actual panel button arms sampling"); + let view = app.view_info(); + canvas::dispatch(app, &PointerEvent::new(PointerKind::Down, point.x, point.y), view); + settle(app, ctx); +} + +#[test] +fn samples_original_trace_pixels_without_painting() { + let (mut app, ctx) = fixture(true, [37; 3], false); + let point = source_point(&app, 0.25); + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + click_control(&mut app, &ctx, SAMPLE_TIP); + assert_eq!(app.session.tool_id(), "eyedropper"); + let at = canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), ctx.zoom_factor()).to_screen(point); + assert!(app.canvas_rect.unwrap().contains(at)); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![Event::PointerMoved(at), press(true)]).textures_delta.clear(); + frame(&mut app, &ctx, vec![press(false)]).textures_delta.clear(); + settle(&mut app, &ctx); + assert_eq!(app.session.tool_id(), "selection"); + assert_eq!(app.session.paint, paint); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document, "Preview off leaves the document unchanged"); + assert_eq!(state.selection, selection); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + click_control(&mut app, &ctx, "Trace"); + assert_eq!(settings(&app)["params"]["ignoreColor"], "#252525", "persist the original gray, not the black tracing result"); +} + +#[test] +fn colored_placed_image_and_live_trace_keep_preview_off_drafts_until_trace() { + for live_trace in [false, true] { + let (mut app, ctx) = fixture(live_trace, [37, 83, 149], false); + let point = source_point(&app, 0.25); + let id = selected(&app).id; + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + sample(&mut app, &ctx, point); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document, "placed/live={live_trace}: sample only the panel draft"); + assert_eq!(state.selection, selection); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert_eq!(app.session.paint, paint); + app.run("select.none", json!({})).unwrap(); + settle(&mut app, &ctx); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + settle(&mut app, &ctx); + click_control(&mut app, &ctx, "Trace"); + assert_eq!(settings(&app)["params"]["ignoreColor"], "#255395", "the raw non-gray draft survives the selection round trip"); + assert_eq!(settings(&app)["preset"], "Custom"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history.0 + 1, "Trace creates the only edit"); + } +} + +#[test] +fn preview_traces_once_and_undo_redo_restore_the_results() { + let (mut app, ctx) = fixture(true, [37, 83, 149], true); + let point = source_point(&app, 0.25); + let state = app.session.active().unwrap(); + let (before, selection, steps) = (state.doc.clone(), state.selection.clone(), state.history.undo.len()); + let paint = app.session.paint.clone(); + let view = selected(&app).trace_view(); + sample(&mut app, &ctx, point); + let after = app.session.active().unwrap().doc.clone(); + assert_ne!(after, before); + assert_eq!(settings(&app)["params"]["ignoreColor"], "#255395"); + assert_eq!(settings(&app)["preset"], "Custom"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); + // The existing imageTrace.make replaces the trace group and selects its new ID. + // Keep the logical trace selected, rather than requiring the removed group's ID. + let mut traced_selection = selection.clone(); + traced_selection.set([selected(&app).id]); + assert_eq!(app.session.active().unwrap().selection, traced_selection); + assert!(after.node(selection.objects[0]).is_none()); + assert_eq!(app.session.paint, paint); + assert_eq!(selected(&app).trace_view(), view); + assert_eq!(app.session.tool_id(), "selection"); + settle(&mut app, &ctx); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "later frames do not retrace"); + app.run("edit.undo", json!({})).unwrap(); + settle(&mut app, &ctx); + assert_eq!(app.session.active().unwrap().doc, before); + assert_eq!(app.session.active().unwrap().selection, selection); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + app.run("edit.redo", json!({})).unwrap(); + settle(&mut app, &ctx); + assert_eq!(app.session.active().unwrap().doc, after); + assert_eq!(app.session.active().unwrap().selection, traced_selection); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); +} + +#[test] +fn miss_escape_and_explicit_tool_choice_do_not_sample_or_paint() { + for exit in ["outside", "escape", "rectangle", "eyedropper"] { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let old_color = settings(&app)["params"]["ignoreColor"].clone(); + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + click_control(&mut app, &ctx, SAMPLE_TIP); + assert_eq!(app.session.tool_id(), "eyedropper"); + match exit { + "outside" => { + let view = app.view_info(); + canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Down, -100.0, -100.0), view); + } + "escape" => { + let key = |pressed| Event::Key { + key: egui::Key::Escape, + physical_key: Some(egui::Key::Escape), + pressed, + repeat: false, + modifiers: egui::Modifiers::NONE, + }; + // Full public input path: claims/ends are observed before tool_key, and + // Escape's requests are applied only if the tool claims the key. + frame(&mut app, &ctx, vec![key(true)]).textures_delta.clear(); + frame(&mut app, &ctx, vec![key(false)]).textures_delta.clear(); + } + chosen => app.select_tool(chosen), + } + let expected = if exit == "outside" || exit == "escape" { "selection" } else { exit }; + assert_eq!(app.session.tool_id(), expected, "{exit}: restore or respect the explicit choice"); + assert!(app.session.tool_options_of("eyedropper")["imageTraceIgnoreColor"].is_null()); + settle(&mut app, &ctx); + assert!(app.canvas.key.as_ref().unwrap().trace_source.is_none()); + assert_eq!(app.session.paint, paint); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document); + assert_eq!(state.selection, selection, "{exit}: Escape does not fall through to deselect"); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + click_control(&mut app, &ctx, "Trace"); + assert_eq!(settings(&app)["params"]["ignoreColor"], old_color, "{exit}: no hidden draft color was sampled"); + } +} + +#[test] +fn stale_target_click_is_consumed_before_the_restored_tool_can_select_or_paint() { + for invalidation in ["selection", "document", "revision_round_trip"] { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let point = source_point(&app, 0.25); + let old_document = app.session.active().unwrap().doc.clone(); + let old_uid = app.session.active().unwrap().uid; + let armed_revision = app.session.active().unwrap().revision; + click_control(&mut app, &ctx, SAMPLE_TIP); + match invalidation { + "selection" => { + app.run("select.none", json!({})).unwrap(); + } + "document" => { + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + } + _ => { + app.run("imageTrace.setView", json!({"view": TraceView::Outlines.id()})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc, old_document); + assert_ne!(app.session.active().unwrap().revision, armed_revision); + } + } + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + // No UI refresh intervenes: this must exercise the real dispatch stale-Down guard. + let view = app.view_info(); + canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Down, point.x, point.y), view); + assert_eq!(app.session.tool_id(), "selection", "{invalidation}: restore prior tool"); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document); + assert_eq!(state.selection, selection, "the stale click cannot reselect the source"); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert_eq!(app.session.paint, paint); + assert_eq!(app.session.documents().iter().find(|d| d.uid == old_uid).unwrap().doc, old_document); + settle(&mut app, &ctx); + assert!(app.canvas.key.as_ref().unwrap().trace_source.is_none()); + } +} + +#[test] +fn a_stale_sampler_and_canvas_press_in_one_frame_do_not_reselect_the_source() { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let point = source_point(&app, 0.25); + let target = selected(&app).id; + click_control(&mut app, &ctx, SAMPLE_TIP); + app.run("select.none", json!({})).unwrap(); + // The last real layout supplies the canvas rect and view. Canvas itself records this + // context's zoom_factor as its UI-coordinate scale before routing input. + let at = canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), ctx.zoom_factor()).to_screen(point); + assert!(app.canvas_rect.unwrap().contains(at)); + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![Event::PointerMoved(at), press(true)]).textures_delta.clear(); + assert_eq!(app.session.tool_id(), "selection"); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document); + assert_eq!(state.selection, selection, "the press in the cancellation frame is consumed"); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert_eq!(app.session.paint, paint); + frame(&mut app, &ctx, vec![press(false)]).textures_delta.clear(); + assert!(app.session.active().unwrap().selection.objects.is_empty()); + // Positive control: the same ordinary, unarmed click really hits and selects this trace. + frame(&mut app, &ctx, vec![Event::PointerMoved(at), press(true)]).textures_delta.clear(); + frame(&mut app, &ctx, vec![press(false)]).textures_delta.clear(); + assert_eq!(app.session.active().unwrap().selection.objects, vec![target]); +} + +fn capture_canvas(app: &mut VectorcraftApp, ctx: &egui::Context) -> (vectorcraft_render::Rendered, CacheKey) { + app.canvas.key = None; // force a complete upload, not a partial delta requiring reconstruction + let mut out = frame(app, ctx, vec![]); + let id = app.canvas.texture.as_ref().expect("real canvas texture").id(); + let upload = + out.textures_delta.set.iter().find(|(texture, _)| **texture == id).and_then(|(_, updates)| updates.last()).expect("CPU canvas upload"); + assert!(upload.pos.is_none()); + let egui::ImageData::Color(image) = &upload.image; + let rendered = vectorcraft_render::Rendered { + width: image.width() as u32, + height: image.height() as u32, + pixels: image.pixels.iter().flat_map(|c| c.to_array()).collect(), + }; + let key = app.canvas.key.as_ref().unwrap().clone(); + out.textures_delta.clear(); + (rendered, key) +} + +fn pixel_at(image: &vectorcraft_render::Rendered, key: &CacheKey, point: Point) -> [u8; 4] { + assert!(key.pixel.is_none() && key.rot == 0.0, "fixture uses the ordinary unrotated canvas"); + let x = (f64::from(image.width) * 0.5 + (point.x - key.cx) * key.zoom * f64::from(key.ppp)).floor(); + let y = (f64::from(image.height) * 0.5 + (point.y - key.cy) * key.zoom * f64::from(key.ppp)).floor(); + assert!(x >= 0.0 && x < f64::from(image.width) && y >= 0.0 && y < f64::from(image.height)); + let at = ((y as usize * image.width as usize) + x as usize) * 4; + image.pixels[at..at + 4].try_into().unwrap() +} + +#[test] +fn actual_canvas_shows_original_while_armed_then_restores_the_stored_view() { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let point = source_point(&app, 0.25); + let control = source_point(&app, 0.75); + let target: NodeId = selected(&app).id; + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let uid = state.uid; + let original = state.doc.node(target).unwrap().children().unwrap()[0].clone(); + assert!(!original.visible, "the live trace retains its hidden original"); + let NodeKind::Image(image) = &original.kind else { panic!("original image") }; + let blob = state.doc.images.get(&image.key).unwrap(); + assert_eq!( + blob.sample_object(f64::from(image.width) * 0.25, f64::from(image.height) * 0.5, (image.width, image.height), 1), + Some([37, 83, 149, 255]) + ); + let source_hash = blob.content_key(); + let stored = settings(&app); + let (before, before_key) = capture_canvas(&mut app, &ctx); + assert_eq!(pixel_at(&before, &before_key, point), [0, 0, 0, 255]); + assert_eq!(pixel_at(&before, &before_key, control), [255; 4]); + click_control(&mut app, &ctx, SAMPLE_TIP); + let (armed, armed_key) = capture_canvas(&mut app, &ctx); + assert!(!ctx.input(|i| i.pointer.any_down()), "the source remains visible after releasing the button"); + assert_eq!(armed_key.trace_source.as_deref().map(Vec::as_slice), Some([target].as_slice())); + assert_eq!(pixel_at(&armed, &armed_key, point), [37, 83, 149, 255]); + assert_eq!(pixel_at(&armed, &armed_key, control), [255; 4]); + app.select_tool("selection"); + let (restored, restored_key) = capture_canvas(&mut app, &ctx); + assert!(restored_key.trace_source.is_none()); + assert_eq!(restored.pixels, before.pixels, "the exact stored result returns"); + let state = app.session.active().unwrap(); + assert_eq!((state.uid, state.revision), (uid, revision)); + assert_eq!(state.doc, document); + assert_eq!(state.selection, selection); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + if let Some(dir) = std::env::var_os("VECTORCRAFT_TRACE_SAMPLER_EVIDENCE") { + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).unwrap(); + for (name, image) in [("before.png", &before), ("armed.png", &armed), ("restored.png", &restored)] { + std::fs::write(dir.join(name), image.to_png().unwrap()).unwrap(); + } + let binding = json!({"doc": uid, "target": target.0, "revision": revision, "storedTrace": stored, "sourceContentKey": source_hash, + "point": [point.x,point.y], "controlPoint": [control.x,control.y], "width": before.width, "height": before.height, + "before": pixel_at(&before,&before_key,point), "armed": pixel_at(&armed,&armed_key,point), "restored": pixel_at(&restored,&restored_key,point), + "sourceIdsWhileArmed": [target.0], "undoRedoLengths": [history.0,history.1], "documentUnchanged": true, + "view": {"zoom":before_key.zoom,"center":[before_key.cx,before_key.cy],"rotation":before_key.rot,"pixelsPerPoint":before_key.ppp}}); + std::fs::write(dir.join("binding.json"), serde_json::to_vec_pretty(&binding).unwrap()).unwrap(); + } +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 17a00368b5..f4dd29c4f7 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -416,6 +416,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. A live trace shows its source temporarily without changing View. The existing color picker remains available. Preview off keeps a draft; Preview on retraces a live trace as one undo step. A sample, Escape or a miss restores the previous tool; changing the target cancels. Paint defaults and selection are retained. `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 | @@ -560,6 +561,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Image Trace: Ignore Color samples original image pixels with a canvas eyedropper, retaining the manual picker, Preview drafts, source View and Undo behavior (#8068). Scores and estimates unchanged. | | 2026-11-16 | minor | 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. | | 2026-11-16 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028). 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. | From cf704663684e0736942870028bc63581a8add245 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 04:02:27 -0800 Subject: [PATCH 04/34] #8068: keep missed color picks armed and preserve the displayed trace --- crates/tools/src/xform/eyedropper.rs | 30 ++--- crates/ui-egui/src/canvas.rs | 3 +- crates/ui-egui/src/panels/image_trace.rs | 30 +++-- .../tests/image_trace_ignore_sampler.rs | 118 +++++++++++++----- docs/roadmap.md | 5 +- docs/target-app-parity.md | 6 +- docs/ui-parity.md | 5 +- 7 files changed, 134 insertions(+), 63 deletions(-) diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 8e0c1bd80b..ac5465942b 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -21,7 +21,8 @@ //! armed, Escape is left to the application. //! //! Image Trace's Ignore Color eyedropper passes its bound document point to the panel, which -//! samples the original image pixels; this tool changes neither paint nor selection. +//! samples the original image pixels and ends the pick only when a color is accepted. A miss +//! stays armed; this tool changes neither paint nor selection. use std::collections::HashSet; @@ -470,12 +471,10 @@ impl Tool for EyedropperTool { if ev.kind != PointerKind::Down { return vec![]; } - if let Some(binding) = self.image_trace_ignore_color.take() { - let back = self.stop.take().unwrap_or_else(|| "selection".to_string()); - return vec![ - Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "point": [ev.pos.x, ev.pos.y] })), - Action::SwitchTool(back), - ]; + if let Some(binding) = &self.image_trace_ignore_color { + // The panel knows whether this hits an opaque source pixel. It clears the binding + // and restores the previous tool only after accepting a color, not on a miss. + return vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "point": [ev.pos.x, ev.pos.y] }))]; } let opts = sample_options(cx); if self.brush_key_color { @@ -726,7 +725,7 @@ mod tests { } #[test] - fn image_trace_sampling_forwards_its_binding_and_document_point_once() { + fn image_trace_sampling_keeps_forwarding_its_binding_until_the_panel_accepts_a_color() { let (d, id) = doc_with_rect(); let (s, p) = (Selection::default(), paint()); let cx = cx(&d, &s, &p); @@ -740,14 +739,17 @@ mod tests { assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, -25.5, 400.25)).is_empty()); assert_eq!( t.pointer(&cx, &PointerEvent::new(PointerKind::Down, -25.5, 400.25).with_mods(mods)), - vec![ - Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "point": [-25.5, 400.25]})), - Action::SwitchTool("gradient".into()), - ] + vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "point": [-25.5, 400.25]}))] ); + assert_eq!(t.options()["imageTraceIgnoreColor"], binding, "a point is only a request until the panel accepts its source color"); + assert_eq!(t.options()["stop"], "gradient"); + assert!(t.claims_key(&cx, ToolKey::Escape)); + assert!(t.ends_on_escape(&cx)); + let next = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 20.0)); + assert_eq!(next, vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "point": [10.0, 20.0]}))]); + t.set_option("imageTraceIgnoreColor", &Value::Null); + t.set_option("stop", &Value::Null); assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false})); - assert!(!t.claims_key(&cx, ToolKey::Escape)); - assert!(!t.ends_on_escape(&cx)); assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index a30b5a3053..7b879fc646 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -643,8 +643,7 @@ fn cache_key( rich_black: app.session.prefs.black_on_screen == "rich", // A tool's drag on the canvas, during an interaction (not a dialog's preview). dragging: app.session.in_interaction() && ui.data(|d| d.get_temp::(drag_id())) == Some(Drag::Tool), - // The sampler keeps its bound original visible between clicks, independently of the eye. - trace_source: crate::panels::image_trace::ignore_sampler_source(app, st.uid).or_else(|| app.ui.trace_hold_source.clone()), + trace_source: app.ui.trace_hold_source.clone(), // Preferences › Performance › Use Monitor Profile for Canvas. display: app.display_profile.key(app.session.prefs.monitor_profile_display), backdrop: backdrop(app, st, app.outline_view()), diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index f73257f0d2..a453e4f136 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -272,7 +272,7 @@ pub(crate) fn cancel_ignore_sampler(app: &mut VectorcraftApp, restore: bool) { } } -/// Also runs when the panel is closed: document changes and tool changes end the source preview. +/// Also runs when the panel is closed: document changes and tool changes end the pick. pub(crate) fn refresh_ignore_sampler(app: &mut VectorcraftApp) -> bool { let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return false }; if !sampler_valid(app, s) { @@ -296,12 +296,6 @@ pub(crate) fn discard_stale_ignore_click(app: &mut VectorcraftApp) -> bool { true } -/// Render the bound live trace's original without changing its stored View or the eye's hold. -pub(crate) fn ignore_sampler_source(app: &VectorcraftApp, doc: u64) -> Option>> { - let s = app.ui.trace_ignore_sampler.as_ref()?; - (s.doc == doc && sampler_valid(app, s) && sampler_tool_active(app, s) && target(app).0).then(|| Arc::new(vec![s.target])) -} - fn start_ignore_sampler(app: &mut VectorcraftApp, ctx: &egui::Context) { if app.ui.trace_ignore_sampler.is_some() { cancel_ignore_sampler(app, true); @@ -347,21 +341,28 @@ fn sampled_ignore_color(app: &VectorcraftApp, s: &crate::state::TraceIgnoreSampl (alpha != 0).then(|| format!("#{r:02x}{g:02x}{b:02x}")) } -/// Handle the one-shot tool's reply after it has consumed its transient binding. +/// A miss keeps the pick armed; only a valid source color, Escape or invalid binding ends it. pub(crate) fn apply_ignore_color_sample(app: &mut VectorcraftApp, p: &Value) { let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return }; if p["binding"] != sampler_binding(s) { return; } - let valid = sampler_valid(app, s); - let s = s.clone(); - cancel_ignore_sampler(app, false); - if !valid || p["cancel"] == true { + if p["cancel"] == true { + // Escape already carries its one deferred SwitchTool request. + cancel_ignore_sampler(app, false); return; } - let Some(color) = sampled_ignore_color(app, &s, p) else { return }; + if !sampler_valid(app, s) { + cancel_ignore_sampler(app, true); + return; + } + // Outside the source or over a transparent pixel there is no color to accept. Keep the + // binding and previous tool so the next canvas click can still complete this pick. + let Some(color) = sampled_ignore_color(app, s, p) else { return }; + let s = s.clone(); // The canvas UI establishes this context before a real panel click can arm the sampler. let Some(ctx) = app.ui_ctx.clone() else { return }; + cancel_ignore_sampler(app, false); let all = presets(app, &ctx); let mut st: TraceUi = pstate(&ctx, "image-trace"); let (is_trace, _, stored) = target(app); @@ -379,6 +380,9 @@ pub(crate) fn apply_ignore_color_sample(app: &mut VectorcraftApp, p: &Value) { } set_pstate(&ctx, "image-trace", st); ctx.request_repaint(); + // The old deferred SwitchTool ran after the panel accepted the color. Keep that order and + // fresh tool choice; a miss above has no switch request and remains armed. + app.select_tool(&s.back); } /// The selected Image Trace object's View row (Control bar, Properties). diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs index 3c7051fab2..edd197195d 100644 --- a/crates/ui-egui/tests/image_trace_ignore_sampler.rs +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -62,10 +62,24 @@ fn click_control(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { } fn fixture(live_trace: bool, rgb: [u8; 3], preview: bool) -> (VectorcraftApp, egui::Context) { + fixture_with_transparent_edge(live_trace, rgb, preview, false) +} + +fn fixture_with_transparent_edge(live_trace: bool, rgb: [u8; 3], preview: bool, transparent: bool) -> (VectorcraftApp, egui::Context) { vectorcraft_ui_egui::i18n::set_current(vectorcraft_ui_egui::i18n::Lang::EN); let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let pixels: Vec = (0..400).flat_map(|i| if i % 20 < 10 { [rgb[0], rgb[1], rgb[2], 255] } else { [255; 4] }).collect(); + let pixels: Vec = (0..400) + .flat_map(|i| { + if transparent && i % 20 == 19 { + [0; 4] + } else if i % 20 < 10 { + [rgb[0], rgb[1], rgb[2], 255] + } else { + [255; 4] + } + }) + .collect(); let image = craft_image_codecs::Image::from_raw(20, 20, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, pixels).unwrap(); let png = craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); @@ -124,6 +138,14 @@ fn sample(app: &mut VectorcraftApp, ctx: &egui::Context, point: Point) { settle(app, ctx); } +fn press_armed_canvas(app: &mut VectorcraftApp, ctx: &egui::Context, point: Point) { + assert_eq!(app.session.tool_id(), "eyedropper", "this is a continuation of the existing armed pick"); + let view = app.view_info(); + canvas::dispatch(app, &PointerEvent::new(PointerKind::Down, point.x, point.y), view); + canvas::dispatch(app, &PointerEvent::new(PointerKind::Up, point.x, point.y), view); + settle(app, ctx); +} + #[test] fn samples_original_trace_pixels_without_painting() { let (mut app, ctx) = fixture(true, [37; 3], false); @@ -217,8 +239,8 @@ fn preview_traces_once_and_undo_redo_restore_the_results() { } #[test] -fn miss_escape_and_explicit_tool_choice_do_not_sample_or_paint() { - for exit in ["outside", "escape", "rectangle", "eyedropper"] { +fn escape_and_explicit_tool_choice_do_not_sample_or_paint() { + for exit in ["escape", "rectangle", "eyedropper"] { let (mut app, ctx) = fixture(true, [37, 83, 149], false); let old_color = settings(&app)["params"]["ignoreColor"].clone(); let state = app.session.active().unwrap(); @@ -228,10 +250,6 @@ fn miss_escape_and_explicit_tool_choice_do_not_sample_or_paint() { click_control(&mut app, &ctx, SAMPLE_TIP); assert_eq!(app.session.tool_id(), "eyedropper"); match exit { - "outside" => { - let view = app.view_info(); - canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Down, -100.0, -100.0), view); - } "escape" => { let key = |pressed| Event::Key { key: egui::Key::Escape, @@ -247,7 +265,7 @@ fn miss_escape_and_explicit_tool_choice_do_not_sample_or_paint() { } chosen => app.select_tool(chosen), } - let expected = if exit == "outside" || exit == "escape" { "selection" } else { exit }; + let expected = if exit == "escape" { "selection" } else { exit }; assert_eq!(app.session.tool_id(), expected, "{exit}: restore or respect the explicit choice"); assert!(app.session.tool_options_of("eyedropper")["imageTraceIgnoreColor"].is_null()); settle(&mut app, &ctx); @@ -263,6 +281,55 @@ fn miss_escape_and_explicit_tool_choice_do_not_sample_or_paint() { } } +#[test] +fn outside_and_transparent_misses_stay_armed_until_an_opaque_source_pixel_is_picked() { + for live_trace in [false, true] { + let (mut app, ctx) = fixture_with_transparent_edge(live_trace, [37, 83, 149], false, true); + let hit = source_point(&app, 0.25); + let outside = source_point(&app, -0.25); + let transparent = source_point(&app, 0.975); + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + let node = selected(&app); + let original = if live_trace { node.children().unwrap()[0].as_ref() } else { &node }; + let NodeKind::Image(image) = &original.kind else { panic!("original fixture image") }; + let blob = &state.doc.images[&image.key]; + let keep = |_: f64, _: f64| true; + assert_eq!( + blob.sample_pixels(&[(Some([0.95, 0.5, 1.0, 0.55]), 1, &keep)]), + Some(vec![vec![[0; 4]]]), + "the missed point is really transparent in the source" + ); + assert!(blob.sample_object(19.5, 10.0, (image.width, image.height), 1).is_none(), "a transparent source pixel has no color to pick"); + click_control(&mut app, &ctx, SAMPLE_TIP); + let binding = app.session.tool_options()["imageTraceIgnoreColor"].clone(); + assert!(!binding.is_null()); + for miss in [outside, transparent] { + press_armed_canvas(&mut app, &ctx, miss); + assert_eq!(app.session.tool_id(), "eyedropper", "live={live_trace}: a miss stays armed"); + assert!(app.ui.trace_ignore_sampler.is_some()); + assert_eq!(app.session.tool_options()["imageTraceIgnoreColor"], binding); + assert_eq!(app.session.tool_options()["stop"], "selection"); + assert_eq!(app.session.paint, paint); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document); + assert_eq!(state.selection, selection); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + } + press_armed_canvas(&mut app, &ctx, hit); + assert_eq!(app.session.tool_id(), "selection", "the valid pick restores the previous tool"); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert!(app.session.tool_options_of("eyedropper")["imageTraceIgnoreColor"].is_null()); + assert_eq!(app.session.paint, paint); + assert_eq!(app.session.active().unwrap().doc, document, "Preview off keeps the accepted color in the draft"); + click_control(&mut app, &ctx, "Trace"); + assert_eq!(settings(&app)["params"]["ignoreColor"], "#255395", "the next valid source pixel completes the same armed pick"); + } +} + #[test] fn stale_target_click_is_consumed_before_the_restored_tool_can_select_or_paint() { for invalidation in ["selection", "document", "revision_round_trip"] { @@ -366,7 +433,7 @@ fn pixel_at(image: &vectorcraft_render::Rendered, key: &CacheKey, point: Point) } #[test] -fn actual_canvas_shows_original_while_armed_then_restores_the_stored_view() { +fn actual_canvas_keeps_its_displayed_view_while_the_original_pixels_are_sampled() { let (mut app, ctx) = fixture(true, [37, 83, 149], false); let point = source_point(&app, 0.25); let control = source_point(&app, 0.75); @@ -383,39 +450,34 @@ fn actual_canvas_shows_original_while_armed_then_restores_the_stored_view() { blob.sample_object(f64::from(image.width) * 0.25, f64::from(image.height) * 0.5, (image.width, image.height), 1), Some([37, 83, 149, 255]) ); - let source_hash = blob.content_key(); let stored = settings(&app); let (before, before_key) = capture_canvas(&mut app, &ctx); assert_eq!(pixel_at(&before, &before_key, point), [0, 0, 0, 255]); assert_eq!(pixel_at(&before, &before_key, control), [255; 4]); click_control(&mut app, &ctx, SAMPLE_TIP); let (armed, armed_key) = capture_canvas(&mut app, &ctx); - assert!(!ctx.input(|i| i.pointer.any_down()), "the source remains visible after releasing the button"); - assert_eq!(armed_key.trace_source.as_deref().map(Vec::as_slice), Some([target].as_slice())); - assert_eq!(pixel_at(&armed, &armed_key, point), [37, 83, 149, 255]); + assert!(!ctx.input(|i| i.pointer.any_down()), "the button press has ended"); + assert_eq!(armed_key.trace_source, before_key.trace_source, "arming does not override the existing eye hold or trace View"); + assert_eq!(armed.pixels, before.pixels, "sampling original pixels does not change the displayed tracing result"); + assert_eq!(pixel_at(&armed, &armed_key, point), [0, 0, 0, 255]); assert_eq!(pixel_at(&armed, &armed_key, control), [255; 4]); - app.select_tool("selection"); + press_armed_canvas(&mut app, &ctx, point); + assert_eq!(app.session.tool_id(), "selection"); let (restored, restored_key) = capture_canvas(&mut app, &ctx); assert!(restored_key.trace_source.is_none()); - assert_eq!(restored.pixels, before.pixels, "the exact stored result returns"); + assert_eq!(restored.pixels, before.pixels, "the valid Preview-off pick leaves the displayed result unchanged"); + assert_eq!(settings(&app), stored, "the stored View and trace settings are unchanged"); let state = app.session.active().unwrap(); assert_eq!((state.uid, state.revision), (uid, revision)); assert_eq!(state.doc, document); assert_eq!(state.selection, selection); assert_eq!((state.history.undo.len(), state.history.redo.len()), history); - if let Some(dir) = std::env::var_os("VECTORCRAFT_TRACE_SAMPLER_EVIDENCE") { - let dir = std::path::PathBuf::from(dir); - std::fs::create_dir_all(&dir).unwrap(); - for (name, image) in [("before.png", &before), ("armed.png", &armed), ("restored.png", &restored)] { - std::fs::write(dir.join(name), image.to_png().unwrap()).unwrap(); - } - let binding = json!({"doc": uid, "target": target.0, "revision": revision, "storedTrace": stored, "sourceContentKey": source_hash, - "point": [point.x,point.y], "controlPoint": [control.x,control.y], "width": before.width, "height": before.height, - "before": pixel_at(&before,&before_key,point), "armed": pixel_at(&armed,&armed_key,point), "restored": pixel_at(&restored,&restored_key,point), - "sourceIdsWhileArmed": [target.0], "undoRedoLengths": [history.0,history.1], "documentUnchanged": true, - "view": {"zoom":before_key.zoom,"center":[before_key.cx,before_key.cy],"rotation":before_key.rot,"pixelsPerPoint":before_key.ppp}}); - std::fs::write(dir.join("binding.json"), serde_json::to_vec_pretty(&binding).unwrap()).unwrap(); - } + click_control(&mut app, &ctx, "Trace"); + assert_eq!( + settings(&app)["params"]["ignoreColor"], + "#255395", + "the source color is sampled while the canvas still shows its black tracing result" + ); } /// Cancelling while Cmd/Ctrl borrows Selection also clears the parked eyedropper's one-shot. diff --git a/docs/roadmap.md b/docs/roadmap.md index 9373b1f499..18f8f29d4e 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-17 · **Change:** minor (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: #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-17 · **Change:** minor (Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); 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: #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). > @@ -168,7 +168,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, ten generated libraries including Tech Circuit, 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, 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, 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 | | 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); 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) | 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 | @@ -212,6 +212,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Image Trace Ignore Color: sample original source pixels without changing the canvas View; outside and transparent misses keep the pick armed, while valid picks and cancellation retain the existing tool and Preview behavior (#8068). Scores, gaps and hours unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | | 2026-11-16 | minor | PDF import: fill and stroke rendering (text rendering modes 2 and 6) draws all the glyphs of a text-showing operator (`Tj`, `TJ`, `'`, `"`) filled, then the same glyphs stroked, so a word shown at once came in as two type objects: a stroke-only copy over a fill-only one. Each stroke is now matched, in order, to the glyph filled with the same placement (where, how large, how wide, slanted and turned) in the same font with the same text on the line, and only that glyph takes the stroke, so the word comes in as one type object, filled and stroked; glyphs stroked with another join part way through still split into runs of their own, and stroked type over no filled glyph (modes 1 and 5) stays stroke only (#8015; `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`, `a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type` in `crates/pdf/src/tests/text_placement.rs`). Scores and estimates unchanged. | | 2026-11-16 | minor | M1: rows or the selected-art square dragged over the Layers panel's list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 12c9a707d1..76fd58b282 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-17 · **Change:** minor (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: #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-17 · **Change:** minor (Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); 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: #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). > @@ -261,7 +261,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 and Weather Icons 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 | | 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 and Weather Icons 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) | +| 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) | | 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, 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); 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 | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | @@ -1613,6 +1613,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, 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. @@ -2776,6 +2777,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Image Trace Ignore Color: sample original source pixels without changing the canvas View; outside and transparent misses keep the pick armed, while valid picks and cancellation retain the existing tool and Preview behavior (#8068). Scores, gaps and hours unchanged. | | 2026-11-16 | minor | Layers panel: rows or the selected-art square dragged over the list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | | 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | | 2026-11-16 | minor | Properties panel: while the Type tool edits text, the Character section shows the font family and style and the Variable Font button of the first selected character (or of the character before the caret), not those of the text object's first run (#8189). Evidence: `panels::properties::tests::character_section_shows_the_type_tool_selections_style`. Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 9c7ad9e16f..21f8e6d45d 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 (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: #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-17 · **Change:** minor (Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); 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: #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). > @@ -421,7 +421,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. A live trace shows its source temporarily without changing View. The existing color picker remains available. Preview off keeps a draft; Preview on retraces a live trace as one undo step. A sample, Escape or a miss restores the previous tool; changing the target 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. `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 | @@ -566,6 +566,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Image Trace Ignore Color: sample original source pixels without changing the canvas View; outside and transparent misses keep the pick armed, while valid picks and cancellation retain the existing tool and Preview behavior (#8068). Scores, gaps and hours unchanged. | | 2026-11-16 | minor | Image Trace: Ignore Color samples original image pixels with a canvas eyedropper, retaining the manual picker, Preview drafts, source View and Undo behavior (#8068). Scores and estimates unchanged. | | 2026-11-16 | minor | 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. | | 2026-11-16 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028). Scores and estimates unchanged. | From 2d156c1bbe96ed59ec1d593d95aeeaf567c6120e Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Tue, 17 Nov 2026 20:15:20 +0100 Subject: [PATCH 05/34] #8188: a head that stays put no longer settles a moving head's placement When both placements give the drawn art's bounds, the tie is decided by the head that moves most between them, not the one that moves least: a start head that runs its line to its tip (a stop of 0) left an end head that moves 4 pt placed on the end. --- crates/eps/src/import/ai/read/ops.rs | 14 ++++++++------ crates/eps/src/import/ai/tests.rs | 23 +++++++++++++++++++++++ docs/file-format-parity.md | 2 +- 3 files changed, 32 insertions(+), 7 deletions(-) diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 4f063bbeec..4562c06507 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1407,17 +1407,19 @@ fn painted_bounds(object: &Node, appearance: &Appearance) -> Option { /// object the look's bounds within a quarter of the least distance a head moves between the two /// (at least 0.05 pt, at most 0.5 pt). `None` /// when neither does (the file draws the heads elsewhere: on other subpaths, say), or when both do -/// and the heads move 0.2 pt or more between them (the bounds can't tell which the file draws). +/// and any head moves 0.2 pt or more between them (the bounds can't tell which the file draws). fn heads_placed(object: &Node, look: &Node, mut appearance: Appearance, space: Affine) -> Option { let k = space.determinant().abs().sqrt(); let k = if k.is_finite() && k > 0.0 { k } else { 1.0 }; - // How far each head moves between the placements: its line's length under it. - let mut shift = f64::INFINITY; + // How far each head moves between the placements (its line's length under it): the least and + // the most. + let (mut shift, mut most) = (f64::INFINITY, 0.0f64); for item in &appearance.items { let AppearanceItem::Stroke(s) = item else { continue }; for (head, end) in [(&s.start_arrow, false), (&s.end_arrow, true)] { if let Some(Arrowhead::Custom(c)) = head { - shift = shift.min(c.stop() * s.arrow_weight(end) * k); + let moves = c.stop() * s.arrow_weight(end) * k; + (shift, most) = (shift.min(moves), most.max(moves)); } } } @@ -1444,10 +1446,10 @@ fn heads_placed(object: &Node, look: &Node, mut appearance: Appearance, space: A } } // Both fit when the bounds can't tell the placements apart (the end inside the bounds of the - // line's other segments), unless the heads move so little that either draws alike. + // line's other segments), unless every head moves so little that either draws alike. let align = match fits.as_slice() { [one] => *one, - [first, _] if shift < 0.2 => *first, + [first, _] if most < 0.2 => *first, _ => return None, }; for item in &mut appearance.items { diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 7d8a213f80..dc3064a2d3 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -6446,6 +6446,29 @@ fn heads_whose_placement_the_drawn_bounds_leave_open_keep_the_drawn_look() { assert!(!matches!(a[0].kind, NodeKind::Path { .. }), "the look, not the object"); } +#[test] +fn a_head_that_stays_put_leaves_a_moving_heads_placement_open() { + // The bent line of the test above, its end head moving 4 between the placements, and a start + // head whose line runs to its tip (a stop of 0), which stays put: the bounds still can't tell + // where the end head goes. + let flat = WEDGE_ART.replace("-9 0 m\n4 0 l", "-9 0 m\n8 0 l"); + let entries = format!("50 /Real (BSArrowBeginScale) ,\n/GObjRef : (Flat) /SymbolArt ; (BSArrowBeginSymbol) ,\n{END_WEDGE}"); + let path = "%_0 50 m\n%_0 0 L\n%_200 0 L\n%_200 100 L\n%_100 100 L\n%_100 50 L\n%_N\n"; + let look = + "0 G\n2 w\n0 50 m\n0 0 l\n200 0 l\n200 100 l\n100 100 l\n100 54 l\nS\n0 g\n-3 44 m\n0 50 l\n3 44 l\nf\n97 56 m\n100 50 l\n103 56 l\nf\n"; + let line = format!("0 Ae\nu\n{look}U\n{path}1 (Arrowed) XW\n"); + let file = format!( + "{}{}{}", + symbols(&format!("{}{}", symbol("Wedge", WEDGE_ART, 5), symbol("Flat", &flat, 5))), + styles_and_list(&[arrow_style("Arrowed", &entries, 2.0)], &["Arrowed"]), + layer(&line) + ); + let r = read_ok(&file); + let a = art(&r.doc); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?} {a:#?}", r.warnings); + assert!(!matches!(a[0].kind, NodeKind::Path { .. }), "the look, not the object"); +} + #[test] fn an_arrowhead_entry_without_heads_leaves_the_stroke_read() { // Only beside heads does an arrowhead entry this doesn't read keep the drawn look. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 8bbd2d46be..6bfa4b26e1 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -344,7 +344,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| -| 2026-11-16 | 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 the heads move 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` 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-16 | 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` 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-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) came in with butt caps, miter joins and a miter limit of 10 whatever the file stroked it with, while paths kept the graphics state's. The characters' stroke now takes the line cap (`J`), line join (`j`) and miter limit (`M`) of the graphics state, as a path's stroke does, and glyphs stroked with other ones start a run of their own, also a glyph filled and then stroked otherwise than the run its fill joined, so the glyphs before it keep their stroke (#7741). Test `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`. Scores and estimates unchanged. | | 2026-11-13 | minor | `.ai` and EPS import: layers that don't draw as the page, even with the drawn art of every live envelope put back, no longer put back the drawn art of every envelope of type. Each live envelope of type is weighed in the page check's own drawing of the pages it lies on, on the pixels that it and its drawn art ink there (the two drawn together on a layer of their own, without the rest of the layers; a pixel inks with an alpha above 8 of 255): it keeps its drawn art and its type, hidden, with the note, where the layers with it differ from the page in more of those pixels than its own check allows against its drawn art (10% of them, or 3% differing with all their neighbours, away from type), or where the envelopes of type that stay live, in the order they were read, would together differ there in more of a page than half of what the page check allows (a budget of the same size as the one their own checks share, kept apart from it). Art that differs elsewhere on the page no longer costs them their editable type; art that differs on their pixels still does. An envelope of type that a clip group or a clipping sublayer clips, an opacity mask masks, or a group with an appearance of its own, another envelope, a repeat or a blend holds keeps its drawn art as before, wherever it lies: drawn on its own it would be weighed elsewhere than it draws, and what holds it can draw it onto the page from off it. An envelope on no page stays live, as the page check doesn't see it, unless the page holds all the art that prints (an EPS's page that is its art's box, where art past the page is compared too): there one reaching past the page keeps its drawn art. Past 12 of them on the pages, all keep it. This holds where the editing data is trusted, where the objects that differ come in as the page's art (the placed files' other placement weighed on its own, as it draws them elsewhere under or over the envelopes; layers that draw as the page with only the envelopes the page holds put back are used as they are; where none of the objects that differ can then come in as the page's art, because an object holds type, the drawn art of every envelope of type is put back and that is tried again, as before), and for a `.ai` whose layers would open alone, which still opens alone: its envelopes of type are all settled again as they were with the page, in the same order and with the same checks, so each that opens live draws as it was weighed, and those the page held get their drawn art back. Where putting the drawn art of every live envelope back makes the layers draw as the page, it is still put back (#5065). In 224 users' files (used locally, never committed): envelopes of type that open live go from 174 to 186, in 8 files, none fewer in any file; no file changes between its layers and its PDF part; 7 renders change, by at most 0.7% of their pixels at 40 ppi (1 closer to the page, 1 alike, 5 further, by at most 0.7 of a percentage point, where VectorCraft's own envelope draws a little apart from the drawn art, within its check); the note for type in an envelope goes from 6 files. Of the 14 envelopes of type that had opened live and lost it to the page check, 2 keep their drawn art: one where the page draws something else where it is, and one in a file that comes in as its PDF part (#7141). Tests `build::candidate_tests::the_page_holds_back_only_envelopes_of_type_where_it_differs_from_them`, `envelopes_of_type_stay_live_within_half_of_what_the_page_check_allows`, `an_envelope_of_type_differing_in_more_of_its_pixels_than_its_check_allows_is_held_back`, `envelopes_of_type_the_layers_dont_draw_in_place_are_held_back`, `on_a_page_that_holds_all_the_art_an_envelope_of_type_past_it_is_held_back`, `objects_come_in_as_the_page_art_with_every_envelope_of_type_put_back_where_a_live_one_holds_a_difference`, `tests_native::layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_doesnt_hold`, `trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_page_doesnt_hold_live`, `layers_with_objects_that_come_in_as_the_page_art_keep_an_envelope_of_type_that_draws_as_the_page_live`, `trusted_layers_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `trusted_layers_leave_an_envelope_of_type_the_page_draws_otherwise_its_drawn_art`, `build::candidate_tests::the_other_placement_of_placed_files_is_weighed_on_its_own`, `layers_that_draw_as_the_page_with_the_held_envelopes_of_type_put_back_are_used_so` | | 2026-11-13 | minor | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke instead of being left out, adding no text (#6971; `empty_actual_text_keeps_the_glyphs_art` in `crates/pdf/src/tests/actual_text.rs`). Scores and estimates unchanged. | From 2abc008931c774cfd127102885bec3900bb28d83 Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Tue, 17 Nov 2026 21:12:56 +0100 Subject: [PATCH 06/34] #8188: a graphic style library reads the heads of symbols defined after its styles A library has no layers, so nothing checked the symbols after the styles and a style whose arrowhead symbol came later was dropped. Read the heads once the reader is done, as the symbols library already does. --- crates/eps/src/import/ai/read/document.rs | 2 ++ crates/eps/src/import/ai/tests.rs | 14 ++++++++++++++ docs/file-format-parity.md | 2 +- 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index d022a5168c..2f685a0a22 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -452,6 +452,8 @@ pub fn graphic_styles(data: &[u8], large_canvas: bool, names: &mut obj::Names) - r.large_canvas = large_canvas.then_some(1.0); // The styles come before the art, so an error in the art leaves them read. let _ = r.run(); + // No layer checks the symbols here: the heads of those defined after the styles. + r.read_arrowheads(); let styles = r.graphic_styles().0; let used: Vec<&str> = styles.iter().map(|s| s.name.as_str()).collect(); names.absorb_among(std::mem::take(&mut r.names), &used); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index e84054a110..b2f2000014 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -6525,6 +6525,20 @@ fn a_head_that_stays_put_leaves_a_moving_heads_placement_open() { assert!(!matches!(a[0].kind, NodeKind::Path { .. }), "the look, not the object"); } +#[test] +fn a_style_library_reads_the_heads_of_symbols_defined_after_its_styles() { + // A graphic style library has no layers, so nothing past its styles reads the heads again. + use vectorcraft_doc::Arrowhead; + let data = stream(&format!( + "%AI9_BeginArtStyles\n{}%AI9_EndArtStyles\n{}%AI9_BeginArtStyleList\n(Arrowed)\n%AI9_EndArtStyleList\n", + arrow_style("Arrowed", END_WEDGE, 2.0), + symbols(&symbol("Wedge", WEDGE_ART, 5)) + )); + let (styles, _) = graphic_styles(data.as_bytes(), false, &mut obj::Names::default()); + let stroke = styles.iter().find(|g| g.name == "Arrowed").and_then(|g| g.appearance.stroke()); + assert!(matches!(stroke.and_then(|s| s.end_arrow.as_ref()), Some(Arrowhead::Custom(h)) if h.name == "Wedge"), "{styles:?}"); +} + #[test] fn an_arrowhead_entry_without_heads_leaves_the_stroke_read() { // Only beside heads does an arrowhead entry this doesn't read keep the drawn look. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index ee1d700b19..3ee2f5491f 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -374,7 +374,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| -| 2026-11-17 | 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` 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-17 | 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-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | | 2026-11-16 | minor | PDF import: fill and stroke rendering (text rendering modes 2 and 6) draws all the glyphs of a text-showing operator (`Tj`, `TJ`, `'`, `"`) filled, then the same glyphs stroked, so a word shown at once came in as two type objects: a stroke-only copy over a fill-only one. Each stroke is now matched, in order, to the glyph filled with the same placement (where, how large, how wide, slanted and turned) in the same font with the same text on the line, and only that glyph takes the stroke, so the word comes in as one type object, filled and stroked; glyphs stroked with another join part way through still split into runs of their own, and stroked type over no filled glyph (modes 1 and 5) stays stroke only (#8015; `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`, `a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type` in `crates/pdf/src/tests/text_placement.rs`). Scores and estimates unchanged. | From 8a70231260840800fe1d7e1fa07e69214c67a00f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 14:05:53 -0800 Subject: [PATCH 07/34] Transform: Rectangle and Ellipse Properties show the shape's angle Rectangle Properties and Ellipse Properties in the Transform panel, the Properties panel and the task bar's Shape Properties popup get an Angle field, as Polygon Properties has. object.setLiveShape takes rectangleAngle and ellipseAngle: each turns the selected shapes of that kind about their own centers, keeping size, corners and pie. The field shows the angle the selected shapes of its kind share and is blank when they differ; the Polygon Properties angle reads the same way. An angle a shape already has, within rounding, records no undo step, for polygonAngle too. A value that is not a number is an error. --- crates/doc/src/node/live_shape.rs | 34 +++++++-- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/object/shape.rs | 30 +++++++- crates/engine/src/tests/livecorners.rs | 78 ++++++++++++++++++++ crates/engine/tests/command_sweep.rs | 33 +++++++++ crates/ui-egui/src/panels/transform.rs | 55 +++++++++++++- crates/ui-egui/src/panels/transform/tests.rs | 32 ++++++++ docs/mcp.md | 16 ++++ docs/target-app-parity.md | 1 + 9 files changed, 268 insertions(+), 13 deletions(-) diff --git a/crates/doc/src/node/live_shape.rs b/crates/doc/src/node/live_shape.rs index 9ddc4e1bb6..88a3e09d2d 100644 --- a/crates/doc/src/node/live_shape.rs +++ b/crates/doc/src/node/live_shape.rs @@ -144,10 +144,34 @@ impl LiveShape { /// from straight up (the Rotate field's sense). None for other shapes. pub fn polygon_angle(&self) -> Option { let LiveShape::Polygon { .. } = self else { return None }; - // No −0° or 360° from rounding: a polygon drawn upright reads 0°. + self.shape_angle() + } + /// A rectangle's, ellipse's or polygon's angle (Rectangle, Ellipse and Polygon Angle): the + /// counterclockwise degrees in [0, 360) it is turned by (the Rotate field's sense). A rectangle or + /// ellipse drawn level reads 0°, as does a polygon drawn with its first vertex straight up. None for + /// other shapes. + pub fn shape_angle(&self) -> Option { + let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. }) = self else { return None }; + // No −0° or 360° from rounding: a shape drawn level reads 0°. let a = (-self.angle_deg()).rem_euclid(360.0); Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 }) } + /// Turn a rectangle, ellipse or polygon about its center to `angle` (degrees, as + /// [`LiveShape::shape_angle`]), keeping its size, corners and pie. Nothing changes for other + /// shapes or an angle that isn't finite. + pub fn set_shape_angle(&mut self, angle: f64) { + let Some(now) = self.shape_angle() else { return }; + if !angle.is_finite() { + return; + } + let (xf, local) = match self { + LiveShape::Rectangle { w, h, xf, .. } | LiveShape::Ellipse { w, h, xf, .. } => (xf, Point::new(*w / 2.0, *h / 2.0)), + LiveShape::Polygon { xf, .. } => (xf, Point::ZERO), + LiveShape::Line { .. } | LiveShape::Path { .. } => return, + }; + let center = *xf * local; + *xf = Affine::rotate_about((now - angle).to_radians(), center) * *xf; + } /// Whether a polygon's sides are all as long: `xf` scales it evenly and doesn't shear it. True /// for other shapes. pub fn polygon_sides_equal(&self) -> bool { @@ -171,12 +195,8 @@ impl LiveShape { } /// Turn a polygon about its centre to `angle` (degrees, as [`LiveShape::polygon_angle`]). pub fn set_polygon_angle(&mut self, angle: f64) { - let Some(now) = self.polygon_angle() else { return }; - if let LiveShape::Polygon { xf, .. } = self - && angle.is_finite() - { - let centre = *xf * Point::ZERO; - *xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf; + if let LiveShape::Polygon { .. } = self { + self.set_shape_angle(angle); } } /// Make a polygon's sides equal (Make Sides Equal): drop the uneven scale and the shear from diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 0c638ceb5e..e85373323e 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -305,7 +305,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; an angle that is not a number is an error; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index b30959de99..c56f1f0ae1 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -171,6 +171,16 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { // A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal. let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?); let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true); + // A rectangle's Rectangle Angle and an ellipse's Ellipse Angle, as `polygonAngle` turns a polygon. + let (rectangle_angle, ellipse_angle) = (angle("rectangleAngle")?, angle("ellipseAngle")?); + // Whether a shape at `now` already stands at `a`: a turn the rounding of an earlier one left + // (89.999999999°, or 359.9999999999° against 0°) counts as no change. + let at_angle = |now: Option, a: f64| { + now.is_some_and(|n| { + let d = (n - a).rem_euclid(360.0); + d.min(360.0 - d) < 1e-9 + }) + }; // An ellipse's pie becomes `pie_of(pie)`. An end of 0 is a full turn (Illustrator shows a whole // ellipse as 0° to 360°). let end_of = |a: f64| if a == 0.0 { 360.0 } else { a }; @@ -187,12 +197,15 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { Some(l @ LiveShape::Polygon { sides: now, .. }) if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now)) && (!equal || l.polygon_sides_equal()) - && polygon_angle.is_none_or(|a| l.polygon_angle() == Some(a)) + && polygon_angle.is_none_or(|a| at_angle(l.polygon_angle(), a)) && side.and_then(|len| l.polygon_radius_for_side(len)).or(polygon_radius).is_none_or(|r| l.polygon_radius() == Some(r))) => { return false; } - Some(LiveShape::Ellipse { pie, .. }) if pie_of(*pie) != *pie => return false, + Some(l @ LiveShape::Ellipse { pie, .. }) if pie_of(*pie) != *pie || ellipse_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => { + return false; + } + Some(l @ LiveShape::Rectangle { .. }) if rectangle_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => return false, _ => {} } if relative_radii.is_some_and(|on| live.as_deref().map(|l| l.radii_relative()) != Some(on)) { @@ -236,9 +249,18 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } *path = l.to_path(); } - if let Some(l @ LiveShape::Ellipse { .. }) = live.as_deref_mut() - && (pie_start.is_some() || pie_end.is_some() || invert) + if let Some(a) = rectangle_angle + && let Some(l @ LiveShape::Rectangle { .. }) = live.as_deref_mut() { + l.set_shape_angle(a); + *path = l.to_path(); + } + if let Some(l @ LiveShape::Ellipse { .. }) = live.as_deref_mut() + && (pie_start.is_some() || pie_end.is_some() || invert || ellipse_angle.is_some()) + { + if let Some(a) = ellipse_angle { + l.set_shape_angle(a); + } if let LiveShape::Ellipse { pie, .. } = l { *pie = pie_of(*pie); } diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index b9e3793913..0ea4bba76a 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -524,6 +524,84 @@ fn a_polygon_takes_its_angle_radius_side_length_and_equal_sides() { } } +/// Rectangle Angle and Ellipse Angle: `rectangleAngle` and `ellipseAngle` turn each selected live +/// rectangle or ellipse about its own center, keeping its size, corners and pie, as one undo step. +/// The angle it already has records no step, each key leaves the other kind as it is, and a value +/// that is not a number is an error. +#[test] +fn a_rectangle_and_an_ellipse_take_their_angle() { + let (mut s, rect) = session(); + run(&mut s, json!({"radius": 8})); + let ellipse = NodeId(s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 120, "height": 80})).unwrap()["id"].as_u64().unwrap()); + run(&mut s, json!({"pieStart": 30, "pieEnd": 120})); + let live = |s: &Session, id: NodeId| { + let n = s.doc().unwrap().doc.node(id).unwrap(); + (n.live_shape().unwrap().clone(), n.geometric_bounds().unwrap()) + }; + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let close = |a: f64, b: f64| (a - b).abs() < 1e-6; + let angle = |s: &Session, id: NodeId| live(s, id).0.shape_angle().unwrap(); + // The ellipse's center: the middle of its untransformed box, wherever its pie leaves the path. + let ellipse_center = |s: &Session| match live(s, ellipse).0 { + LiveShape::Ellipse { w, h, xf, .. } => xf * vectorcraft_geom::Point::new(w / 2.0, h / 2.0), + l => panic!("{l:?}"), + }; + let center = ellipse_center(&s); + + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + let n = steps(&s); + run(&mut s, json!({"rectangleAngle": 90})); + let (l, b) = live(&s, rect); + assert!(close(angle(&s, rect), 90.0), "{l:?}"); + // 100 × 60 at (10, 10) turned about (60, 40): 60 wide, 100 tall, same center. + assert!(close(b.width(), 60.0) && close(b.height(), 100.0) && close(b.center().x, 60.0) && close(b.center().y, 40.0), "{b:?}"); + let LiveShape::Rectangle { w, h, radii, .. } = &l else { panic!("{l:?}") }; + assert!(close(*w, 100.0) && close(*h, 60.0) && *radii == [8.0; 4], "{w} {h} {radii:?}"); + assert_eq!(steps(&s), n + 1, "one undo step"); + for same in [json!({"rectangleAngle": 90}), json!({"rectangleAngle": 450}), json!({"rectangleAngle": -270}), json!({"ellipseAngle": 10})] { + run(&mut s, same.clone()); + assert_eq!(steps(&s), n + 1, "{same} records no undo step"); + } + // A turn the field gives back rounded is the angle the shape has: typing it again records no step. + run(&mut s, json!({"rectangleAngle": 33.3})); + let now = angle(&s, rect); + run(&mut s, json!({"rectangleAngle": now})); + run(&mut s, json!({"rectangleAngle": 33.3})); + assert_eq!(steps(&s), n + 2); + for bad in [json!({"rectangleAngle": "left"}), json!({"ellipseAngle": "up"}), json!({"rectangleAngle": true})] { + assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}"); + assert_eq!(steps(&s), n + 2, "{bad} changes nothing"); + } + + // The ellipse turns about its center and keeps its pie. + s.execute("select.set", &json!({"ids": [ellipse.0]})).unwrap(); + run(&mut s, json!({"ellipseAngle": 90})); + let (l, b) = live(&s, ellipse); + assert!(close(angle(&s, ellipse), 90.0), "{l:?}"); + let LiveShape::Ellipse { pie, .. } = &l else { panic!("{l:?}") }; + assert_eq!(*pie, (30.0, 120.0)); + let now = ellipse_center(&s); + assert!(close(now.x, center.x) && close(now.y, center.y), "{center:?} → {now:?}"); + assert!(b.width() < b.height(), "120 × 80 turned a quarter turn: {b:?}"); + + // Both selected: each key turns its own kind only, each about its own center. + s.execute("select.set", &json!({"ids": [rect.0, ellipse.0]})).unwrap(); + run(&mut s, json!({"rectangleAngle": 45})); + assert!(close(angle(&s, rect), 45.0) && close(angle(&s, ellipse), 90.0)); + let b = live(&s, rect).1; + assert!(close(b.center().x, 60.0) && close(b.center().y, 40.0), "{b:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(close(angle(&s, rect), 33.3)); + + // A reflected rectangle takes the angle too, about its center. + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap(); + let before = live(&s, rect).1.center(); + run(&mut s, json!({"rectangleAngle": 20})); + let after = live(&s, rect).1.center(); + assert!(close(angle(&s, rect), 20.0) && close(before.x, after.x) && close(before.y, after.y), "{before:?} → {after:?}"); +} + #[test] fn relative_corner_rounding_keeps_fraction_on_resize() { let (mut s, id) = session(); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index fd1edc9b77..36386dc9d9 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1256,6 +1256,39 @@ fn polygon_properties_junk() { assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); } +/// A live rectangle's and ellipse's Rectangle and Ellipse Angle with junk values, drawn plain, +/// scaled unevenly, flattened to nothing and sheared: never a panic, and the document stays sound. +#[test] +fn rectangle_and_ellipse_angle_junk() { + let mut failures = vec![]; + for (shape, key) in [("shape.rectangle", "rectangleAngle"), ("shape.ellipse", "ellipseAngle")] { + for xf in [ + None, + Some(("object.scale", json!({"sx": 300, "sy": 20}))), + Some(("object.scale", json!({"sx": 1e-300, "sy": 100}))), + Some(("object.shear", json!({"angle": 40}))), + ] { + for v in junk_values() { + let p = json!({ key: v }); + let mut s = Fixture::Multi.session(); + let Ok(_) = no_panic(s.execute(shape, &json!({"x": 60, "y": 60, "width": 80, "height": 50}))) else { continue }; + if let Some((cmd, q)) = &xf { + let _ = no_panic(s.execute(cmd, q)); + } + match catch_quiet(|| no_panic(s.execute("object.setLiveShape", &p))) { + Err(m) => failures.push(format!("PANIC object.setLiveShape {p} [{xf:?}]: {m}")), + Ok(_) => { + if let Err(e) = catch_quiet(|| check_all(&mut s)).unwrap_or_else(|m| Err(format!("panic in checks: {m}"))) { + failures.push(format!("object.setLiveShape {p} [{xf:?}]: {e}")); + } + } + } + } + } + } + assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); +} + /// The params `fuzzed_calls_keep_documents_serializable` sends `c`: each key with each of the /// first junk values, a string under a file or folder key replaced by a location inside `path`'s /// folder. diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 1bce03c53d..a2e179829f 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -426,6 +426,8 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l if headed { widgets::subheader(ui, tl!("Rectangle Properties:")); } + let fw = super::field_width(ui); + shape_angle_row(app, ui, live, &format!("{id}-rectangle"), "rectangleAngle", fw); corner_radius_row(app, ui, n, &format!("{id}-radius")); } LiveShape::Polygon { .. } => { @@ -436,6 +438,7 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l } LiveShape::Ellipse { pie, .. } => { widgets::subheader(ui, tl!("Ellipse Properties:")); + shape_angle_row(app, ui, live, &format!("{id}-ellipse"), "ellipseAngle", 60.0); pie_rows(app, ui, *pie, &format!("{id}-pie")); } _ => return false, @@ -443,6 +446,55 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l true } +/// A live rectangle's or ellipse's Angle row (Rectangle and Ellipse Angle, counterclockwise): the +/// angle the selected shapes of its kind share, blank when they differ. `key` is the +/// `object.setLiveShape` param an edit sets, which turns each of them about its own center. +fn shape_angle_row(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, id: &str, key: &str, width: f32) { + let angle = shared_shape_angle(app, ui.ctx(), live); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Angle:")); + if let Some(a) = widgets::mixed_field_named(ui, (id, "angle"), Some(tl!("Angle:")), angle, "°", 1, width) { + app.run("object.setLiveShape", json!({ key: a })).ok(); + } + }); +} + +/// The selected live shapes of `live`'s kind, the document uid and revision they were read at, and +/// the angle they share. +type SharedAngle = Option<((u64, u64, std::mem::Discriminant), Option)>; + +/// The angle ([`LiveShape::shape_angle`]) every selected live shape of `live`'s kind shares, `None` +/// when they differ or none is selected. Measured once per (document uid, revision) and kind: the +/// panels read it every frame, and Select All can select hundreds of thousands of shapes. +fn shared_shape_angle(app: &VectorcraftApp, ctx: &egui::Context, live: &LiveShape) -> Option { + let st = app.session.active()?; + let key = (st.uid, st.revision, std::mem::discriminant(live)); + if let Some((k, angle)) = pstate::(ctx, "shape-angle") + && k == key + { + return angle; + } + let mut angles = st + .selection + .objects + .iter() + .filter_map(|id| st.doc.node(*id)?.live_shape()) + .filter(|l| std::mem::discriminant(*l) == key.2) + .filter_map(LiveShape::shape_angle); + // With no shape of its kind selected, the panel shows `live`'s own angle. + let angle = match angles.next() { + None => live.shape_angle(), + Some(first) => angles + .all(|a| { + let d = (a - first).rem_euclid(360.0); + d.min(360.0 - d) < 1e-9 + }) + .then_some(first), + }; + set_pstate::(ctx, "shape-angle", Some((key, angle))); + angle +} + /// An ellipse's Pie Start and End Angle (degrees, counterclockwise from 3 o'clock; 0 to 360 is the /// whole ellipse) and Invert Pie, which shows the other part of it (Transform and Properties panels). pub(crate) fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64), id: &str) { @@ -469,6 +521,7 @@ pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live let side = radius.map(|r| 2.0 * r * (std::f64::consts::PI / f64::from((*sides).max(3))).sin()); let kind = super::corner_style(app, n).1; let kinds: Vec<&str> = CornerKind::ALL.iter().map(|k| corner_kind(*k)).collect(); + let angle = shared_shape_angle(app, ui.ctx(), live); // The `object.setLiveShape` param an edited field sets. let mut set = None; egui::Grid::new((id, "grid")).num_columns(2).spacing([6.0, 6.0]).show(ui, |ui| { @@ -478,7 +531,7 @@ pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live } ui.end_row(); widgets::dim_label(ui, tl!("Angle:")); - if let Some(a) = widgets::plain_field_named(ui, (id, "angle"), Some(tl!("Angle:")), live.polygon_angle().unwrap_or(0.0), "°", 1, fw) { + if let Some(a) = widgets::mixed_field_named(ui, (id, "angle"), Some(tl!("Angle:")), angle, "°", 1, fw) { set = Some(("polygonAngle", json!(a))); } ui.end_row(); diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index 3dff8e6a4b..83c78047e7 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -125,6 +125,38 @@ fn an_ellipse_shows_its_pie_properties() { assert!(shown.iter().any(|s| s == "30°") && shown.iter().any(|s| s == "120°"), "{shown:?}"); } +/// A live rectangle and a live ellipse show their own angle (Rectangle and Ellipse Angle) in the +/// Transform panel and the Properties panel's Transform section, apart from the Rotate field's box +/// angle, which Reset Bounding Box squares to the page. Selected shapes of one kind at different +/// angles show a blank angle. +#[test] +fn a_rectangle_and_an_ellipse_show_their_angle() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + for (shape, heading) in [("shape.rectangle", "Rectangle Properties:"), ("shape.ellipse", "Ellipse Properties:")] { + let mut ids = vec![]; + for (y, angle) in [(20, 30), (200, 60)] { + let id = app.run(shape, json!({"x": 50, "y": y, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("object.rotate", json!({"angle": angle, "absolute": true})).unwrap(); + app.run("object.resetBoundingBox", json!({})).unwrap(); + ids.push(id); + } + app.run("select.set", json!({"ids": [ids[0]]})).unwrap(); + for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section] { + let shown = texts(&mut app, draw); + for t in ["Angle:", "0°", "30°"] { + assert!(shown.iter().any(|s| s == t), "{t} in {shown:?}"); + } + } + assert!(texts(&mut app, show).iter().any(|s| s == heading), "{heading}"); + app.run("select.set", json!({"ids": ids})).unwrap(); + let shown = texts(&mut app, show); + assert!(shown.iter().any(|s| s == "Angle:") && !shown.iter().any(|s| s == "30°" || s == "60°"), "{shape}: {shown:?}"); + app.run("select.set", json!({"ids": [ids[1]]})).unwrap(); + assert!(texts(&mut app, show).iter().any(|s| s == "60°"), "{shape}"); + } +} + #[test] fn the_artboard_tool_shows_the_active_artboard() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..4dc28308c6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6490,6 +6490,22 @@ length that isn't a number above 0 is an error. An ellipse (Ellipse Properties): counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse) and `invertPie: true`, which swaps them. Each call is one undo step. +A live rectangle's Rectangle Angle and a live ellipse's Ellipse Angle are `rectangleAngle` and `ellipseAngle` +(degrees counterclockwise, 0 for a shape drawn level; any number is read modulo 360). The help page +(https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) lists +both as the shape's rotation on the canvas from 0° to 360°. The rest are VectorCraft's own rules: each selected shape +of that kind turns about its own center, keeping its size, corners and pie (an ellipse's pie turns with it), and other +objects stay as they are. The Transform and Properties panels show the angle in each shape's Properties section, blank +when the selected shapes of that kind differ. It is the shape's own angle: after Reset Bounding Box +(`object.resetBoundingBox`) the Rotate field reads 0° while the shape angle keeps the turn. An angle that is not a +number is an error and changes nothing, and the angle the shape already has records no undo step; the same holds for +`polygonAngle`, and the Polygon Properties angle is blank, too, when the selected polygons differ. + +```json +{"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"rectangleAngle":30}}} +{"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"ellipseAngle":45}}} +``` + `object.setLiveShape` returns a parameter error, and leaves the document and its undo history as they were, for a key it does not take, at the top level (`` unknown parameter `path` ``) or in one of `items` (`` unknown parameter `items[0].corner`; did you mean `items[0].corners`? ``), for a `sides` that is not a whole number diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..e910293daf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -976,6 +976,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - While a Type tool (Type, Area Type, Type on a Path and their vertical versions) adds or edits type, the contextual task bar shows the font family menu, the font style menu, the Font Size combo and the Fill chip (); the Touch Type tool shows no bar, as the same page describes. Type selected with a selection tool shows the same three font controls beside its Create Outlines, conversion and Type on a Path items (). The controls act as the Character panel's do: on the characters a Type tool selects, else on every selected type object, with the size left blank where the sizes differ. VectorCraft's own rules: a Type tool's bar leaves out the object actions, the Stroke chip, Recolor Artwork and Lock; a Type tool shows no bar before it adds type or with other art selected; type selected with other art shows no font controls; the font controls go on a second row when one row would be wider than the canvas, and narrow to fit a canvas narrower than they are; while a Type tool edits type, the Fill chip shows the edited characters' fill ("?" where it differs). Evidence: `the_type_tools_show_font_and_fill_controls`, `the_type_tools_show_no_bar_without_type`, `selected_type_shows_font_controls_beside_its_actions`, `the_task_bars_font_size_sets_what_the_character_panel_would`, `the_type_tools_fill_chip_activates_the_fill`, `the_type_tools_bar_is_named_and_stays_on_the_canvas`, `selected_types_font_controls_take_a_second_row_on_a_narrow_canvas` and `the_type_tools_fill_chip_shows_the_edited_characters_fill` in `crates/ui-egui/src/tests/taskbar.rs`. - The help page describes the contextual task bar as one horizontal row () and gives no rule for a canvas narrower than that row. VectorCraft's own rule: the bar stays whole on the canvas. When its actions don't fit in one row, they wrap, in order, onto rows under the row with the handle, the chips and More Options; an action wider than any row, or one that would need a row past the canvas's height, is listed in More Options instead; when the chips don't fit beside the handle and More Options, they take rows after the actions; with no row to spare for the font controls, the bar leaves them out; a canvas too small for the handle and More Options shows no bar. Evidence: `a_task_bars_actions_wrap_on_a_narrow_canvas` and `a_task_bar_action_wider_than_the_canvas_goes_in_more_options` in `crates/ui-egui/src/tests/taskbar.rs`. - With a live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool, the contextual task bar shows a Shape Properties button in place of Lock. It opens a popup with the shape's rows from the Transform panel (corner radius, pie angles, or sides, angle, corner and radius), which edit it through `object.setLiveShape`. The overview describes this: when a shape drawn with a shape tool (Rectangle, Star) is selected, the bar offers to change its properties where Lock Object would be ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Object › Lock and ⌘2 still lock the shape. Not done: stars, which the app draws as plain paths. Evidence: `a_basic_shape_shows_its_properties_in_place_of_lock`, `the_shape_properties_popup_edits_the_shape` and `other_selections_keep_lock` in `crates/ui-egui/src/tests/taskbar.rs`. + - Rectangle Properties and Ellipse Properties in the Transform panel, the Properties panel and the task bar's Shape Properties popup have an Angle field, as Polygon Properties does: the help page lists Rectangle Angle and Ellipse Angle as the shape's rotation on the canvas from 0° to 360° (). A typed angle turns the shape through `object.setLiveShape {rectangleAngle, ellipseAngle}`. VectorCraft's own rules: degrees counterclockwise, 0 for a shape drawn level; each selected shape of that kind turns about its own center and keeps its size, corners and pie; the field is blank when the selected shapes of that kind differ, as the Polygon Properties angle now is too; the shape keeps its angle after Reset Bounding Box squares the Rotate field's box to the page; the angle a shape already has records no undo step. Evidence: `a_rectangle_and_an_ellipse_take_their_angle` in `crates/engine/src/tests/livecorners.rs` and `a_rectangle_and_an_ellipse_show_their_angle` in `crates/ui-egui/src/panels/transform/tests.rs`. - While the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool is in use, the contextual task bar offers Edit Path (the Direct Selection tool), the Fill and Stroke chips, and Shape Properties for the shape it draws, as the help page lists for those five tools (). VectorCraft's own rules: the bar shows while one of those tools has one closed path selected whole, as right after it draws one, and not with nothing selected, several objects, a group, an open path, type or picked-out anchors; it shows nothing during the drag that draws the shape; it leaves out the selection tools' Duplicate, Offset Path, Simplify, Recolor Artwork and Lock; the Line Segment tool shows no bar. Not done: Shape Properties for a star, which the app draws as a plain path, and Gen Shape Fill and Generate Vectors, which the app doesn't have. Evidence: `shape_tools_show_edit_path_paint_and_properties_after_drawing`, `shape_tools_have_no_shape_bar_without_a_single_shape` and `shape_tool_bar_retargets_after_another_shape_and_undo` in `crates/ui-egui/src/tests/taskbar.rs`. - While the Smooth tool is in use with a path it can smooth selected (a path with three or more anchors, or two joined by a curve, on its own or inside a selected group), the contextual task bar shows the tool's Fidelity field and Tool Options…, which opens the Smooth tool's options. The overview says the Smooth tool's bar has its tool options (), and the tool's help page names Fidelity as its option (). A value typed or stepped in the field sets the tool's Fidelity through `tool.setOption`, with the same range, unit (screen pixels) and steps as the field in its options. VectorCraft's own rules: with nothing selected, or only straight lines or type selected, the tool shows no bar; the bar leaves out the selection tools' actions, the Fill and Stroke chips, Recolor Artwork and Lock; on a canvas too narrow for the field, More Options lists Fidelity, which opens the tool's options. Evidence: `the_smooth_tool_shows_fidelity_and_tool_options_for_a_path` and `the_smooth_tool_shows_no_bar_without_a_path_to_smooth` in `crates/ui-egui/src/tests/taskbar.rs`. - The contextual task bar has a Stroke chip beside the Fill chip, drawn with the paint the Stroke proxy shows (a "?" when the selected objects' strokes differ, as on the Fill chip); a click brings the Stroke proxy forward and shows the Swatches panel wherever it is docked, floating or closed, as a click on the Fill chip does for the Fill proxy. The reference app's bar has Fill and Stroke controls for changing an object's colors ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Evidence: `the_task_bar_shows_a_stroke_chip_beside_fill` and `the_task_bar_chips_follow_the_proxies_and_show_swatches_anywhere` in `crates/ui-egui/src/canvas/tests.rs`. From 0133157783ee17cf5c887867fa511b1dad4618d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 14:09:49 -0800 Subject: [PATCH 08/34] PSD import: a layer with a knockout merges with the layers below it in its group Opening a PSD or PSB file with its layers as objects now applies a layer's Knockout setting instead of only counting it in a warning. The import options help page says that layers using a Knockout option are merged with the underlying layers: https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html A layer or group inside a group whose `knko` value is 1 is read as a shallow knockout and merged with the visible layers below it in that group into one image, named after them with " + ". Where it has pixels (shaped by its layer mask), the layers below are cleared to transparency and it is drawn there at its fill opacity; its opacity then fades the result back toward the layers below. In a pass-through group the cut shows what is outside the group, and the knockout is applied only when it and the visible layers below it are in the Normal mode, so that no layer stops blending with what is outside the group. The knockouts of top-level layers, clipped layers, layers that others are clipped to, other `knko` values, and merges that would need more memory than allowed are not applied: those layers come in as before and the existing warning counts only them. A hidden knockout that would need the merge is left out, like other hidden layers that need a merge. A knockout that draws nothing, or has nothing visible below it, merges nothing and comes in as before. --- crates/engine/src/cmd/fileio/psdlayers.rs | 334 ++++++++++++++---- .../engine/src/cmd/fileio/tests_psdlayers.rs | 128 +++++++ docs/target-app-parity.md | 2 +- 3 files changed, 395 insertions(+), 69 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index cbfaa434d5..ded5288c69 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -24,14 +24,20 @@ //! Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color, Lighter Color) is merged with the //! layers below it in its group. A Dissolve layer's partly transparent pixels are merged as opaque //! or transparent, opaque at the share of its pixels their transparency gives, in a fixed pattern -//! that differs from layer to layer. When a merge's canvases would need more memory than allowed, -//! the layer comes in alone: in the Normal mode, or unclipped. -//! Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need a merge -//! (one in a mode VectorCraft lacks, one that layers are clipped to, one clipped to another, or -//! one below a merged layer) is always left out, with the layers clipped to it. Adjustment layers, -//! fill layers that store no pixels and whose fill isn't read or whose shape is a vector mask, -//! layer effects that are switched on, knockouts and vector masks aren't applied; the warnings -//! count them and the hidden layers left out. +//! that differs from layer to layer. A layer or group in a group whose Knockout setting is 1 (read +//! as a shallow knockout) is merged with the layers below it in its group too, as the import option +//! describes: where it has pixels, they are cleared to transparency and it is drawn there at its fill +//! opacity, and its opacity fades that back toward them. In a pass-through group this is done only +//! when it and the visible layers below it are in the Normal mode. When a merge's canvases would need more +//! memory than allowed, the layer comes in alone: in the Normal mode, unclipped, or without its +//! knockout. Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need +//! a merge (one in a mode VectorCraft lacks, one with a knockout in a group, one that layers are +//! clipped to, one clipped to another, or one below a merged layer) is always left out, with the +//! layers clipped to it. Adjustment layers, fill layers that store no pixels and whose fill isn't read +//! or whose shape is a vector mask, layer effects that are switched on, vector masks, and the +//! knockouts of top-level layers, of clipped layers, of layers that others are clipped to and of +//! layers in a pass-through group with a layer in another mode, and other Knockout values, aren't +//! applied; the warnings count them and the hidden layers left out. //! //! The file is untrusted: every count, length and size is checked before anything is allocated, //! groups nest at most [`MAX_DEPTH`] deep (layers deeper than a document may nest merge into the @@ -227,7 +233,9 @@ struct Record<'a> { content: Content, effects: bool, vector_mask: bool, - knockout: bool, + /// The Knockout setting's byte (`knko`): 0 none, 1 a shallow knockout. Any other value isn't + /// applied. + knockout: u8, } /// The layer records of `info` (the layer count, the records, then their channels' data). @@ -285,7 +293,7 @@ fn record<'a>(r: &mut Reader<'a>, psb: bool) -> Result<(Record<'a>, Vec<(i16, us content: Content::Pixels, effects: false, vector_mask: false, - knockout: false, + knockout: 0, }; rec.read_extra(extra, psb)?; Ok((rec, lengths)) @@ -345,8 +353,7 @@ impl Record<'_> { b"lfx2" | b"lmfx" => effects = Some(effects == Some(true) || effects_on(data)), b"lrFX" => old_effects = true, b"vmsk" | b"vsms" => self.vector_mask = true, - // Shallow or deep knockout. - b"knko" => self.knockout = data.first().is_some_and(|&k| k != 0), + b"knko" => self.knockout = data.first().copied().unwrap_or(0), k if ADJUSTMENTS.contains(&k) => self.content = Content::Adjustment, _ => {} } @@ -646,6 +653,27 @@ enum Body<'i> { Merged(Canvas), } +/// Where a layer list is. +#[derive(Clone, Copy, PartialEq)] +enum Level { + /// The file's top level. + Top, + /// An isolated group, or a group drawn on its own. + Group, + /// A pass-through group whose layers blend with what is below it. + Pass, +} + +/// What a knockout's merge with the layers below it gives. +enum Knocked { + /// The merged canvas. + Merged(Canvas), + /// Nothing below it draws, or it draws nothing: it comes in as a layer of its own. + Nothing, + /// The canvases would need more memory than allowed. + TooLarge, +} + /// A unit's body drawn alone. enum Drawn { /// It draws nothing. @@ -663,6 +691,7 @@ struct Notes { fills: usize, effects: usize, vector_masks: usize, + /// Layers whose knockout wasn't applied. knockouts: usize, /// Hidden layers left out, and layers clipped to them. hidden: usize, @@ -678,6 +707,8 @@ struct Notes { #[derive(Clone, Copy)] struct Counts { skipped: usize, + /// The knockouts counted as not applied. + unknocked: usize, merged: usize, unmerged: usize, unclipped: usize, @@ -745,8 +776,8 @@ impl Notes { out } - fn counts(&self, skipped: usize) -> Counts { - Counts { skipped, merged: self.merged.len(), unmerged: self.unmerged, unclipped: self.unclipped, clipped_out: self.clipped_out } + fn counts(&self, skipped: usize, unknocked: usize) -> Counts { + Counts { skipped, unknocked, merged: self.merged.len(), unmerged: self.unmerged, unclipped: self.unclipped, clipped_out: self.clipped_out } } } @@ -771,6 +802,10 @@ struct Builder<'a, F> { skipped: Vec, /// Those records, in the order they were counted. skip_log: Vec, + /// The records counted as knockouts not applied. + unknocked: Vec, + /// Those records, in the order they were counted. + unknock_log: Vec, /// Bytes of layer and mask pixels decoded, and of canvases the merges made, so far. spent: Cell, } @@ -920,6 +955,10 @@ impl [f32; 3]> Builder<'_, F> { Some(b) => { // Counted even when it draws nothing (an adjustment layer). self.note(i)?; + // A clipped layer's knockout isn't applied. + if self.record(i)?.knockout != 0 { + self.unknock(i); + } if !unclipped && self.clip(&mut out, b, &body, i, &name, blend, opacity)? { continue; } @@ -1048,9 +1087,9 @@ impl [f32; 3]> Builder<'_, F> { Some(n) => *n = true, None => {} } - let (content, empty, effects, vector_mask, knockout) = { + let (content, empty, effects, vector_mask) = { let rec = self.record(i)?; - (rec.content, rec.stores_nothing(), rec.effects, rec.vector_mask, rec.knockout) + (rec.content, rec.stores_nothing(), rec.effects, rec.vector_mask) }; match content { Content::Type => self.notes.types += 1, @@ -1062,10 +1101,39 @@ impl [f32; 3]> Builder<'_, F> { } self.notes.effects += usize::from(effects); self.notes.vector_masks += usize::from(vector_mask); - self.notes.knockouts += usize::from(knockout); Ok(()) } + /// Count record `i` as a layer whose knockout isn't applied (once). + fn unknock(&mut self, i: usize) { + if let Some(s) = self.unknocked.get_mut(i) + && !*s + { + *s = true; + self.notes.knockouts += 1; + self.unknock_log.push(i); + } + } + + /// Does unit `u`, at `level` above the units `below` it, take a shallow knockout this import + /// applies? Only a layer or group in a group, neither clipped nor a base of clipped layers, does; + /// in a pass-through group, only when it and the visible units below it are in the Normal mode, so + /// that none of them blends with what is below the group. Any other knockout is counted as not + /// applied. + fn knocks(&mut self, u: &Unit<'_>, below: &[Unit<'_>], level: Level) -> Result { + let rec = self.record(u.record)?; + if rec.knockout == 0 { + return Ok(false); + } + let normal = |u: &Unit<'_>| u.blend == Blend::Mode(BlendMode::Normal); + let blends_out = level == Level::Pass && !(normal(u) && below.iter().filter(|b| b.visible).all(normal)); + let applies = rec.knockout == 1 && level != Level::Top && !blends_out && !rec.clipped && !matches!(u.body, Body::Merged(_)); + if !applies { + self.unknock(u.record); + } + Ok(applies) + } + /// Count record `i` as a hidden layer left out (once). fn skip(&mut self, i: usize) { if let Some(s) = self.skipped.get_mut(i) @@ -1077,10 +1145,36 @@ impl [f32; 3]> Builder<'_, F> { } } - /// `items`' units with the layers in blend modes VectorCraft lacks merged with those below. - fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool) -> Result>, String> { + /// `items`' units, at `level`, with the layers in blend modes VectorCraft lacks, and in a group + /// the layers with a shallow knockout, merged with those below. + fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool, level: Level) -> Result>, String> { let mut out: Vec> = vec![]; for mut u in self.units(items, keep_hidden)? { + if self.knocks(&u, &out, level)? { + // A hidden layer that would need the merge is left out. + if !u.visible { + self.skip(u.record); + continue; + } + let saved = self.notes.counts(self.skip_log.len(), self.unknock_log.len()); + match self.knock(&out, &u)? { + Knocked::Merged(canvas) => { + self.take_merge(&mut out, &u, canvas); + if let Blend::Other(other) = u.blend + && !self.notes.merged.contains(&other.label()) + { + self.notes.merged.push(other.label()); + } + continue; + } + // Nothing below it, or nothing of its own, to knock out: it comes in as a layer. + Knocked::Nothing => {} + Knocked::TooLarge => { + self.restore(saved); + self.unknock(u.record); + } + } + } let Blend::Other(other) = u.blend else { out.push(u); continue; @@ -1091,7 +1185,7 @@ impl [f32; 3]> Builder<'_, F> { continue; } // A merge that can't be made counts nothing its groups would have counted. - let saved = self.notes.counts(self.skip_log.len()); + let saved = self.notes.counts(self.skip_log.len(), self.unknock_log.len()); let made = match out.as_mut_slice() { // Onto the previous merge alone: composited onto its canvas, in place. [prev] if prev.is_merge() => { @@ -1113,34 +1207,7 @@ impl [f32; 3]> Builder<'_, F> { } _ => match self.merge(&out, &u)? { Some(canvas) => { - let mut name = String::new(); - for (k, b) in out.iter_mut().filter(|b| b.visible).enumerate() { - if k == 0 { - name = std::mem::take(&mut b.name); - } else { - name.push_str(" + "); - name.push_str(&b.name); - } - } - if out.iter().any(|b| b.visible) { - name.push_str(" + "); - } - name.push_str(&u.name); - // Hidden layers below are left out with the rest. - for b in out.iter().filter(|b| !b.visible).map(|b| b.record).collect::>() { - self.skip(b); - } - out.clear(); - out.push(Unit { - name, - visible: true, - opacity: 1.0, - blend: Blend::Mode(BlendMode::Normal), - mask_of: None, - record: u.record, - body: Body::Merged(canvas), - clip: None, - }); + self.take_merge(&mut out, &u, canvas); true } None => false, @@ -1168,6 +1235,12 @@ impl [f32; 3]> Builder<'_, F> { self.notes.hidden = self.notes.hidden.saturating_sub(1); } } + for i in self.unknock_log.split_off(c.unknocked) { + if let Some(s) = self.unknocked.get_mut(i) { + *s = false; + self.notes.knockouts = self.notes.knockouts.saturating_sub(1); + } + } self.notes.merged.truncate(c.merged); self.notes.unmerged = c.unmerged; self.notes.unclipped = c.unclipped; @@ -1186,6 +1259,82 @@ impl [f32; 3]> Builder<'_, F> { Ok(Some(acc.unwrap_or_default())) } + /// `out` replaced by one layer: `canvas`, the merge of its visible units with `top`, named after + /// them, bottom first. Its hidden units are left out. + fn take_merge<'i>(&mut self, out: &mut Vec>, top: &Unit<'_>, canvas: Canvas) { + let mut name = String::new(); + for (k, b) in out.iter_mut().filter(|b| b.visible).enumerate() { + if k == 0 { + name = std::mem::take(&mut b.name); + } else { + name.push_str(" + "); + name.push_str(&b.name); + } + } + if out.iter().any(|b| b.visible) { + name.push_str(" + "); + } + name.push_str(&top.name); + // Hidden layers below are left out with the rest. + for b in out.iter().filter(|b| !b.visible).map(|b| b.record).collect::>() { + self.skip(b); + } + out.clear(); + out.push(Unit { + name, + visible: true, + opacity: 1.0, + blend: Blend::Mode(BlendMode::Normal), + mask_of: None, + record: top.record, + body: Body::Merged(canvas), + clip: None, + }); + } + + /// The visible units `below` with `top`, a layer with a shallow knockout, knocking them out: where + /// `top` has pixels, what is below it in its group is cleared to transparency (the group's own + /// backdrop) and `top` is drawn there at its fill opacity; its opacity then fades all of that + /// back toward the units below as they were. Its layer mask shapes the cut. + fn knock(&mut self, below: &[Unit<'_>], top: &Unit<'_>) -> Result { + if !below.iter().any(|u| u.visible) { + return Ok(Knocked::Nothing); + } + let (fill, opacity) = { + let rec = self.record(top.record)?; + (rec.fill, rec.opacity) + }; + let k = match self.draw_body(&top.body, top.mask_of)? { + Drawn::Nothing => return Ok(Knocked::Nothing), + Drawn::TooLarge => return Ok(Knocked::TooLarge), + Drawn::Canvas(c) if c.px.iter().all(|p| p[3] <= 0.0) => return Ok(Knocked::Nothing), + Drawn::Canvas(c) => c, + }; + // The layer's canvas is held while the units below are drawn. + let bytes = 16 * k.px.len() as u64; + self.held = self.held.saturating_add(bytes); + let mut acc: Option = None; + let mut drawn = Ok(true); + for u in below.iter().filter(|u| u.visible) { + drawn = self.composite(&mut acc, u); + if !matches!(drawn, Ok(true)) { + break; + } + } + self.held = self.held.saturating_sub(bytes); + if !drawn? { + return Ok(Knocked::TooLarge); + } + // Nothing below draws. + if acc.is_none() { + return Ok(Knocked::Nothing); + } + if !knock_onto(&mut acc, &k, top.blend, fill, opacity, top.record, self.room(), &|n| self.spend(n))? { + return Ok(Knocked::TooLarge); + } + Ok(acc.map_or(Knocked::Nothing, Knocked::Merged)) + } + /// The bytes a merge step may still take: the memory allowed, less the copies of what is below /// the pass-through groups being merged. fn room(&self) -> u64 { @@ -1203,7 +1352,7 @@ impl [f32; 3]> Builder<'_, F> { _ => None, }; if u.opacity >= 1.0 && mask.is_none() { - return self.lay(acc, items); + return self.lay(acc, items, Level::Pass); } let bytes = acc.as_ref().map_or(0, |c| 16 * c.px.len() as u64); if bytes > self.room() { @@ -1212,7 +1361,7 @@ impl [f32; 3]> Builder<'_, F> { self.spend(bytes)?; let below = acc.clone(); self.held = self.held.saturating_add(bytes); - let laid = self.lay(acc, items); + let laid = self.lay(acc, items, Level::Pass); self.held = self.held.saturating_sub(bytes); if !laid? { return Ok(false); @@ -1230,10 +1379,10 @@ impl [f32; 3]> Builder<'_, F> { blend_onto(acc, &c, u.blend, u.opacity, u.record, self.room(), &|n| self.spend(n)) } - /// `items`' layers composited onto `acc` one by one; `false` when a canvas would need more - /// memory than allowed. - fn lay(&mut self, acc: &mut Option, items: &[Item]) -> Result { - for c in self.merged(items, false)? { + /// `items`' layers, the layers of a group at `level`, composited onto `acc` one by one; `false` + /// when a canvas would need more memory than allowed. + fn lay(&mut self, acc: &mut Option, items: &[Item], level: Level) -> Result { + for c in self.merged(items, false, level)? { if !self.composite(acc, &c)? { return Ok(false); } @@ -1273,7 +1422,7 @@ impl [f32; 3]> Builder<'_, F> { }, Body::Group(items) => { let mut acc: Option = None; - if !self.lay(&mut acc, items)? { + if !self.lay(&mut acc, items, Level::Group)? { return Ok(Drawn::TooLarge); } let Some(acc) = acc else { return Ok(Drawn::Nothing) }; @@ -1306,10 +1455,10 @@ impl [f32; 3]> Builder<'_, F> { Ok(n) } - /// Layers of the document for `items`, bottom first. - fn list(&mut self, items: &[Item]) -> Result>, String> { + /// Layers of the document for `items`, the layers at `level`, bottom first. + fn list(&mut self, items: &[Item], level: Level) -> Result>, String> { let mut out = vec![]; - for u in self.merged(items, self.hidden)? { + for u in self.merged(items, self.hidden, level)? { if let Some(n) = self.node(u)? { out.push(Arc::new(n)); } @@ -1329,7 +1478,7 @@ impl [f32; 3]> Builder<'_, F> { Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)], None => return Ok(None), }, - Body::Group(items) => self.list(items)?, + Body::Group(items) => self.list(items, if u.blend == Blend::Pass { Level::Pass } else { Level::Group })?, }; let mut layer = self.layer(&u.name); layer.visible = u.visible; @@ -1443,6 +1592,61 @@ fn blend_onto( max_alloc: u64, spend: &dyn Fn(u64) -> Result<(), String>, ) -> Result { + if !cover(acc, src, max_alloc, spend)? { + return Ok(false); + } + let Some(out) = acc.as_mut() else { return Ok(false) }; + // Only the source's rows and columns change. + let (sw, x0, y0) = (src.width.max(1), (src.left - out.left) as usize, (src.top - out.top) as usize); + for (k, s) in src.px.iter().enumerate() { + let Some(p) = out.px.get_mut((y0 + k / sw) * out.width + x0 + k % sw) else { continue }; + let a = coverage(blend, s[3] * opacity, src.left + (k % sw) as i64, src.top + (k / sw) as i64, record); + *p = over(blend, *p, [s[0], s[1], s[2], a]); + } + Ok(true) +} + +/// `knock` (of record `record`, in `blend`, with its `fill` and `opacity`), a layer with a shallow +/// knockout, knocking out `acc`, on a canvas covering both, as [`blend_onto`] makes it. Where +/// `knock` has pixels, its transparency is the share of `acc` cleared and replaced by its color at +/// `fill`; `opacity` then fades that back toward `acc`. `false`, with `acc` as it was, when the +/// canvases would take more than `max_alloc` bytes. +#[allow(clippy::too_many_arguments)] +fn knock_onto( + acc: &mut Option, + knock: &Canvas, + blend: Blend, + fill: f32, + opacity: f32, + record: usize, + max_alloc: u64, + spend: &dyn Fn(u64) -> Result<(), String>, +) -> Result { + if !cover(acc, knock, max_alloc, spend)? { + return Ok(false); + } + let Some(out) = acc.as_mut() else { return Ok(false) }; + let (fill, opacity) = (fill.clamp(0.0, 1.0), opacity.clamp(0.0, 1.0)); + let (kw, x0, y0) = (knock.width.max(1), (knock.left - out.left) as usize, (knock.top - out.top) as usize); + for (k, s) in knock.px.iter().enumerate() { + let Some(p) = out.px.get_mut((y0 + k / kw) * out.width + x0 + k % kw) else { continue }; + let t = opacity * coverage(blend, s[3].clamp(0.0, 1.0), knock.left + (k % kw) as i64, knock.top + (k / kw) as i64, record); + let below = p[3].clamp(0.0, 1.0); + let alpha = (1.0 - t) * below + t * fill; + if alpha <= 0.0 { + *p = [0.0; 4]; + continue; + } + let mix = |i: usize| ((1.0 - t) * below * p[i] + t * fill * s[i]) / alpha; + *p = [mix(0), mix(1), mix(2), alpha]; + } + Ok(true) +} + +/// `acc` grown, when it doesn't already, to a canvas covering itself and `src` (a new one counted +/// with `spend`). `false`, with `acc` as it was, when the canvases held, `acc` and `src` and a +/// larger canvas when one is needed, would take more than `max_alloc` bytes. +fn cover(acc: &mut Option, src: &Canvas, max_alloc: u64, spend: &dyn Fn(u64) -> Result<(), String>) -> Result { let (mut left, mut top, mut right, mut bottom) = (src.left, src.top, src.left + src.width as i64, src.top + src.height as i64); if let Some(a) = acc.as_ref() { left = left.min(a.left); @@ -1475,14 +1679,6 @@ fn blend_onto( } *acc = Some(out); } - let Some(out) = acc.as_mut() else { return Ok(false) }; - // Only the source's rows and columns change. - let (sw, x0, y0) = (src.width.max(1), (src.left - left) as usize, (src.top - top) as usize); - for (k, s) in src.px.iter().enumerate() { - let Some(p) = out.px.get_mut((y0 + k / sw) * width + x0 + k % sw) else { continue }; - let a = coverage(blend, s[3] * opacity, src.left + (k % sw) as i64, src.top + (k / sw) as i64, record); - *p = over(blend, *p, [s[0], s[1], s[2], a]); - } Ok(true) } @@ -1523,9 +1719,11 @@ pub(super) fn import( noted: vec![false; records.len()], skipped: vec![false; records.len()], skip_log: vec![], + unknocked: vec![false; records.len()], + unknock_log: vec![], spent: Cell::new(0), }; - let layers = b.list(&items)?; + let layers = b.list(&items, Level::Top)?; let Builder { mut doc, notes, .. } = b; if !layers.is_empty() { doc.layers = layers; diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 6c227c0e17..61db4b86fc 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -646,6 +646,134 @@ fn dissolve_layers_merge_as_opaque_or_transparent_pixels() { assert!((32..=96).contains(&red), "{red} of 256 pixels show the lower layer: {r}"); } +/// A layer with a Knockout value of `knko` and a fill opacity of `fill`. +fn knockout(l: L, knko: u8, fill: u8) -> L { + let mut l = l; + l.blocks.push((*b"knko", vec![knko, 0, 0, 0])); + l.blocks.push((*b"iOpa", vec![fill])); + l +} + +/// A green layer under a group of `group_blend` holding a red layer and `cut` above it. +fn knockout_stack(group_blend: &'static [u8; 4], cut: L) -> Vec { + vec![ + layer("Outside", [0, 0, 4, 4], [0, 255, 0, 255]), + group_end(), + layer("Lower", [0, 0, 4, 4], [255, 0, 0, 255]), + cut, + group("Group", group_blend), + ] +} + +/// The names of the document's layers, and of the layers in its second one. +fn knockout_names(s: &Session) -> (Vec, Vec) { + let d = &s.doc().unwrap().doc; + let names = |ls: &[std::sync::Arc]| ls.iter().map(|l| name(l).to_string()).collect::>(); + (names(&d.layers), d.layers.get(1).and_then(|g| g.children()).map_or(vec![], |c| names(c))) +} + +/// A layer with a shallow knockout in a group merges with the layers below it in the group: its +/// shape clears them to transparency, it draws there at its fill opacity, and its opacity fades +/// that. What is outside the group stays a layer of its own and shows through. +#[test] +fn knockout_layers_merge_with_the_layers_below_them_in_their_group() { + let cut = |fill: u8, opacity: u8| knockout(L { opacity, ..layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]) }, 1, fill); + for (fill, opacity, at_cut) in [(0, 255, [0, 0, 0, 0]), (128, 255, [0, 0, 255, 128]), (0, 128, [255, 0, 0, 127]), (255, 255, [0, 0, 255, 255])] { + for group_blend in [b"norm", b"pass"] { + let (s, r) = open(&file(4, 4, &knockout_stack(group_blend, cut(fill, opacity)), 8, false, false), json!({})); + assert_eq!(r["warnings"], json!([]), "{r}"); + let (top, inner) = knockout_names(&s); + assert_eq!((top, inner), (vec!["Outside".to_string(), "Group".into()], vec!["Lower + Cut".to_string()]), "{fill} {opacity}"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers[1].isolate, group_blend == b"norm"); + let ((x, y), px) = image_of(&s, &d.layers[1].children().unwrap()[0]); + assert_eq!(((x, y), px.dimensions()), ((0.0, 0.0), (4, 4))); + assert_eq!((px.get_pixel(1, 1).0, px.get_pixel(3, 3).0), (at_cut, [255, 0, 0, 255]), "{fill} {opacity}"); + } + } + // A layer mask shapes the cut: where it hides the layer, nothing below is cleared. + let mut masked = cut(0, 255); + masked.mask = Some(([0, 0, 1, 1], 255, 0, vec![0])); + let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", masked), 8, false, false), json!({})); + let px = image_of(&s, &s.doc().unwrap().doc.layers[1].children().unwrap()[0]).1; + assert_eq!((px.get_pixel(0, 0).0, px.get_pixel(1, 1).0), ([255, 0, 0, 255], [0, 0, 0, 0]), "{r}"); + // Without a knockout (0), the layers stay apart. + let (s, r) = + open(&file(4, 4, &knockout_stack(b"norm", knockout(layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]), 0, 0)), 8, false, false), json!({})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([])), "{r}"); +} + +/// The knockouts this import doesn't apply come in as layers, counted in a warning: at the top level, +/// on a clipped layer, and with a Knockout value other than 1. Hidden ones that would need the merge +/// are left out; one that draws nothing, or nothing below it, merges nothing. +#[test] +fn knockouts_that_arent_applied_are_said() { + const UNAPPLIED: &str = "the knockout of 1 layer wasn't applied"; + let cut = |l: L, knko: u8| knockout(l, knko, 0); + let blue = || layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]); + // At the top level. + let layers = [layer("Lower", [0, 0, 4, 4], [255, 0, 0, 255]), cut(blue(), 1)]; + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({})); + assert_eq!((knockout_names(&s).0, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}"); + // Another Knockout value, and a clipped layer, in a group. + let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", cut(blue(), 2)), 8, false, false), json!({})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}"); + let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", cut(L { clipped: true, ..blue() }, 1)), 8, false, false), json!({})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower + Cut".to_string()], &json!([UNAPPLIED])), "{r}"); + // In a pass-through group, a layer below it, or the knockout itself, in another mode blends with + // what is outside the group: the layers stay apart, and the lower one still multiplies the green + // outside. In an isolated group they merge. + let mut multiply = knockout_stack(b"pass", cut(blue(), 1)); + multiply[2].blend = b"mul "; + let (s, r) = open(&file(4, 4, &multiply, 8, false, false), json!({})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}"); + assert_eq!(s.doc().unwrap().doc.layers[1].children().unwrap()[0].blend, BlendMode::Multiply); + let (s, r) = open(&file(4, 4, &knockout_stack(b"pass", cut(L { blend: b"mul ", ..blue() }, 1)), 8, false, false), json!({})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}"); + multiply[4] = group("Group", b"norm"); + let (s, r) = open(&file(4, 4, &multiply, 8, false, false), json!({})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower + Cut".to_string()], &json!([])), "{r}"); + // A hidden knockout would need the merge: left out, hidden layers asked for or not. + for hidden in [false, true] { + let (s, r) = + open(&file(4, 4, &knockout_stack(b"norm", cut(L { hidden: true, ..blue() }, 1)), 8, false, false), json!({"hiddenLayers": hidden})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{hidden}: {r}"); + } + // One that stores no pixels or only transparent ones cuts nothing, and merges nothing. + for (l, inner) in [(L { bare: true, ..blue() }, vec!["Lower"]), (layer("Cut", [0, 0, 2, 2], [0, 0, 255, 0]), vec!["Lower", "Cut"])] { + let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", cut(l, 1)), 8, false, false), json!({})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (inner.iter().map(|n| n.to_string()).collect(), &json!([])), "{r}"); + } + // Nothing below it in its group: it comes in as a layer. + let layers = [group_end(), cut(blue(), 1), group("Group", b"norm"), layer("Over", [0, 0, 1, 1], [9, 9, 9, 255])]; + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Cut"], "{r}"); + assert_eq!(r["warnings"], json!([]), "{r}"); +} + +/// A knockout's merge whose canvases would need more memory than allowed leaves the layers apart, +/// with a warning. +#[test] +fn a_knockout_merge_past_the_memory_allowed_leaves_the_layers_apart() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let layers = [ + group_end(), + layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]), + knockout(layer("Cut", [2, 2, 4, 4], [0, 0, 255, 255]), 1, 0), + group("Group", b"norm"), + ]; + let f = file(4, 4, &layers, 8, false, false); + // Each 2 × 2 layer fits 128 bytes (16 a pixel), but not the canvas of the layer below with the + // knockout's canvas held beside it. + let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Lower", "Cut"]); + assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]); + let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Lower + Cut"]); + assert!(warnings.is_empty(), "{warnings:?}"); +} + #[test] fn what_doesnt_come_in_is_said() { let mut text = layer("Words", [0, 0, 2, 2], [0, 0, 0, 255]); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 900dd99aab..e4bbf9dbbb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2040,7 +2040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur EPS export and EPS Save make each file's PNG thumbnail from its TIFF preview, averaging the preview's pixels down to the thumbnail's size on white, instead of drawing the document a second time; a file without a preview still draws its thumbnail (`crates/engine/src/cmd/fileio/tests_eps.rs`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), and adjustment layers, layer effects, knockouts and vector masks aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the layers below it are in the Normal mode), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none, and files that name no clipping path come in as before (`crates/engine/src/cmd/fileio/tests_psdread.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). From 313d889a7f513ea0157ab0fd4bc736e2ab97851f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 16:54:12 -0800 Subject: [PATCH 09/34] PSD import: a group that draws nothing is drawn once, however deep it nests A group with a knockout was drawn for the knockout and, when it drew nothing, drawn again as a layer of its own. Nested inside each other, such groups were drawn twice over for every level, so opening a crafted PSD file could take exponential time; layers without pixels charge nothing against the import's memory allowance, so it did not stop it. The import now keeps what a group gave when drawn without reading any layer's pixels (nothing, or a canvas without pixels) and gives it again without walking the group's layers. A pass-through group that laid nothing onto an empty canvas without reading any pixels is not laid there again; its layers count the same warnings each time. A merge that can't be made forgets the groups found during it, with the notes it gives back. A knockout group that comes in as a layer is also listed after being drawn, and its layers clipped to a fill that isn't drawn, or left unclipped by a merge past the memory allowed, were counted twice in the warnings. Each is now counted once. The knockout of a layer that others are clipped to was applied when the clip merge needed more memory than allowed and the layers came in apart. It is now left unapplied and counted, as it is when the clip merge is made. A Dissolve knockout at part opacity cleared every pixel below it in part. It now clears each pixel fully or not at all, at the share its transparency times its opacity gives, as other Dissolve merges do. --- crates/engine/src/cmd/fileio/psdlayers.rs | 198 +++++++++++++++--- .../engine/src/cmd/fileio/tests_psdlayers.rs | 137 ++++++++++++ 2 files changed, 308 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index ded5288c69..c2f0dd5ff2 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -72,6 +72,13 @@ const MAX_CHANNELS: usize = 56; const MIN_RECORD: usize = 34; const DAMAGED: &str = "the PSD file's layer records are damaged"; +#[cfg(test)] +thread_local! { + /// The layer lists imports on this thread have walked, and the most a test lets them walk + /// before the import stops with an error. + pub(super) static WALKS: Cell<(usize, usize)> = const { Cell::new((0, usize::MAX)) }; +} + /// The keys of the tagged blocks that make a layer an adjustment layer. const ADJUSTMENTS: [&[u8; 4]; 18] = [ b"levl", b"curv", b"brit", b"blnc", b"hue ", b"hue2", b"selc", b"mixr", b"grdm", b"phfl", b"expA", b"vibA", b"thrs", b"nvrt", b"post", b"clrL", @@ -619,6 +626,8 @@ struct Unit<'i> { body: Body<'i>, /// While layers are clipped to it: how its merged canvas is shaped. clip: Option, + /// Layers are clipped to it, merged into it or not. + base: bool, } impl Unit<'_> { @@ -647,8 +656,8 @@ enum Clip { enum Body<'i> { /// A layer record's pixels. Layer(usize), - /// A group's layers. - Group(&'i [Item]), + /// A group's record and its layers. + Group(usize, &'i [Item]), /// Layers merged into one image. Merged(Canvas), } @@ -675,6 +684,7 @@ enum Knocked { } /// A unit's body drawn alone. +#[derive(Clone)] enum Drawn { /// It draws nothing. Nothing, @@ -713,6 +723,8 @@ struct Counts { unmerged: usize, unclipped: usize, clipped_out: usize, + /// The groups found to read no pixels. + blank: usize, } /// Adds the warning for `n` things to `out`: `one` when `n` is 1, `many` with the count in place @@ -776,8 +788,16 @@ impl Notes { out } - fn counts(&self, skipped: usize, unknocked: usize) -> Counts { - Counts { skipped, unknocked, merged: self.merged.len(), unmerged: self.unmerged, unclipped: self.unclipped, clipped_out: self.clipped_out } + fn counts(&self, skipped: usize, unknocked: usize, blank: usize) -> Counts { + Counts { + skipped, + unknocked, + merged: self.merged.len(), + unmerged: self.unmerged, + unclipped: self.unclipped, + clipped_out: self.clipped_out, + blank, + } } } @@ -806,8 +826,26 @@ struct Builder<'a, F> { unknocked: Vec, /// Those records, in the order they were counted. unknock_log: Vec, + /// The records counted as layers clipped to a fill that isn't drawn. + clipped_out: Vec, + /// Those records, in the order they were counted. + clipped_out_log: Vec, + /// The records counted as clipped layers left unclipped. + unclipped: Vec, + /// Those records, in the order they were counted. + unclip_log: Vec, /// Bytes of layer and mask pixels decoded, and of canvases the merges made, so far. spent: Cell, + /// The layers whose pixels were read so far (each time they were). + painted: Cell, + /// What each group gave when drawn alone without reading any layer's pixels (nothing, or a + /// canvas without pixels, whatever the memory left): drawing it again gives that without + /// walking its layers. + blank: Vec>, + /// The pass-through groups that laid nothing onto nothing (see [`Self::laid_nothing`]). + laid_blank: Vec, + /// The groups of both, in the order they were found. + blank_log: Vec, } impl [f32; 3]> Builder<'_, F> { @@ -849,6 +887,7 @@ impl [f32; 3]> Builder<'_, F> { Paint::Cmyk(ink) => (self.cmyk)(ink), }; let px = image::Rgba([byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), 255]); + self.painted.set(self.painted.get() + 1); return Ok(Some((0, 0, RgbaImage::from_pixel(h.width, h.height, px)))); } Content::Pixels | Content::Type | Content::Solid(_) | Content::Fill => rec.bounds.size(), @@ -880,6 +919,7 @@ impl [f32; 3]> Builder<'_, F> { let rgb = to_rgb(h, |c| planes.get(c).map_or(0.0, |p| at(p, linear, 0.0)), &self.cmyk); image::Rgba([byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), byte(at(&alpha, false, 1.0))]) }); + self.painted.set(self.painted.get() + 1); Ok(Some((i64::from(rec.bounds.left), i64::from(rec.bounds.top), img))) } @@ -932,7 +972,7 @@ impl [f32; 3]> Builder<'_, F> { for item in items { let (i, body) = match item { Item::Layer(i) => (*i, Body::Layer(*i)), - Item::Group(i, children) => (*i, Body::Group(children)), + Item::Group(i, children) => (*i, Body::Group(*i, children)), }; let rec = self.record(i)?; let (name, hidden, clipped, blend) = (rec.name.clone(), rec.hidden, rec.clipped, rec.blend); @@ -959,14 +999,17 @@ impl [f32; 3]> Builder<'_, F> { if self.record(i)?.knockout != 0 { self.unknock(i); } + if let Some(u) = out.get_mut(b) { + u.base = true; + } if !unclipped && self.clip(&mut out, b, &body, i, &name, blend, opacity)? { continue; } // The merge doesn't fit: this layer and the next ones clipped to the same // base come in as layers of their own. unclipped = true; - self.notes.unclipped += 1; - out.push(Unit { name, visible: true, opacity, blend, mask_of: Some(i), record: i, body, clip: None }); + self.unclip(i); + out.push(Unit { name, visible: true, opacity, blend, mask_of: Some(i), record: i, body, clip: None, base: false }); } } continue; @@ -978,7 +1021,7 @@ impl [f32; 3]> Builder<'_, F> { continue; } self.note(i)?; - out.push(Unit { name, visible: !hidden, opacity, blend, mask_of: Some(i), record: i, body, clip: None }); + out.push(Unit { name, visible: !hidden, opacity, blend, mask_of: Some(i), record: i, body, clip: None, base: false }); base = Some(Some(out.len() - 1)); } for u in &mut out { @@ -1001,7 +1044,7 @@ impl [f32; 3]> Builder<'_, F> { }; // A fill whose shape is a vector mask isn't drawn, and nothing clipped to it is either. if undrawn && u.clip.is_none() { - self.notes.clipped_out += 1; + self.clip_out(i); return Ok(true); } let layer = match self.draw_body(body, Some(i))? { @@ -1127,7 +1170,7 @@ impl [f32; 3]> Builder<'_, F> { } let normal = |u: &Unit<'_>| u.blend == Blend::Mode(BlendMode::Normal); let blends_out = level == Level::Pass && !(normal(u) && below.iter().filter(|b| b.visible).all(normal)); - let applies = rec.knockout == 1 && level != Level::Top && !blends_out && !rec.clipped && !matches!(u.body, Body::Merged(_)); + let applies = rec.knockout == 1 && level != Level::Top && !blends_out && !rec.clipped && !u.base && !matches!(u.body, Body::Merged(_)); if !applies { self.unknock(u.record); } @@ -1145,9 +1188,39 @@ impl [f32; 3]> Builder<'_, F> { } } + /// Count record `i` as a layer clipped to a fill that isn't drawn (once). + fn clip_out(&mut self, i: usize) { + if let Some(s) = self.clipped_out.get_mut(i) + && !*s + { + *s = true; + self.notes.clipped_out += 1; + self.clipped_out_log.push(i); + } + } + + /// Count record `i` as a clipped layer left unclipped (once). + fn unclip(&mut self, i: usize) { + if let Some(s) = self.unclipped.get_mut(i) + && !*s + { + *s = true; + self.notes.unclipped += 1; + self.unclip_log.push(i); + } + } + /// `items`' units, at `level`, with the layers in blend modes VectorCraft lacks, and in a group /// the layers with a shallow knockout, merged with those below. fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool, level: Level) -> Result>, String> { + #[cfg(test)] + { + let (walked, most) = WALKS.get(); + if walked >= most { + return Err("the import walked more layer lists than the test allows".into()); + } + WALKS.set((walked + 1, most)); + } let mut out: Vec> = vec![]; for mut u in self.units(items, keep_hidden)? { if self.knocks(&u, &out, level)? { @@ -1156,7 +1229,7 @@ impl [f32; 3]> Builder<'_, F> { self.skip(u.record); continue; } - let saved = self.notes.counts(self.skip_log.len(), self.unknock_log.len()); + let saved = self.notes.counts(self.skip_log.len(), self.unknock_log.len(), self.blank_log.len()); match self.knock(&out, &u)? { Knocked::Merged(canvas) => { self.take_merge(&mut out, &u, canvas); @@ -1185,7 +1258,7 @@ impl [f32; 3]> Builder<'_, F> { continue; } // A merge that can't be made counts nothing its groups would have counted. - let saved = self.notes.counts(self.skip_log.len(), self.unknock_log.len()); + let saved = self.notes.counts(self.skip_log.len(), self.unknock_log.len(), self.blank_log.len()); let made = match out.as_mut_slice() { // Onto the previous merge alone: composited onto its canvas, in place. [prev] if prev.is_merge() => { @@ -1241,10 +1314,29 @@ impl [f32; 3]> Builder<'_, F> { self.notes.knockouts = self.notes.knockouts.saturating_sub(1); } } + // The groups found since: what their drawing counted is given back, so they are drawn again. + for g in self.blank_log.split_off(c.blank) { + if let Some(b) = self.blank.get_mut(g) { + *b = None; + } + if let Some(b) = self.laid_blank.get_mut(g) { + *b = false; + } + } + for i in self.unclip_log.split_off(c.unclipped) { + if let Some(s) = self.unclipped.get_mut(i) { + *s = false; + self.notes.unclipped = self.notes.unclipped.saturating_sub(1); + } + } + for i in self.clipped_out_log.split_off(c.clipped_out) { + if let Some(s) = self.clipped_out.get_mut(i) { + *s = false; + self.notes.clipped_out = self.notes.clipped_out.saturating_sub(1); + } + } self.notes.merged.truncate(c.merged); self.notes.unmerged = c.unmerged; - self.notes.unclipped = c.unclipped; - self.notes.clipped_out = c.clipped_out; } /// The visible units `below` with `top` composited over them; `None` when the canvas would need @@ -1289,6 +1381,7 @@ impl [f32; 3]> Builder<'_, F> { record: top.record, body: Body::Merged(canvas), clip: None, + base: false, }); } @@ -1341,18 +1434,41 @@ impl [f32; 3]> Builder<'_, F> { self.max_alloc.saturating_sub(self.held) } + /// Note pass-through group `g` as laying nothing onto nothing when `acc`, nothing before, still + /// is and no layer's pixels were read since `painted`: laying its layers onto nothing again + /// gives nothing, with the same notes. + fn laid_nothing(&mut self, g: usize, acc: &Option, painted: usize) { + if acc.is_none() + && self.painted.get() == painted + && let Some(b) = self.laid_blank.get_mut(g) + && !*b + { + *b = true; + self.blank_log.push(g); + } + } + /// Unit `u` composited onto `acc`. A pass-through group lays its layers onto `acc` one by one, /// so that they blend with what is below it; at less than full opacity or with a layer mask, the /// result is then faded back toward `acc` as it was by the opacity and the mask. Anything else /// is drawn alone first. `false` when the canvas would need more memory than allowed. fn composite(&mut self, acc: &mut Option, u: &Unit<'_>) -> Result { - if let (Body::Group(items), Blend::Pass) = (&u.body, u.blend) { + if let (Body::Group(g, items), Blend::Pass) = (&u.body, u.blend) { let mask = match u.mask_of { Some(i) if self.has_mask(Some(i))? => self.mask(i, false)?, _ => None, }; + // Onto nothing, a group that laid nothing onto nothing before lays nothing again. + let (fresh, painted) = (acc.is_none(), self.painted.get()); + if fresh && self.laid_blank.get(*g) == Some(&true) { + return Ok(true); + } if u.opacity >= 1.0 && mask.is_none() { - return self.lay(acc, items, Level::Pass); + let laid = self.lay(acc, items, Level::Pass)?; + if laid && fresh { + self.laid_nothing(*g, acc, painted); + } + return Ok(laid); } let bytes = acc.as_ref().map_or(0, |c| 16 * c.px.len() as u64); if bytes > self.room() { @@ -1366,6 +1482,9 @@ impl [f32; 3]> Builder<'_, F> { if !laid? { return Ok(false); } + if fresh { + self.laid_nothing(*g, acc, painted); + } if let Some(after) = acc.as_mut() { fade(after, below.as_ref(), u.opacity, mask.as_ref()); } @@ -1420,13 +1539,29 @@ impl [f32; 3]> Builder<'_, F> { } None => return Ok(Drawn::Nothing), }, - Body::Group(items) => { - let mut acc: Option = None; - if !self.lay(&mut acc, items, Level::Group)? { - return Ok(Drawn::TooLarge); + Body::Group(g, items) => { + let drawn = match self.blank.get(*g).cloned().flatten() { + Some(d) => d, + None => { + let painted = self.painted.get(); + let mut acc: Option = None; + if !self.lay(&mut acc, items, Level::Group)? { + return Ok(Drawn::TooLarge); + } + let d = acc.map_or(Drawn::Nothing, Drawn::Canvas); + if self.painted.get() == painted + && let Some(b) = self.blank.get_mut(*g) + { + *b = Some(d.clone()); + self.blank_log.push(*g); + } + d + } + }; + match drawn { + Drawn::Canvas(c) => c, + other => return Ok(other), } - let Some(acc) = acc else { return Ok(Drawn::Nothing) }; - acc } }; if let Some(i) = mask_of { @@ -1478,13 +1613,13 @@ impl [f32; 3]> Builder<'_, F> { Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)], None => return Ok(None), }, - Body::Group(items) => self.list(items, if u.blend == Blend::Pass { Level::Pass } else { Level::Group })?, + Body::Group(_, items) => self.list(items, if u.blend == Blend::Pass { Level::Pass } else { Level::Group })?, }; let mut layer = self.layer(&u.name); layer.visible = u.visible; layer.opacity = u.opacity.clamp(0.0, 1.0); (layer.blend, layer.isolate) = match u.blend { - Blend::Mode(m) => (m, matches!(u.body, Body::Group(_))), + Blend::Mode(m) => (m, matches!(u.body, Body::Group(..))), Blend::Pass | Blend::Other(_) => (BlendMode::Normal, false), }; if let Some(c) = layer.children_mut() { @@ -1609,8 +1744,9 @@ fn blend_onto( /// `knock` (of record `record`, in `blend`, with its `fill` and `opacity`), a layer with a shallow /// knockout, knocking out `acc`, on a canvas covering both, as [`blend_onto`] makes it. Where /// `knock` has pixels, its transparency is the share of `acc` cleared and replaced by its color at -/// `fill`; `opacity` then fades that back toward `acc`. `false`, with `acc` as it was, when the -/// canvases would take more than `max_alloc` bytes. +/// `fill`; `opacity` then fades that back toward `acc` (in Dissolve, each pixel is cleared fully +/// or not at all, at the share its transparency times `opacity` gives). `false`, with `acc` as it +/// was, when the canvases would take more than `max_alloc` bytes. #[allow(clippy::too_many_arguments)] fn knock_onto( acc: &mut Option, @@ -1630,7 +1766,7 @@ fn knock_onto( let (kw, x0, y0) = (knock.width.max(1), (knock.left - out.left) as usize, (knock.top - out.top) as usize); for (k, s) in knock.px.iter().enumerate() { let Some(p) = out.px.get_mut((y0 + k / kw) * out.width + x0 + k % kw) else { continue }; - let t = opacity * coverage(blend, s[3].clamp(0.0, 1.0), knock.left + (k % kw) as i64, knock.top + (k / kw) as i64, record); + let t = coverage(blend, s[3].clamp(0.0, 1.0) * opacity, knock.left + (k % kw) as i64, knock.top + (k / kw) as i64, record); let below = p[3].clamp(0.0, 1.0); let alpha = (1.0 - t) * below + t * fill; if alpha <= 0.0 { @@ -1721,7 +1857,15 @@ pub(super) fn import( skip_log: vec![], unknocked: vec![false; records.len()], unknock_log: vec![], + clipped_out: vec![false; records.len()], + clipped_out_log: vec![], + unclipped: vec![false; records.len()], + unclip_log: vec![], spent: Cell::new(0), + painted: Cell::new(0), + blank: vec![None; records.len()], + laid_blank: vec![false; records.len()], + blank_log: vec![], }; let layers = b.list(&items, Level::Top)?; let Builder { mut doc, notes, .. } = b; diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 61db4b86fc..6c2f8b8ff2 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -774,6 +774,143 @@ fn a_knockout_merge_past_the_memory_allowed_leaves_the_layers_apart() { assert!(warnings.is_empty(), "{warnings:?}"); } +/// A Dissolve knockout at part opacity clears each pixel below it fully or not at all, at the share +/// its opacity gives, as a Dissolve layer merges. +#[test] +fn a_dissolve_knockout_at_part_opacity_clears_whole_pixels() { + let cut = knockout(L { blend: b"diss", opacity: 128, ..layer("Cut", [0, 0, 16, 16], [0, 0, 255, 255]) }, 1, 0); + let layers = [group_end(), layer("Lower", [0, 0, 16, 16], [255, 0, 0, 255]), cut, group("Group", b"norm")]; + let (s, r) = open(&file(16, 16, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let (_, px) = image_of(&s, &d.layers[0].children().unwrap()[0]); + assert!(px.pixels().all(|p| p.0 == [255, 0, 0, 255] || p.0[3] == 0), "{r}"); + let red = px.pixels().filter(|p| p.0 == [255, 0, 0, 255]).count(); + assert!((32..=224).contains(&red), "{red} of 256 pixels keep the lower layer: {r}"); +} + +/// The knockout of a layer that another is clipped to isn't applied, also when the clipped layer's +/// merge with it needs more memory than allowed and the two come in apart. +#[test] +fn a_clipping_base_knockout_isnt_applied_when_its_clip_doesnt_fit() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + // The 4 × 4 clipped layer and its 2 × 2 base don't fit 320 bytes together for the clip; the + // base's knockout merge with the 2 × 2 layer below would. + let layers = [ + group_end(), + layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]), + knockout(layer("Base", [0, 0, 2, 2], [0, 0, 255, 255]), 1, 0), + L { clipped: true, ..layer("Clipped", [0, 0, 4, 4], [0, 255, 0, 255]) }, + group("Group", b"norm"), + ]; + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 320, cms).unwrap().unwrap(); + assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Lower", "Base", "Clipped"], "{warnings:?}"); + assert_eq!( + warnings, + ["the knockout of 1 layer wasn't applied", "1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"] + ); +} + +/// A knockout group that comes in as a layer counts each layer clipped in it once in the warnings, +/// though its layers are also drawn for the knockout: one clipped to a fill that isn't drawn, and +/// one that a merge past the memory allowed leaves unclipped. +#[test] +fn a_knockout_group_that_comes_in_as_a_layer_counts_its_clipped_layers_once() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let empty = L { bare: true, ..layer("Empty", [0, 0, 2, 2], [0, 0, 0, 0]) }; + // A fill whose shape is a vector mask, with a layer clipped to it: neither is drawn. + let mut soco = vec![0; 8]; + for (key, v) in [(b"Rd doub", 255.0f64), (b"Grn doub", 0.0), (b"Bl doub", 51.0)] { + soco.extend(key); + soco.extend(v.to_be_bytes()); + } + let mut outline = layer("Outline", [0, 0, 0, 0], [0; 4]); + outline.blocks.push((*b"SoCo", soco)); + outline.blocks.push((*b"vsms", vec![0; 8])); + let on_outline = L { clipped: true, ..layer("On outline", [0, 0, 2, 2], [1, 1, 1, 255]) }; + // Each 2 × 2 layer fits 128 bytes, and so do the two drawn together, but not the merge of the + // clipped one with the one below. + let base = layer("Base", [0, 0, 2, 2], [255, 0, 0, 255]); + let clipped = L { clipped: true, ..layer("Clipped", [0, 0, 2, 2], [0, 0, 255, 255]) }; + for (inner, said) in [ + (vec![outline, on_outline], "1 layer clipped to a fill layer that wasn't drawn was left out"), + (vec![base, clipped], "1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"), + ] { + let mut layers = vec![layer("Outside", [0, 0, 4, 4], [0, 255, 0, 255]), group_end(), empty.clone(), group_end()]; + layers.extend(inner); + layers.extend([knockout(group("Cut", b"norm"), 1, 255), group("Group", b"norm")]); + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Outside", "Group"]); + assert!(warnings.iter().any(|w| w == said), "{said}: {warnings:?}"); + } +} + +/// A pass-through group that draws nothing still counts what its layers count in it, also when it +/// is drawn again inside a group that merges: a knockout above a Multiply layer isn't applied in a +/// pass-through group, though drawn alone it would be. +#[test] +fn a_pass_through_group_that_draws_nothing_still_counts_its_unapplied_knockouts() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let empty = |name: &'static str, blend: &'static [u8; 4]| L { bare: true, blend, ..layer(name, [0, 0, 2, 2], [0, 0, 0, 0]) }; + let layers = [ + layer("Lower", [0, 0, 4, 4], [255, 0, 0, 255]), + group_end(), + empty("Empty", b"norm"), + group_end(), + empty("Multiplied", b"mul "), + knockout(empty("Cut", b"norm"), 1, 255), + knockout(group("Through", b"pass"), 1, 255), + group("Dissolved", b"diss"), + ]; + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Lower + Dissolved"], "{warnings:?}"); + assert_eq!(warnings, ["the knockout of 1 layer wasn't applied".to_string(), psdlayers::MERGED_WARNING.replace("{modes}", "Dissolve")]); +} + +/// A group that draws nothing is drawn once, however deep the groups like it nest: here each holds +/// a layer that stores no pixels and, above it, the next group, with a knockout. The import walks +/// at most as many layer lists as the file has records, with isolated groups, with groups that +/// alternate with pass-through ones, with pass-through groups inside the outermost one (whose +/// knockouts aren't applied), and with a layer in a mode VectorCraft lacks in each (a merge of +/// nothing, a canvas without pixels). +#[test] +fn groups_that_draw_nothing_are_drawn_once_however_deep_they_nest() { + const LEVELS: usize = 48; + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let empty = |name: &'static str, blend: &'static [u8; 4]| L { bare: true, blend, ..layer(name, [0, 0, 2, 2], [0, 0, 0, 0]) }; + // Which levels are pass-through groups. + let none: fn(usize) -> bool = |_| false; + let odd: fn(usize) -> bool = |k| k % 2 == 1; + let all: fn(usize) -> bool = |k| k > 0; + for (case, pass, dissolve, warned) in [ + ("isolated", none, false, vec![]), + ("alternating", odd, false, vec![]), + ("pass-through", all, false, vec![format!("the knockout of {} layers wasn't applied", LEVELS - 1)]), + ("dissolved", none, true, vec![psdlayers::MERGED_WARNING.replace("{modes}", "Dissolve")]), + ] { + let mut layers = vec![layer("Outside", [0, 0, 4, 4], [0, 255, 0, 255])]; + for _ in 0..=LEVELS { + layers.push(group_end()); + if dissolve { + layers.push(empty("Dissolved", b"diss")); + } + layers.push(empty("Empty", b"norm")); + } + for k in (0..=LEVELS).rev() { + let g = group("Group", if pass(k) { b"pass" } else { b"norm" }); + layers.push(if k == 0 { g } else { knockout(g, 1, 255) }); + } + psdlayers::WALKS.set((0, layers.len())); + let imported = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 1 << 20, cms); + let (walked, _) = psdlayers::WALKS.replace((0, usize::MAX)); + let (doc, warnings) = imported.unwrap().unwrap(); + assert!(walked <= layers.len(), "{case}: {walked} walks for {} records", layers.len()); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Outside", "Group"], "{case}"); + let mut expected = warned; + expected.push(vectorcraft_doc::depth::merged_note()); + assert_eq!(warnings, expected, "{case}"); + } +} + #[test] fn what_doesnt_come_in_is_said() { let mut text = layer("Words", [0, 0, 2, 2], [0, 0, 0, 255]); From 9c364510e9249082a3cf1335e1ccc18cb8fd835a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 19:32:03 -0800 Subject: [PATCH 10/34] PSD import: knockouts that change nothing below them leave the layers apart A shallow knockout at 0 opacity, or at 0 fill over layers that are all transparent, is no longer merged with the layers below it, so hidden layers below it come in with hiddenLayers. A hidden knockout at 0 opacity, or with nothing visible below it, comes in with hiddenLayers instead of being left out. The count of hidden layers left out no longer includes hidden layers that came in after a group was drawn for a knockout or a clip that wasn't made. docs/mcp.md describes the knockouts document.open applies. --- crates/engine/src/cmd/fileio/psdlayers.rs | 35 ++++++++-- .../engine/src/cmd/fileio/tests_psdlayers.rs | 68 +++++++++++++++++++ docs/mcp.md | 14 +++- docs/target-app-parity.md | 2 +- 4 files changed, 108 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index c2f0dd5ff2..4c3e05cb48 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -677,7 +677,8 @@ enum Level { enum Knocked { /// The merged canvas. Merged(Canvas), - /// Nothing below it draws, or it draws nothing: it comes in as a layer of its own. + /// Nothing below it draws, it draws nothing, or what is below it and the merge are both + /// transparent: it comes in as a layer of its own. Nothing, /// The canvases would need more memory than allowed. TooLarge, @@ -834,6 +835,9 @@ struct Builder<'a, F> { unclipped: Vec, /// Those records, in the order they were counted. unclip_log: Vec, + /// The records that came in as layers of the document (hidden ones too, with `hidden`): not left + /// out, though a drawing for a merge that wasn't made counted them. + kept: Vec, /// Bytes of layer and mask pixels decoded, and of canvases the merges made, so far. spent: Cell, /// The layers whose pixels were read so far (each time they were). @@ -1162,7 +1166,8 @@ impl [f32; 3]> Builder<'_, F> { /// applies? Only a layer or group in a group, neither clipped nor a base of clipped layers, does; /// in a pass-through group, only when it and the visible units below it are in the Normal mode, so /// that none of them blends with what is below the group. Any other knockout is counted as not - /// applied. + /// applied. One at 0 opacity, or with no visible unit below it, changes nothing below it: it needs + /// no merge, and a hidden one isn't left out for it. fn knocks(&mut self, u: &Unit<'_>, below: &[Unit<'_>], level: Level) -> Result { let rec = self.record(u.record)?; if rec.knockout == 0 { @@ -1171,10 +1176,12 @@ impl [f32; 3]> Builder<'_, F> { let normal = |u: &Unit<'_>| u.blend == Blend::Mode(BlendMode::Normal); let blends_out = level == Level::Pass && !(normal(u) && below.iter().filter(|b| b.visible).all(normal)); let applies = rec.knockout == 1 && level != Level::Top && !blends_out && !rec.clipped && !u.base && !matches!(u.body, Body::Merged(_)); + // Its fill opacity isn't checked: at 0 fill it still clears what is below it. + let changes = rec.opacity > 0.0 && below.iter().any(|b| b.visible); if !applies { self.unknock(u.record); } - Ok(applies) + Ok(applies && changes) } /// Count record `i` as a hidden layer left out (once). @@ -1240,7 +1247,8 @@ impl [f32; 3]> Builder<'_, F> { } continue; } - // Nothing below it, or nothing of its own, to knock out: it comes in as a layer. + // Nothing below it, or nothing of its own, to knock out: it comes in as a layer, + // with the hidden layers its drawing left out (see `kept`). Knocked::Nothing => {} Knocked::TooLarge => { self.restore(saved); @@ -1390,9 +1398,6 @@ impl [f32; 3]> Builder<'_, F> { /// backdrop) and `top` is drawn there at its fill opacity; its opacity then fades all of that /// back toward the units below as they were. Its layer mask shapes the cut. fn knock(&mut self, below: &[Unit<'_>], top: &Unit<'_>) -> Result { - if !below.iter().any(|u| u.visible) { - return Ok(Knocked::Nothing); - } let (fill, opacity) = { let rec = self.record(top.record)?; (rec.fill, rec.opacity) @@ -1422,9 +1427,19 @@ impl [f32; 3]> Builder<'_, F> { if acc.is_none() { return Ok(Knocked::Nothing); } + let clear = |c: &Canvas| c.px.iter().all(|p| p[3] <= 0.0); + let below_clear = acc.as_ref().is_some_and(clear); + // Nothing below to cut, and nothing of its own drawn at 0 fill: no canvas for the merge is needed. + if below_clear && fill <= 0.0 { + return Ok(Knocked::Nothing); + } if !knock_onto(&mut acc, &k, top.blend, fill, opacity, top.record, self.room(), &|n| self.spend(n))? { return Ok(Knocked::TooLarge); } + // Nothing below to cut, and nothing of its own drawn at its fill opacity. + if below_clear && acc.as_ref().is_none_or(clear) { + return Ok(Knocked::Nothing); + } Ok(acc.map_or(Knocked::Nothing, Knocked::Merged)) } @@ -1604,6 +1619,9 @@ impl [f32; 3]> Builder<'_, F> { /// The layer of the document unit `u` becomes; `None` for a layer that draws nothing (an /// adjustment layer, or one without pixels). fn node(&mut self, u: Unit<'_>) -> Result, String> { + if let Some(k) = self.kept.get_mut(u.record) { + *k = true; + } let children = match &u.body { Body::Layer(i) => match self.image(*i)? { Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)], @@ -1861,6 +1879,7 @@ pub(super) fn import( clipped_out_log: vec![], unclipped: vec![false; records.len()], unclip_log: vec![], + kept: vec![false; records.len()], spent: Cell::new(0), painted: Cell::new(0), blank: vec![None; records.len()], @@ -1868,6 +1887,8 @@ pub(super) fn import( blank_log: vec![], }; let layers = b.list(&items, Level::Top)?; + // A drawing for a knockout or a clip leaves hidden layers out; those that came in anyway aren't. + b.notes.hidden = b.skipped.iter().zip(&b.kept).filter(|&(s, k)| *s && !*k).count(); let Builder { mut doc, notes, .. } = b; if !layers.is_empty() { doc.layers = layers; diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 6c2f8b8ff2..6324ffcce5 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -752,6 +752,74 @@ fn knockouts_that_arent_applied_are_said() { assert_eq!(r["warnings"], json!([]), "{r}"); } +/// A knockout that changes nothing below it leaves the layers apart, hidden ones included: one at 0 +/// opacity, and one at 0 fill over layers that are transparent. At 0 fill over painted layers, and +/// at a fill over transparent ones, it still merges. A knockout at 0 fill over a transparent layer +/// stays apart without a warning when their merge would need more memory than allowed. +#[test] +fn knockouts_that_change_nothing_keep_the_layers_apart() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let layers = [ + group_end(), + layer("Lower", [0, 0, 2, 2], [255, 0, 0, 0]), + knockout(layer("Cut", [2, 2, 4, 4], [0, 0, 255, 255]), 1, 0), + group("Group", b"norm"), + ]; + // The two 2 × 2 layers drawn together fit 256 bytes, but not the 4 × 4 canvas covering both. + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 256, cms).unwrap().unwrap(); + assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Lower", "Cut"]); + assert!(warnings.is_empty(), "{warnings:?}"); + let lower = |alpha: u8| layer("Lower", [0, 0, 4, 4], [255, 0, 0, alpha]); + let hidden = L { hidden: true, ..layer("Hidden", [0, 0, 4, 4], [0, 255, 0, 255]) }; + let cut = |fill: u8, opacity: u8| knockout(L { opacity, ..layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]) }, 1, fill); + let inner = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(vec![], |c| c.iter().map(|l| name(l).to_string()).collect::>()); + for (alpha, fill, opacity, apart) in [(255, 0, 0, true), (0, 0, 255, true), (255, 0, 255, false), (0, 128, 255, false)] { + let layers = [group_end(), lower(alpha), hidden.clone(), cut(fill, opacity), group("Group", b"norm")]; + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true})); + let (names, warnings) = if apart { (vec!["Lower", "Hidden", "Cut"], json!([])) } else { (vec!["Lower + Cut"], json!([HIDDEN_1])) }; + assert_eq!((inner(&s), &r["warnings"]), (names.iter().map(|n| n.to_string()).collect(), &warnings), "{alpha} {fill} {opacity}: {r}"); + } + // A hidden knockout that needs no merge comes in with hidden layers: at 0 opacity, and with + // nothing below it in its group. + let hidden_cut = |opacity: u8| L { hidden: true, ..cut(0, opacity) }; + for (layers, names) in [ + (vec![group_end(), lower(255), hidden_cut(0), group("Group", b"norm")], vec!["Lower", "Cut"]), + (vec![group_end(), hidden_cut(255), group("Group", b"norm")], vec!["Cut"]), + ] { + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true})); + assert_eq!((inner(&s), &r["warnings"]), (names.iter().map(|n| n.to_string()).collect(), &json!([])), "{r}"); + } +} + +/// With hidden layers asked for, the hidden layers of a group drawn for a knockout or a clip that +/// isn't made come in, and aren't counted as left out: a knockout group over a layer that stores no +/// pixels, and a clipped group whose merge needs more memory than allowed. +#[test] +fn hidden_layers_of_a_group_drawn_for_a_merge_not_made_come_in() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let children = |l: &Node| l.children().map_or(vec![], |c| c.iter().map(|l| (name(l).to_string(), l.visible)).collect::>()); + let shown_and_hidden = + || [group_end(), layer("Shown", [0, 0, 2, 2], [0, 0, 255, 255]), L { hidden: true, ..layer("Hidden", [2, 2, 4, 4], [0, 255, 0, 255]) }]; + let both = vec![("Shown".to_string(), true), ("Hidden".to_string(), false)]; + // A knockout group over a layer that stores no pixels. + let mut layers = vec![group_end(), L { bare: true, ..layer("Lower", [0, 0, 2, 2], [0; 4]) }]; + layers.extend(shown_and_hidden()); + layers.extend([knockout(group("Cut", b"norm"), 1, 255), group("Group", b"norm")]); + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true})); + let d = &s.doc().unwrap().doc; + let cut = &d.layers[0].children().unwrap()[0]; + assert_eq!((name(cut), children(cut), &r["warnings"]), ("Cut", both.clone(), &json!([])), "{r}"); + // A clipped group whose merge with its base doesn't fit 320 bytes. + let mut layers = vec![layer("Base", [0, 0, 2, 2], [255, 0, 0, 255])]; + layers.extend(shown_and_hidden()); + layers[2].rect = [0, 0, 4, 4]; + layers.push(L { clipped: true, ..group("Clipped", b"norm") }); + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), true, 320, cms).unwrap().unwrap(); + let clipped = &doc.layers[1]; + assert_eq!((name(clipped), children(clipped)), ("Clipped", both), "{warnings:?}"); + assert_eq!(warnings, ["1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"]); +} + /// A knockout's merge whose canvases would need more memory than allowed leaves the layers apart, /// with a warning. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..06fc2fe242 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9312,8 +9312,8 @@ clipping mask into one layer and discards hidden layers that require merging; th imports one image, and Import Hidden Layers brings hidden layers in. `document.open` does the same, with `layers: false` for the single image and `hiddenLayers: true` for the hidden layers. The page also merges adjustment layers, layers with a knockout option, and layers that hold transparent pixels in some blend modes with -the layers below them. `document.open` applies neither adjustments nor knockouts, and it merges a layer by its blend -mode alone, as the rules below say. +the layers below them. `document.open` does not apply adjustments, applies only shallow knockouts inside groups, and +otherwise merges a layer by its blend mode alone, as the rules below say. The rest are VectorCraft's own rules: @@ -9333,6 +9333,12 @@ The rest are VectorCraft's own rules: mask. - A Dissolve layer's partly transparent pixels are merged as opaque or transparent, opaque at the share of its pixels their transparency gives, in a fixed pattern that differs from layer to layer. +- A layer or group inside a group with a Knockout value of 1 (shallow) is merged with the visible layers below it + in that group: where it has pixels, shaped by its layer mask, they are cleared to transparency, it is drawn there + at its fill opacity, and its opacity fades the result back toward them. In a Pass Through group this applies only + when it and the visible layers below it are in Normal mode. A knockout at 0 opacity, one that draws nothing, one + with nothing visible below it, and one at 0 fill over layers that are all transparent are not merged for the + knockout; one in a mode VectorCraft lacks is still merged by its mode. - A merged layer is named after the layers it holds, joined with ` + `. - A layer name the file stores only as a one-byte Pascal string, without its Unicode name, is read as Mac Roman. - A layer's opacity is multiplied by its fill opacity, in every blend mode. A layer that others are clipped to keeps @@ -9344,7 +9350,9 @@ The rest are VectorCraft's own rules: (RGB, CMYK, Grayscale, Lab or HSB) over the canvas. One whose shape is a vector mask isn't drawn, and the layers clipped to it are left out. - Adjustment layers, fill layers that store no pixels and whose fill isn't read, layer effects that are switched on, - knockouts and vector masks are not applied; the `warnings` count them. + the other knockouts (top-level layers, clipped layers, layers that others are clipped to, Pass Through groups with + layers in other modes, other Knockout values, and merges that need more memory than allowed) and vector masks are + not applied; the `warnings` count them. - Layer channels may be raw, PackBits or zipped (with or without prediction) at 8, 16 and 32 bits. - A file without layers opens as its merged image. A file whose layers can't be read opens as its merged image with a warning, and when the merged image can't be read either, the file is refused with an error. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e4bbf9dbbb..36b53e6f6f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2040,7 +2040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur EPS export and EPS Save make each file's PNG thumbnail from its TIFF preview, averaging the preview's pixels down to the thumbnail's size on white, instead of drawing the document a second time; a file without a preview still draws its thumbnail (`crates/engine/src/cmd/fileio/tests_eps.rs`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the layers below it are in the Normal mode), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill over layers that are all transparent, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none, and files that name no clipping path come in as before (`crates/engine/src/cmd/fileio/tests_psdread.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). From 157469f6af49137de4e0f06afce9ad0ec02e1dfc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 19:56:29 -0800 Subject: [PATCH 11/34] i18n: the Greek PSD knockout warnings use the catalog's knockout term MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit main now checks that every Greek row naming a knockout says διάτρηση. --- crates/ui-egui/src/i18n/el.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index acd85f7742..43abb58be7 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5717,8 +5717,8 @@ variable-list-end {0}, {1} {0} και {1} @msg the layer effects of {n} layers weren't drawn τα εφέ επιπέδου {n} επιπέδων δεν σχεδιάστηκαν @msg the vector masks of 1 layer weren't applied οι διανυσματικές μάσκες 1 επιπέδου δεν εφαρμόστηκαν @msg the vector masks of {n} layers weren't applied οι διανυσματικές μάσκες {n} επιπέδων δεν εφαρμόστηκαν -@msg the knockout of 1 layer wasn't applied η εκκένωση 1 επιπέδου δεν εφαρμόστηκε -@msg the knockout of {n} layers wasn't applied η εκκένωση {n} επιπέδων δεν εφαρμόστηκε +@msg the knockout of 1 layer wasn't applied η διάτρηση 1 επιπέδου δεν εφαρμόστηκε +@msg the knockout of {n} layers wasn't applied η διάτρηση {n} επιπέδων δεν εφαρμόστηκε @msg 1 layer was left out (hidden layers and the layers clipped to them) 1 επίπεδο παραλείφθηκε (κρυφά επίπεδα και τα επίπεδα που αποκόπτονται σε αυτά) @msg {n} layers were left out (hidden layers and the layers clipped to them) {n} επίπεδα παραλείφθηκαν (κρυφά επίπεδα και τα επίπεδα που αποκόπτονται σε αυτά) @msg 1 layer clipped to a fill layer that wasn't drawn was left out 1 επίπεδο που αποκόπτεται σε επίπεδο γεμίσματος που δεν σχεδιάστηκε παραλείφθηκε From a6d4729bf246c0645a1a809abb249ed45d395a3f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 06:49:40 -0800 Subject: [PATCH 12/34] PSD import: knockouts that cut no paint stay apart, and failed merges keep room to read the layers - A knockout at 0 fill whose pixels cover none of the painted pixels below it is no longer merged with them. - A hidden knockout is left out only when its merge would be made or is too large, so one whose layer mask hides all of it comes in with hiddenLayers. What drawing it counted is forgotten when it is left out. - The pixels and canvases of a merge that isn't made are counted against a separate limit of the same size, so the layers can still be read apart afterward. - docs: the memory-limit fallback for knockouts is listed with the knockouts that aren't applied. --- crates/engine/src/cmd/fileio/psdlayers.rs | 125 ++++++++++++++---- .../engine/src/cmd/fileio/tests_psdlayers.rs | 74 +++++++++-- docs/mcp.md | 9 +- docs/target-app-parity.md | 2 +- 4 files changed, 163 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 4c3e05cb48..598f75ff04 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -31,19 +31,20 @@ //! when it and the visible layers below it are in the Normal mode. When a merge's canvases would need more //! memory than allowed, the layer comes in alone: in the Normal mode, unclipped, or without its //! knockout. Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need -//! a merge (one in a mode VectorCraft lacks, one with a knockout in a group, one that layers are -//! clipped to, one clipped to another, or one below a merged layer) is always left out, with the -//! layers clipped to it. Adjustment layers, fill layers that store no pixels and whose fill isn't read -//! or whose shape is a vector mask, layer effects that are switched on, vector masks, and the -//! knockouts of top-level layers, of clipped layers, of layers that others are clipped to and of -//! layers in a pass-through group with a layer in another mode, and other Knockout values, aren't -//! applied; the warnings count them and the hidden layers left out. +//! a merge (one in a mode VectorCraft lacks, one with a knockout in a group that changes the layers +//! below it, one that layers are clipped to, one clipped to another, or one below a merged layer) is +//! always left out, with the layers clipped to it. Adjustment layers, fill layers that store no +//! pixels and whose fill isn't read or whose shape is a vector mask, layer effects that are switched +//! on, vector masks, and the knockouts of top-level layers, of clipped layers, of layers that others +//! are clipped to and of layers in a pass-through group with a layer in another mode, and other +//! Knockout values, aren't applied; the warnings count them and the hidden layers left out. //! //! The file is untrusted: every count, length and size is checked before anything is allocated, //! groups nest at most [`MAX_DEPTH`] deep (layers deeper than a document may nest merge into the //! group around them, with a warning), each layer's pixels, like the canvases one step of a //! merge holds together, must fit the memory allowed, and all the pixels decoded and the canvases -//! the merges make must fit [`TOTAL_DECODED`] times that. +//! the merges make must fit [`TOTAL_DECODED`] times that. What the merges that can't be made, or +//! that a hidden layer would need, decoded and made is counted apart, against the same limit. use std::cell::Cell; use std::sync::Arc; @@ -677,8 +678,8 @@ enum Level { enum Knocked { /// The merged canvas. Merged(Canvas), - /// Nothing below it draws, it draws nothing, or what is below it and the merge are both - /// transparent: it comes in as a layer of its own. + /// Nothing below it draws, it draws nothing, it is at 0 fill and cuts no painted pixel below + /// it, or what is below it and the merge are both transparent: it comes in as a layer of its own. Nothing, /// The canvases would need more memory than allowed. TooLarge, @@ -717,6 +718,8 @@ struct Notes { /// The counts a merge that can't be made gives back. #[derive(Clone, Copy)] struct Counts { + /// The bytes spent so far (see [`Builder::spent`]). + spent: u64, skipped: usize, /// The knockouts counted as not applied. unknocked: usize, @@ -789,8 +792,9 @@ impl Notes { out } - fn counts(&self, skipped: usize, unknocked: usize, blank: usize) -> Counts { + fn counts(&self, spent: u64, skipped: usize, unknocked: usize, blank: usize) -> Counts { Counts { + spent, skipped, unknocked, merged: self.merged.len(), @@ -819,6 +823,8 @@ struct Builder<'a, F> { notes: Notes, /// The records [`Notes`] counted. noted: Vec, + /// Those records, in the order they were counted. + noted_log: Vec, /// The records counted as hidden layers left out. skipped: Vec, /// Those records, in the order they were counted. @@ -840,6 +846,9 @@ struct Builder<'a, F> { kept: Vec, /// Bytes of layer and mask pixels decoded, and of canvases the merges made, so far. spent: Cell, + /// Those bytes that merges not made, and merges a hidden layer would need, took: given back to + /// `spent` and counted here instead, against the same limit. + wasted: Cell, /// The layers whose pixels were read so far (each time they were). painted: Cell, /// What each group gave when drawn alone without reading any layer's pixels (nothing, or a @@ -873,6 +882,20 @@ impl [f32; 3]> Builder<'_, F> { Ok(()) } + /// Move the bytes spent since `spent` was the count to [`Self::wasted`], which has an allowance + /// of its own as large: what a merge that isn't made decoded doesn't take the room for reading + /// the layers apart. + fn refund(&self, spent: u64) -> Result<(), String> { + let since = self.spent.get().saturating_sub(spent); + self.spent.set(self.spent.get().min(spent)); + let total = self.wasted.get().saturating_add(since); + self.wasted.set(total); + if total > self.max_alloc.saturating_mul(TOTAL_DECODED) { + return Err("the PSD file's layers take more memory to read than allowed".into()); + } + Ok(()) + } + /// Record `i`'s pixels as straight RGBA, at their place on the canvas; `None` when it has none. fn image(&self, i: usize) -> Result, String> { let rec = self.record(i)?; @@ -1006,9 +1029,11 @@ impl [f32; 3]> Builder<'_, F> { if let Some(u) = out.get_mut(b) { u.base = true; } + let spent = self.spent.get(); if !unclipped && self.clip(&mut out, b, &body, i, &name, blend, opacity)? { continue; } + self.refund(spent)?; // The merge doesn't fit: this layer and the next ones clipped to the same // base come in as layers of their own. unclipped = true; @@ -1131,7 +1156,10 @@ impl [f32; 3]> Builder<'_, F> { // Once, though a merge may draw it again. match self.noted.get_mut(i) { Some(true) => return Ok(()), - Some(n) => *n = true, + Some(n) => { + *n = true; + self.noted_log.push(i); + } None => {} } let (content, empty, effects, vector_mask) = { @@ -1151,6 +1179,23 @@ impl [f32; 3]> Builder<'_, F> { Ok(()) } + /// What [`Self::note`] has counted so far: the length of its log, and the counts. + fn noted_so_far(&self) -> (usize, [usize; 5]) { + let n = &self.notes; + (self.noted_log.len(), [n.types, n.adjustments, n.fills, n.effects, n.vector_masks]) + } + + /// Forget what [`Self::note`] counted since `so_far`, for layers that are left out. + fn unnote(&mut self, (logged, counts): (usize, [usize; 5])) { + for i in self.noted_log.split_off(logged) { + if let Some(n) = self.noted.get_mut(i) { + *n = false; + } + } + let n = &mut self.notes; + [n.types, n.adjustments, n.fills, n.effects, n.vector_masks] = counts; + } + /// Count record `i` as a layer whose knockout isn't applied (once). fn unknock(&mut self, i: usize) { if let Some(s) = self.unknocked.get_mut(i) @@ -1231,13 +1276,17 @@ impl [f32; 3]> Builder<'_, F> { let mut out: Vec> = vec![]; for mut u in self.units(items, keep_hidden)? { if self.knocks(&u, &out, level)? { - // A hidden layer that would need the merge is left out. - if !u.visible { - self.skip(u.record); - continue; - } - let saved = self.notes.counts(self.skip_log.len(), self.unknock_log.len(), self.blank_log.len()); + let saved = self.saved(); + let noted = self.noted_so_far(); match self.knock(&out, &u)? { + // A hidden layer that would need the merge is left out, and nothing its drawing + // counted is counted. + Knocked::Merged(_) | Knocked::TooLarge if !u.visible => { + self.restore(saved)?; + self.unnote(noted); + self.skip(u.record); + continue; + } Knocked::Merged(canvas) => { self.take_merge(&mut out, &u, canvas); if let Blend::Other(other) = u.blend @@ -1251,7 +1300,7 @@ impl [f32; 3]> Builder<'_, F> { // with the hidden layers its drawing left out (see `kept`). Knocked::Nothing => {} Knocked::TooLarge => { - self.restore(saved); + self.restore(saved)?; self.unknock(u.record); } } @@ -1266,7 +1315,7 @@ impl [f32; 3]> Builder<'_, F> { continue; } // A merge that can't be made counts nothing its groups would have counted. - let saved = self.notes.counts(self.skip_log.len(), self.unknock_log.len(), self.blank_log.len()); + let saved = self.saved(); let made = match out.as_mut_slice() { // Onto the previous merge alone: composited onto its canvas, in place. [prev] if prev.is_merge() => { @@ -1299,7 +1348,7 @@ impl [f32; 3]> Builder<'_, F> { self.notes.merged.push(other.label()); } } else { - self.restore(saved); + self.restore(saved)?; self.notes.unmerged += 1; u.blend = Blend::Mode(BlendMode::Normal); out.push(u); @@ -1308,8 +1357,15 @@ impl [f32; 3]> Builder<'_, F> { Ok(out) } - /// The counts as they were before a merge that couldn't be made. - fn restore(&mut self, c: Counts) { + /// The counts as they are, for [`Self::restore`]. + fn saved(&self) -> Counts { + self.notes.counts(self.spent.get(), self.skip_log.len(), self.unknock_log.len(), self.blank_log.len()) + } + + /// The counts as they were before a merge that couldn't be made, the bytes it spent counted as + /// wasted (see [`Self::refund`]). + fn restore(&mut self, c: Counts) -> Result<(), String> { + self.refund(c.spent)?; for i in self.skip_log.split_off(c.skipped) { if let Some(s) = self.skipped.get_mut(i) { *s = false; @@ -1345,6 +1401,7 @@ impl [f32; 3]> Builder<'_, F> { } self.notes.merged.truncate(c.merged); self.notes.unmerged = c.unmerged; + Ok(()) } /// The visible units `below` with `top` composited over them; `None` when the canvas would need @@ -1424,15 +1481,14 @@ impl [f32; 3]> Builder<'_, F> { return Ok(Knocked::TooLarge); } // Nothing below draws. - if acc.is_none() { + let Some(below) = acc.as_ref() else { return Ok(Knocked::Nothing) }; + // At 0 fill it draws nothing of its own: where it cuts no painted pixel below, no canvas for + // the merge is needed. + if fill <= 0.0 && !cuts_paint(below, &k, top.blend, opacity, top.record) { return Ok(Knocked::Nothing); } let clear = |c: &Canvas| c.px.iter().all(|p| p[3] <= 0.0); - let below_clear = acc.as_ref().is_some_and(clear); - // Nothing below to cut, and nothing of its own drawn at 0 fill: no canvas for the merge is needed. - if below_clear && fill <= 0.0 { - return Ok(Knocked::Nothing); - } + let below_clear = clear(below); if !knock_onto(&mut acc, &k, top.blend, fill, opacity, top.record, self.room(), &|n| self.spend(n))? { return Ok(Knocked::TooLarge); } @@ -1797,6 +1853,15 @@ fn knock_onto( Ok(true) } +/// Does `knock`, as [`knock_onto`] takes it, clear any of a pixel of `below` that has paint? +fn cuts_paint(below: &Canvas, knock: &Canvas, blend: Blend, opacity: f32, record: usize) -> bool { + let (kw, opacity) = (knock.width.max(1), opacity.clamp(0.0, 1.0)); + knock.px.iter().enumerate().any(|(k, s)| { + let (x, y) = (knock.left + (k % kw) as i64, knock.top + (k / kw) as i64); + below.get(x, y).is_some_and(|b| b[3] > 0.0) && coverage(blend, s[3].clamp(0.0, 1.0) * opacity, x, y, record) > 0.0 + }) +} + /// `acc` grown, when it doesn't already, to a canvas covering itself and `src` (a new one counted /// with `spend`). `false`, with `acc` as it was, when the canvases held, `acc` and `src` and a /// larger canvas when one is needed, would take more than `max_alloc` bytes. @@ -1871,6 +1936,7 @@ pub(super) fn import( layers: 0, notes: Notes::default(), noted: vec![false; records.len()], + noted_log: vec![], skipped: vec![false; records.len()], skip_log: vec![], unknocked: vec![false; records.len()], @@ -1881,6 +1947,7 @@ pub(super) fn import( unclip_log: vec![], kept: vec![false; records.len()], spent: Cell::new(0), + wasted: Cell::new(0), painted: Cell::new(0), blank: vec![None; records.len()], laid_blank: vec![false; records.len()], diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 6324ffcce5..c5be312153 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -753,7 +753,8 @@ fn knockouts_that_arent_applied_are_said() { } /// A knockout that changes nothing below it leaves the layers apart, hidden ones included: one at 0 -/// opacity, and one at 0 fill over layers that are transparent. At 0 fill over painted layers, and +/// opacity, one at 0 fill over layers that are transparent or beside their painted pixels, and one +/// whose layer mask hides all of it. At 0 fill over painted layers, and /// at a fill over transparent ones, it still merges. A knockout at 0 fill over a transparent layer /// stays apart without a warning when their merge would need more memory than allowed. #[test] @@ -779,16 +780,40 @@ fn knockouts_that_change_nothing_keep_the_layers_apart() { let (names, warnings) = if apart { (vec!["Lower", "Hidden", "Cut"], json!([])) } else { (vec!["Lower + Cut"], json!([HIDDEN_1])) }; assert_eq!((inner(&s), &r["warnings"]), (names.iter().map(|n| n.to_string()).collect(), &warnings), "{alpha} {fill} {opacity}: {r}"); } - // A hidden knockout that needs no merge comes in with hidden layers: at 0 opacity, and with - // nothing below it in its group. + // A hidden knockout that needs no merge comes in with hidden layers: at 0 opacity, with nothing + // below it in its group, at 0 fill beside the painted pixels below it, and with a layer mask that + // hides all of it. let hidden_cut = |opacity: u8| L { hidden: true, ..cut(0, opacity) }; + let beside = L { hidden: true, ..knockout(layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]), 1, 0) }; + let masked = L { hidden: true, mask: Some(([0, 0, 2, 2], 0, 0, vec![0; 4])), ..cut(255, 255) }; for (layers, names) in [ (vec![group_end(), lower(255), hidden_cut(0), group("Group", b"norm")], vec!["Lower", "Cut"]), (vec![group_end(), hidden_cut(255), group("Group", b"norm")], vec!["Cut"]), + (vec![group_end(), layer("Lower", [2, 2, 4, 4], [255, 0, 0, 255]), beside, group("Group", b"norm")], vec!["Lower", "Cut"]), + (vec![group_end(), lower(255), masked.clone(), group("Group", b"norm")], vec!["Lower", "Cut"]), ] { let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true})); assert_eq!((inner(&s), &r["warnings"]), (names.iter().map(|n| n.to_string()).collect(), &json!([])), "{r}"); } + // With the mask switched off it would need the merge, and is left out. + let unmasked = L { mask: Some(([0, 0, 2, 2], 0, 2, vec![0; 4])), ..masked }; + let (s, r) = open(&file(4, 4, &[group_end(), lower(255), unmasked, group("Group", b"norm")], 8, false, false), json!({"hiddenLayers": true})); + assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{r}"); + // A hidden knockout group that would need the merge is counted once, as a hidden layer left out: + // its type layer and its own hidden layer aren't counted. + let mut words = layer("Words", [0, 0, 2, 2], [0, 0, 0, 255]); + words.blocks.push((*b"TySh", vec![0; 4])); + let layers = [ + group_end(), + lower(255), + group_end(), + words, + L { hidden: true, ..layer("Inner", [0, 0, 2, 2], [0, 0, 255, 255]) }, + L { hidden: true, ..knockout(group("Cut", b"norm"), 1, 255) }, + group("Group", b"norm"), + ]; + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true})); + assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{r}"); } /// With hidden layers asked for, the hidden layers of a group drawn for a knockout or a clip that @@ -821,25 +846,48 @@ fn hidden_layers_of_a_group_drawn_for_a_merge_not_made_come_in() { } /// A knockout's merge whose canvases would need more memory than allowed leaves the layers apart, -/// with a warning. +/// with a warning. One at 0 fill beside the painted pixels below it cuts nothing, and stays apart +/// whatever the memory. #[test] fn a_knockout_merge_past_the_memory_allowed_leaves_the_layers_apart() { let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; - let layers = [ - group_end(), - layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]), - knockout(layer("Cut", [2, 2, 4, 4], [0, 0, 255, 255]), 1, 0), - group("Group", b"norm"), - ]; - let f = file(4, 4, &layers, 8, false, false); + let stack = |cut: [i32; 4]| { + let layers = [ + group_end(), + layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]), + knockout(layer("Cut", cut, [0, 0, 255, 255]), 1, 0), + group("Group", b"norm"), + ]; + file(4, 4, &layers, 8, false, false) + }; + let names = |doc: &vectorcraft_doc::Document| doc.layers[0].children().unwrap().iter().map(|c| name(c).to_string()).collect::>(); + let f = stack([1, 1, 3, 3]); // Each 2 × 2 layer fits 128 bytes (16 a pixel), but not the canvas of the layer below with the // knockout's canvas held beside it. let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap().unwrap(); - assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Lower", "Cut"]); + assert_eq!(names(&doc), ["Lower", "Cut"]); assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]); let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); - assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Lower + Cut"]); + assert_eq!(names(&doc), ["Lower + Cut"]); assert!(warnings.is_empty(), "{warnings:?}"); + let (doc, warnings) = psdlayers::import(&stack([2, 2, 4, 4]), false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(names(&doc), ["Lower", "Cut"]); + assert!(warnings.is_empty(), "{warnings:?}"); +} + +/// A knockout merge that can't be made leaves the import the whole allowance for reading the layers +/// apart: here the merge decodes 22 layers over one another before the layer beside them makes its +/// canvas too large, which used up nearly all of eight times 64 KiB. +#[test] +fn a_knockout_merge_not_made_leaves_room_to_read_the_layers() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let mut layers = vec![group_end()]; + layers.extend((0..22).map(|_| layer("Lower", [0, 0, 32, 32], [255, 0, 0, 255]))); + layers.push(layer("Beside", [0, 64, 32, 96], [0, 255, 0, 255])); + layers.extend([knockout(layer("Cut", [0, 0, 32, 32], [0, 0, 255, 255]), 1, 0), group("Group", b"norm")]); + let (doc, warnings) = psdlayers::import(&file(96, 32, &layers, 8, false, false), false, 64 << 10, cms).unwrap().unwrap(); + assert_eq!(doc.layers[0].children().unwrap().len(), 24, "{warnings:?}"); + assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]); } /// A Dissolve knockout at part opacity clears each pixel below it fully or not at all, at the share diff --git a/docs/mcp.md b/docs/mcp.md index 048fc5f557..e641490062 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9906,7 +9906,7 @@ The rest are VectorCraft's own rules: in that group: where it has pixels, shaped by its layer mask, they are cleared to transparency, it is drawn there at its fill opacity, and its opacity fades the result back toward them. In a Pass Through group this applies only when it and the visible layers below it are in Normal mode. A knockout at 0 opacity, one that draws nothing, one - with nothing visible below it, and one at 0 fill over layers that are all transparent are not merged for the + with nothing visible below it, and one at 0 fill that covers none of their painted pixels are not merged for the knockout; one in a mode VectorCraft lacks is still merged by its mode. - A merged layer is named after the layers it holds, joined with ` + `. - A layer name the file stores only as a one-byte Pascal string, without its Unicode name, is read as Mac Roman. @@ -9928,9 +9928,10 @@ The rest are VectorCraft's own rules: Each layer's pixels must fit the memory allowed for one image, and the pixels of all the layers and masks, with the canvases the merges make, must together fit eight times that; a file past either limit opens as its merged image, -with a warning. The canvases one step of a merge holds at once must also fit the memory allowed for one image; when -they don't, the layer that needed the merge comes in alone, with a warning: in the Normal mode, or as a layer of its -own instead of clipped. +with a warning. The pixels and canvases of merges that aren't made count against a second limit of the same size. The +canvases one step of a merge holds at once must also fit the memory allowed for one image; when they don't, the +layer that needed the merge comes in alone, with a warning: in the Normal mode, as a layer of its own instead of +clipped, or without its knockout. ```json {"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/poster.psd","hiddenLayers":true}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c7e1723f05..14bf39612f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2141,7 +2141,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur EPS export and EPS Save make each file's PNG thumbnail from its TIFF preview, averaging the preview's pixels down to the thumbnail's size on white, instead of drawing the document a second time; a file without a preview still draws its thumbnail (`crates/engine/src/cmd/fileio/tests_eps.rs`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill over layers that are all transparent, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none, and files that name no clipping path come in as before (`crates/engine/src/cmd/fileio/tests_psdread.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). From 4b2412eaf9833b0b13046b5967a39b10d553e53e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 06:57:06 -0800 Subject: [PATCH 13/34] Docs: G5 Missing line counts eleven built-in brush libraries docs/gaps.md's G5 Missing line said "beyond the ten shipped", while BUILTIN in crates/engine/src/cmd/brushlib.rs lists eleven libraries and the G5 Done text above already names all eleven. --- docs/gaps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/gaps.md b/docs/gaps.md index ea34b655ca..1c57f3dbfc 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -708,7 +708,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Fine Grain, Canvas Weave, Burlap Sack, Cracked Glaze, Mosaic Floor, Quilted Squares, Leaded Glass and Damp Paper, painted with the texture effects; User Defined; Other Library…; `graphicStyle.libraries`, `graphicStyle.addFromLibrary`). -- **Missing:** more built-in brush libraries beyond the ten shipped (and further graphic-style libraries beyond the eleven shipped, and further symbol libraries beyond Basic +- **Missing:** more built-in brush libraries beyond the eleven shipped (and further graphic-style libraries beyond the eleven shipped, and further symbol libraries beyond Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write. - **Estimate:** 3–13 h (estimated). From bc1c1131c0ea43cf22da20d05697532d1db2c5ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 08:01:32 -0800 Subject: [PATCH 14/34] PSD import: merges being tried get their own allowance, and knockouts that cut nothing give it back - A knockout, clip or blend-mode merge being tried may use the whole import allowance beyond what was read before it. A merge that is made must still fit the allowance with everything read before it. - A knockout that turns out to cut nothing moves what its drawing read out of the allowance, as a merge that isn't made does. A hidden one also forgets what its drawing counted, so a later merge that leaves it out reports only the hidden layer. - A hidden layer in a mode VectorCraft lacks is left out before any knockout drawing, as before the knockout merge. - A knockout at 0 fill whose painted pixels lie outside the bounds of every layer below it is kept apart before their canvas is made. --- crates/engine/src/cmd/fileio/psdlayers.rs | 99 ++++++++++++++++--- .../engine/src/cmd/fileio/tests_psdlayers.rs | 54 +++++++++- docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 4 files changed, 139 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 598f75ff04..3779b72745 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -43,8 +43,9 @@ //! groups nest at most [`MAX_DEPTH`] deep (layers deeper than a document may nest merge into the //! group around them, with a warning), each layer's pixels, like the canvases one step of a //! merge holds together, must fit the memory allowed, and all the pixels decoded and the canvases -//! the merges make must fit [`TOTAL_DECODED`] times that. What the merges that can't be made, or -//! that a hidden layer would need, decoded and made is counted apart, against the same limit. +//! the merges make must fit [`TOTAL_DECODED`] times that. A merge being tried may take that much +//! past what was read before it. What the merges that aren't made, or that a hidden layer would +//! need, decoded and made is counted apart, against the same limit. use std::cell::Cell; use std::sync::Arc; @@ -849,6 +850,9 @@ struct Builder<'a, F> { /// Those bytes that merges not made, and merges a hidden layer would need, took: given back to /// `spent` and counted here instead, against the same limit. wasted: Cell, + /// `spent` when the innermost merge being tried began: until it is made or given up, it may + /// spend the whole allowance past that (see [`Self::spend`]). + trial: Cell, /// The layers whose pixels were read so far (each time they were). painted: Cell, /// What each group gave when drawn alone without reading any layer's pixels (nothing, or a @@ -872,16 +876,30 @@ impl [f32; 3]> Builder<'_, F> { } /// Count `bytes` of decoded pixels, or of a canvas a merge makes, against the whole import's - /// allowance, [`TOTAL_DECODED`] times the memory allowed for one image. + /// allowance, [`TOTAL_DECODED`] times the memory allowed for one image. While a merge is tried + /// (see [`Self::try_from_here`]), only what it spent counts against the allowance. fn spend(&self, bytes: u64) -> Result<(), String> { let total = self.spent.get().saturating_add(bytes); self.spent.set(total); - if total > self.max_alloc.saturating_mul(TOTAL_DECODED) { + if total.saturating_sub(self.trial.get()) > self.max_alloc.saturating_mul(TOTAL_DECODED) { return Err("the PSD file's layers take more memory to read than allowed".into()); } Ok(()) } + /// Start trying a merge that may not be made: what it spends counts against the whole + /// allowance, however much was spent before it. Gives what [`Self::tried`] takes back. + fn try_from_here(&self) -> u64 { + self.trial.replace(self.spent.get()) + } + + /// End the merge tried since [`Self::try_from_here`] gave `outer`. A merge that is `made` keeps + /// what it spent, which must then fit the allowance with what was spent before it. + fn tried(&self, outer: u64, made: bool) -> Result<(), String> { + self.trial.set(outer); + if made { self.spend(0) } else { Ok(()) } + } + /// Move the bytes spent since `spent` was the count to [`Self::wasted`], which has an allowance /// of its own as large: what a merge that isn't made decoded doesn't take the room for reading /// the layers apart. @@ -1030,7 +1048,10 @@ impl [f32; 3]> Builder<'_, F> { u.base = true; } let spent = self.spent.get(); - if !unclipped && self.clip(&mut out, b, &body, i, &name, blend, opacity)? { + let outer = self.try_from_here(); + let made = !unclipped && self.clip(&mut out, b, &body, i, &name, blend, opacity)?; + self.tried(outer, made)?; + if made { continue; } self.refund(spent)?; @@ -1275,10 +1296,19 @@ impl [f32; 3]> Builder<'_, F> { } let mut out: Vec> = vec![]; for mut u in self.units(items, keep_hidden)? { + // A hidden layer in a mode VectorCraft lacks would need the merge for its mode: it is left + // out without being drawn. + if !u.visible && matches!(u.blend, Blend::Other(_)) { + self.skip(u.record); + continue; + } if self.knocks(&u, &out, level)? { let saved = self.saved(); let noted = self.noted_so_far(); - match self.knock(&out, &u)? { + let outer = self.try_from_here(); + let knocked = self.knock(&out, &u)?; + self.tried(outer, u.visible && matches!(knocked, Knocked::Merged(_)))?; + match knocked { // A hidden layer that would need the merge is left out, and nothing its drawing // counted is counted. Knocked::Merged(_) | Knocked::TooLarge if !u.visible => { @@ -1297,8 +1327,14 @@ impl [f32; 3]> Builder<'_, F> { continue; } // Nothing below it, or nothing of its own, to knock out: it comes in as a layer, - // with the hidden layers its drawing left out (see `kept`). - Knocked::Nothing => {} + // with the hidden layers its drawing left out (see `kept`). What its drawing + // read is read again when it comes in. A hidden one may still be left out by a + // later merge: what its drawing counted is counted when it comes in instead. + Knocked::Nothing if !u.visible => { + self.restore(saved)?; + self.unnote(noted); + } + Knocked::Nothing => self.refund(saved.spent)?, Knocked::TooLarge => { self.restore(saved)?; self.unknock(u.record); @@ -1309,13 +1345,9 @@ impl [f32; 3]> Builder<'_, F> { out.push(u); continue; }; - // A hidden layer that would need the merge is left out. - if !u.visible { - self.skip(u.record); - continue; - } // A merge that can't be made counts nothing its groups would have counted. let saved = self.saved(); + let outer = self.try_from_here(); let made = match out.as_mut_slice() { // Onto the previous merge alone: composited onto its canvas, in place. [prev] if prev.is_merge() => { @@ -1343,6 +1375,7 @@ impl [f32; 3]> Builder<'_, F> { None => false, }, }; + self.tried(outer, made)?; if made { if !self.notes.merged.contains(&other.label()) { self.notes.merged.push(other.label()); @@ -1465,6 +1498,10 @@ impl [f32; 3]> Builder<'_, F> { Drawn::Canvas(c) if c.px.iter().all(|p| p[3] <= 0.0) => return Ok(Knocked::Nothing), Drawn::Canvas(c) => c, }; + // At 0 fill, beside every layer below it, it cuts nothing: no canvas for them is needed. + if fill <= 0.0 && self.beside(below, &k)? { + return Ok(Knocked::Nothing); + } // The layer's canvas is held while the units below are drawn. let bytes = 16 * k.px.len() as u64; self.held = self.held.saturating_add(bytes); @@ -1499,6 +1536,41 @@ impl [f32; 3]> Builder<'_, F> { Ok(acc.map_or(Knocked::Nothing, Knocked::Merged)) } + /// Do the pixels `knock` paints lie outside the bounds of every visible unit `below`? Only the + /// bounds of layers and of merged canvases are known without drawing them: with a group below, + /// `false`. + fn beside(&self, below: &[Unit<'_>], knock: &Canvas) -> Result { + let width = knock.width.max(1); + let mut painted: Option<[i64; 4]> = None; + for (k, _) in knock.px.iter().enumerate().filter(|(_, p)| p[3] > 0.0) { + let (x, y) = (knock.left + (k % width) as i64, knock.top + (k / width) as i64); + painted = Some(painted.map_or([x, y, x + 1, y + 1], |[l, t, r, b]| [l.min(x), t.min(y), r.max(x + 1), b.max(y + 1)])); + } + let Some([left, top, right, bottom]) = painted else { return Ok(true) }; + for u in below.iter().filter(|u| u.visible) { + let [l, t, r, b] = match &u.body { + Body::Merged(c) => [c.left, c.top, c.left + c.width as i64, c.top + c.height as i64], + Body::Layer(i) => { + let rec = self.record(*i)?; + match rec.content { + Content::Adjustment => continue, + Content::Solid(Some(_)) if rec.color_over_canvas() => [0, 0, i64::from(self.h.width), i64::from(self.h.height)], + _ => { + let (w, h) = rec.bounds.size(); + let (l, t) = (i64::from(rec.bounds.left), i64::from(rec.bounds.top)); + [l, t, l + w as i64, t + h as i64] + } + } + } + Body::Group(..) => return Ok(false), + }; + if l < right && left < r && t < bottom && top < b { + return Ok(false); + } + } + Ok(true) + } + /// The bytes a merge step may still take: the memory allowed, less the copies of what is below /// the pass-through groups being merged. fn room(&self) -> u64 { @@ -1948,6 +2020,7 @@ pub(super) fn import( kept: vec![false; records.len()], spent: Cell::new(0), wasted: Cell::new(0), + trial: Cell::new(0), painted: Cell::new(0), blank: vec![None; records.len()], laid_blank: vec![false; records.len()], diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index c5be312153..d197658c20 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -807,13 +807,26 @@ fn knockouts_that_change_nothing_keep_the_layers_apart() { group_end(), lower(255), group_end(), - words, + words.clone(), L { hidden: true, ..layer("Inner", [0, 0, 2, 2], [0, 0, 255, 255]) }, L { hidden: true, ..knockout(group("Cut", b"norm"), 1, 255) }, group("Group", b"norm"), ]; let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true})); assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{r}"); + // One whose layer mask hides all of it needs no merge, but a knockout above it merges the layers + // and leaves it out: it is counted once, without its type layer. + let layers = [ + group_end(), + lower(255), + group_end(), + words, + L { hidden: true, mask: Some(([0, 0, 2, 2], 0, 0, vec![0; 4])), ..knockout(group("Masked", b"norm"), 1, 255) }, + cut(0, 255), + group("Group", b"norm"), + ]; + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true})); + assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower + Cut".to_string()], &json!([HIDDEN_1])), "{r}"); } /// With hidden layers asked for, the hidden layers of a group drawn for a knockout or a clip that @@ -870,14 +883,18 @@ fn a_knockout_merge_past_the_memory_allowed_leaves_the_layers_apart() { let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); assert_eq!(names(&doc), ["Lower + Cut"]); assert!(warnings.is_empty(), "{warnings:?}"); - let (doc, warnings) = psdlayers::import(&stack([2, 2, 4, 4]), false, 1 << 20, cms).unwrap().unwrap(); - assert_eq!(names(&doc), ["Lower", "Cut"]); - assert!(warnings.is_empty(), "{warnings:?}"); + for max_alloc in [128, 1 << 20] { + let (doc, warnings) = psdlayers::import(&stack([2, 2, 4, 4]), false, max_alloc, cms).unwrap().unwrap(); + assert_eq!(names(&doc), ["Lower", "Cut"], "{max_alloc}"); + assert!(warnings.is_empty(), "{max_alloc}: {warnings:?}"); + } } /// A knockout merge that can't be made leaves the import the whole allowance for reading the layers /// apart: here the merge decodes 22 layers over one another before the layer beside them makes its -/// canvas too large, which used up nearly all of eight times 64 KiB. +/// canvas too large, which used up nearly all of eight times 64 KiB. The merge has that allowance +/// also after five layers below the group were read, and a knockout at 0 fill over 22 transparent +/// layers, which cuts no paint after they are drawn, leaves the same room. #[test] fn a_knockout_merge_not_made_leaves_room_to_read_the_layers() { let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; @@ -888,6 +905,33 @@ fn a_knockout_merge_not_made_leaves_room_to_read_the_layers() { let (doc, warnings) = psdlayers::import(&file(96, 32, &layers, 8, false, false), false, 64 << 10, cms).unwrap().unwrap(); assert_eq!(doc.layers[0].children().unwrap().len(), 24, "{warnings:?}"); assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]); + let mut after_five = vec![layer("Outside", [0, 0, 32, 32], [0, 0, 0, 255]); 5]; + after_five.extend(layers); + let (doc, warnings) = psdlayers::import(&file(96, 32, &after_five, 8, false, false), false, 64 << 10, cms).unwrap().unwrap(); + assert_eq!((doc.layers.len(), doc.layers[5].children().unwrap().len()), (6, 24), "{warnings:?}"); + assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]); + let mut layers = vec![group_end()]; + layers.extend((0..22).map(|_| layer("Lower", [0, 0, 32, 32], [255, 0, 0, 0]))); + layers.extend([knockout(layer("Cut", [0, 0, 32, 32], [0, 0, 255, 255]), 1, 0), group("Group", b"norm")]); + let (doc, warnings) = psdlayers::import(&file(32, 32, &layers, 8, false, false), false, 64 << 10, cms).unwrap().unwrap(); + assert_eq!(doc.layers[0].children().unwrap().len(), 23, "{warnings:?}"); + assert!(warnings.is_empty(), "{warnings:?}"); +} + +/// A hidden knockout in a mode VectorCraft lacks is left out without being drawn, hidden layers +/// asked for: here its pixels are larger than the memory allowed for one image. +#[test] +fn a_hidden_knockout_in_a_mode_vectorcraft_lacks_is_left_out_unread() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let layers = [ + group_end(), + layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]), + L { hidden: true, blend: b"diss", ..knockout(layer("Cut", [0, 0, 8, 8], [0, 0, 255, 255]), 1, 255) }, + group("Group", b"norm"), + ]; + let (doc, warnings) = psdlayers::import(&file(8, 8, &layers, 8, false, false), true, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Lower"]); + assert_eq!(warnings, [HIDDEN_1]); } /// A Dissolve knockout at part opacity clears each pixel below it fully or not at all, at the share diff --git a/docs/mcp.md b/docs/mcp.md index e641490062..a71a4d6943 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9928,7 +9928,9 @@ The rest are VectorCraft's own rules: Each layer's pixels must fit the memory allowed for one image, and the pixels of all the layers and masks, with the canvases the merges make, must together fit eight times that; a file past either limit opens as its merged image, -with a warning. The pixels and canvases of merges that aren't made count against a second limit of the same size. The +with a warning. A merge being tried may use the whole of that limit beyond what was read before it. The pixels and +canvases of merges that aren't made, including knockouts that turn out to cut nothing, then count against a second +limit of the same size instead. The canvases one step of a merge holds at once must also fit the memory allowed for one image; when they don't, the layer that needed the merge comes in alone, with a warning: in the Normal mode, as a layer of its own instead of clipped, or without its knockout. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 14bf39612f..ca57638462 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2141,7 +2141,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur EPS export and EPS Save make each file's PNG thumbnail from its TIFF preview, averaging the preview's pixels down to the thumbnail's size on white, instead of drawing the document a second time; a file without a preview still draws its thumbnail (`crates/engine/src/cmd/fileio/tests_eps.rs`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none, and files that name no clipping path come in as before (`crates/engine/src/cmd/fileio/tests_psdread.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). From 768edc48fee566afddc24327affee5c7e5e7a6ab Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 11:36:39 -0800 Subject: [PATCH 15/34] Test stale sampler double-click release ownership --- .../tests/image_trace_ignore_sampler.rs | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs index edd197195d..bc9fd97eb1 100644 --- a/crates/ui-egui/tests/image_trace_ignore_sampler.rs +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -405,6 +405,92 @@ fn a_stale_sampler_and_canvas_press_in_one_frame_do_not_reselect_the_source() { assert_eq!(app.session.active().unwrap().selection.objects, vec![target]); } +/// A stale sampler consumes its second press, including the release's double-click action. +#[test] +fn a_consumed_stale_sampler_press_does_not_complete_a_double_click() { + fn frame_at(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec) { + let mut raw = RawInput { + time: Some(time), + events, + focused: true, + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1400.0))), + ..Default::default() + }; + app.raw_input_hook(ctx, &mut raw); + let mut out = ctx.run_ui(raw, |ui| { + app.tick(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + assert_eq!(ctx.time(), time, "the real UI frame uses the supplied gesture time"); + } + + // Run the legitimate control first: this geometry and these real UI frames must isolate. + for sampler in [false, true] { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let source = selected(&app).id; + app.session.prefs.double_click_to_isolate = true; + let first = app.run("shape.rectangle", json!({"x": 100, "y": 140, "width": 20, "height": 20})).unwrap()["id"].clone(); + let second = app.run("shape.rectangle", json!({"x": 120, "y": 140, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [first.clone(), second.clone()], "color": "#cc3322"})).unwrap(); + app.run("select.set", json!({"ids": [first, second]})).unwrap(); + let group = NodeId(app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [source.0]})).unwrap(); + settle(&mut app, &ctx); + let point = Point::new(110.0, 150.0); + assert!(point.x < source_point(&app, 0.0).x - 40.0, "the group is outside the source image"); + if sampler { + click_control(&mut app, &ctx, SAMPLE_TIP); + assert_eq!(app.session.tool_id(), "eyedropper"); + assert!(app.ui.trace_ignore_sampler.is_some()); + } + let at = canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), ctx.zoom_factor()).to_screen(point); + assert!(app.canvas_rect.unwrap().contains(at)); + let (delay, hold) = ctx.options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_duration)); + assert!(delay.is_finite() && delay > 0.0 && hold.is_finite() && hold > 0.0); + let step = delay.min(hold) / 8.0; + // Leave the panel-button click outside the interval; only these two canvas clicks count. + let start = ctx.time() + delay + 1.0; + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame_at(&mut app, &ctx, start, vec![Event::PointerMoved(at), press(true)]); + frame_at(&mut app, &ctx, start + step, vec![press(false)]); + assert!(!ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)), "the first canvas click is single"); + assert_eq!(app.session.active().unwrap().isolation, None); + + if sampler { + assert_eq!(app.session.tool_id(), "eyedropper", "the first click is a source-image miss"); + assert!(app.ui.trace_ignore_sampler.is_some(), "the miss keeps sampling armed"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![source], "the miss does not select the group"); + // No intervening UI frame: canvas refresh must consume the stale second press. + app.run("select.none", json!({})).unwrap(); + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + frame_at(&mut app, &ctx, start + 3.0 * step, vec![press(true)]); + assert_eq!(app.session.tool_id(), "selection"); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert_eq!(app.session.active().unwrap().selection, selection, "the second press was consumed"); + frame_at(&mut app, &ctx, start + 4.0 * step, vec![press(false)]); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)), "egui recognizes the timed release as a double-click"); + let state = app.session.active().unwrap(); + assert_eq!(state.isolation, None, "the release of the consumed press must not isolate the group"); + assert_eq!(state.doc, document); + assert_eq!(state.selection, selection); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert_eq!(app.session.paint, paint); + assert_eq!(app.session.tool_id(), "selection"); + } else { + assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the ordinary first click really selects the group"); + frame_at(&mut app, &ctx, start + 3.0 * step, vec![press(true)]); + frame_at(&mut app, &ctx, start + 4.0 * step, vec![press(false)]); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "the legitimate unarmed double-click isolates the same group"); + } + } +} + fn capture_canvas(app: &mut VectorcraftApp, ctx: &egui::Context) -> (vectorcraft_render::Rendered, CacheKey) { app.canvas.key = None; // force a complete upload, not a partial delta requiring reconstruction let mut out = frame(app, ctx, vec![]); From 42f69621a23998e2ebbb0ac76992feab52395bb3 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 12:12:05 -0800 Subject: [PATCH 16/34] Keep a cancelled trace sampler press owned through release --- crates/ui-egui/src/canvas.rs | 19 +++++++++++++++++-- .../tests/image_trace_ignore_sampler.rs | 11 +++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e401b0a70b..c10ca61fb4 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -466,9 +466,24 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } -/// A press arriving with an invalidated sampler is consumed, not given to its restored tool. +/// A press arriving with an invalidated sampler and its release belong to that cancelled pick. fn input_after_sampler_refresh(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect, cancelled: bool) { - if !cancelled || !ui.input(|i| i.pointer.any_pressed()) { + let (pressed, released, down, any_pressed) = ui.input(|i| { + (i.pointer.primary_pressed(), i.pointer.primary_released(), i.pointer.primary_down(), i.pointer.any_pressed()) + }); + let consumed_primary = ui.data_mut(|data| { + let id = resp.id.with("image-trace-consumed-primary"); + // A fresh press replaces any ownership whose release this canvas did not observe. + let consumed = if pressed { cancelled } else { data.get_temp::(id).unwrap_or(false) }; + if consumed && down { + data.insert_temp(id, true); + } else { + data.remove::(id); + } + // egui classifies double/triple clicks on release, independently of the tool's Down. + consumed && (pressed || released || down) + }); + if !consumed_primary && (!cancelled || !any_pressed) { canvas_input(app, ui, resp, rect); } } diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs index bc9fd97eb1..5a61946659 100644 --- a/crates/ui-egui/tests/image_trace_ignore_sampler.rs +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -481,6 +481,17 @@ fn a_consumed_stale_sampler_press_does_not_complete_a_double_click() { assert_eq!((state.history.undo.len(), state.history.redo.len()), history); assert_eq!(app.session.paint, paint); assert_eq!(app.session.tool_id(), "selection"); + // The consumed release must not take the next independent ordinary gesture with it. + let next = start + 4.0 * step + delay + 1.0; + frame_at(&mut app, &ctx, next, vec![Event::PointerMoved(at), press(true)]); + frame_at(&mut app, &ctx, next + step, vec![press(false)]); + assert!(!ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the next ordinary first click selects the group"); + assert_eq!(app.session.active().unwrap().isolation, None); + frame_at(&mut app, &ctx, next + 3.0 * step, vec![press(true)]); + frame_at(&mut app, &ctx, next + 4.0 * step, vec![press(false)]); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "the next ordinary double-click still isolates the group"); } else { assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the ordinary first click really selects the group"); frame_at(&mut app, &ctx, start + 3.0 * step, vec![press(true)]); From 149cc169694a82fb82390b9979e7478874b9c2ac Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 12:16:00 -0800 Subject: [PATCH 17/34] Format the cancelled sampler pointer-state binding --- crates/ui-egui/src/canvas.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index c10ca61fb4..7392ad73b8 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -468,9 +468,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { /// A press arriving with an invalidated sampler and its release belong to that cancelled pick. fn input_after_sampler_refresh(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect, cancelled: bool) { - let (pressed, released, down, any_pressed) = ui.input(|i| { - (i.pointer.primary_pressed(), i.pointer.primary_released(), i.pointer.primary_down(), i.pointer.any_pressed()) - }); + let (pressed, released, down, any_pressed) = + ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_released(), i.pointer.primary_down(), i.pointer.any_pressed())); let consumed_primary = ui.data_mut(|data| { let id = resp.id.with("image-trace-consumed-primary"); // A fresh press replaces any ownership whose release this canvas did not observe. From a0e67959467a525d308b4327e3f31497847bbaef Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 12:39:58 -0800 Subject: [PATCH 18/34] Split sampler double-click scenarios into a focused helper --- .../tests/image_trace_ignore_sampler.rs | 149 +++++++++--------- 1 file changed, 76 insertions(+), 73 deletions(-) diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs index 5a61946659..6a05c7f086 100644 --- a/crates/ui-egui/tests/image_trace_ignore_sampler.rs +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -408,6 +408,12 @@ fn a_stale_sampler_and_canvas_press_in_one_frame_do_not_reselect_the_source() { /// A stale sampler consumes its second press, including the release's double-click action. #[test] fn a_consumed_stale_sampler_press_does_not_complete_a_double_click() { + // Run the legitimate control first: this geometry and these real UI frames must isolate. + check_sampler_double_click(false); + check_sampler_double_click(true); +} + +fn check_sampler_double_click(sampler: bool) { fn frame_at(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec) { let mut raw = RawInput { time: Some(time), @@ -425,80 +431,77 @@ fn a_consumed_stale_sampler_press_does_not_complete_a_double_click() { assert_eq!(ctx.time(), time, "the real UI frame uses the supplied gesture time"); } - // Run the legitimate control first: this geometry and these real UI frames must isolate. - for sampler in [false, true] { - let (mut app, ctx) = fixture(true, [37, 83, 149], false); - let source = selected(&app).id; - app.session.prefs.double_click_to_isolate = true; - let first = app.run("shape.rectangle", json!({"x": 100, "y": 140, "width": 20, "height": 20})).unwrap()["id"].clone(); - let second = app.run("shape.rectangle", json!({"x": 120, "y": 140, "width": 20, "height": 20})).unwrap()["id"].clone(); - app.run("paint.setFill", json!({"ids": [first.clone(), second.clone()], "color": "#cc3322"})).unwrap(); - app.run("select.set", json!({"ids": [first, second]})).unwrap(); - let group = NodeId(app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap()); - app.run("select.set", json!({"ids": [source.0]})).unwrap(); - settle(&mut app, &ctx); - let point = Point::new(110.0, 150.0); - assert!(point.x < source_point(&app, 0.0).x - 40.0, "the group is outside the source image"); - if sampler { - click_control(&mut app, &ctx, SAMPLE_TIP); - assert_eq!(app.session.tool_id(), "eyedropper"); - assert!(app.ui.trace_ignore_sampler.is_some()); - } - let at = canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), ctx.zoom_factor()).to_screen(point); - assert!(app.canvas_rect.unwrap().contains(at)); - let (delay, hold) = ctx.options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_duration)); - assert!(delay.is_finite() && delay > 0.0 && hold.is_finite() && hold > 0.0); - let step = delay.min(hold) / 8.0; - // Leave the panel-button click outside the interval; only these two canvas clicks count. - let start = ctx.time() + delay + 1.0; - let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; - frame_at(&mut app, &ctx, start, vec![Event::PointerMoved(at), press(true)]); - frame_at(&mut app, &ctx, start + step, vec![press(false)]); - assert!(!ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)), "the first canvas click is single"); - assert_eq!(app.session.active().unwrap().isolation, None); + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let source = selected(&app).id; + app.session.prefs.double_click_to_isolate = true; + let first = app.run("shape.rectangle", json!({"x": 100, "y": 140, "width": 20, "height": 20})).unwrap()["id"].clone(); + let second = app.run("shape.rectangle", json!({"x": 120, "y": 140, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [first.clone(), second.clone()], "color": "#cc3322"})).unwrap(); + app.run("select.set", json!({"ids": [first, second]})).unwrap(); + let group = NodeId(app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [source.0]})).unwrap(); + settle(&mut app, &ctx); + let point = Point::new(110.0, 150.0); + assert!(point.x < source_point(&app, 0.0).x - 40.0, "the group is outside the source image"); + if sampler { + click_control(&mut app, &ctx, SAMPLE_TIP); + assert_eq!(app.session.tool_id(), "eyedropper"); + assert!(app.ui.trace_ignore_sampler.is_some()); + } + let at = canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), ctx.zoom_factor()).to_screen(point); + assert!(app.canvas_rect.unwrap().contains(at)); + let (delay, hold) = ctx.options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_duration)); + assert!(delay.is_finite() && delay > 0.0 && hold.is_finite() && hold > 0.0); + let step = delay.min(hold) / 8.0; + // Leave the panel-button click outside the interval; only these two canvas clicks count. + let start = ctx.time() + delay + 1.0; + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame_at(&mut app, &ctx, start, vec![Event::PointerMoved(at), press(true)]); + frame_at(&mut app, &ctx, start + step, vec![press(false)]); + assert!(!ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)), "the first canvas click is single"); + assert_eq!(app.session.active().unwrap().isolation, None); - if sampler { - assert_eq!(app.session.tool_id(), "eyedropper", "the first click is a source-image miss"); - assert!(app.ui.trace_ignore_sampler.is_some(), "the miss keeps sampling armed"); - assert_eq!(app.session.active().unwrap().selection.objects, vec![source], "the miss does not select the group"); - // No intervening UI frame: canvas refresh must consume the stale second press. - app.run("select.none", json!({})).unwrap(); - let state = app.session.active().unwrap(); - let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); - let history = (state.history.undo.len(), state.history.redo.len()); - let paint = app.session.paint.clone(); - frame_at(&mut app, &ctx, start + 3.0 * step, vec![press(true)]); - assert_eq!(app.session.tool_id(), "selection"); - assert!(app.ui.trace_ignore_sampler.is_none()); - assert_eq!(app.session.active().unwrap().selection, selection, "the second press was consumed"); - frame_at(&mut app, &ctx, start + 4.0 * step, vec![press(false)]); - assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)), "egui recognizes the timed release as a double-click"); - let state = app.session.active().unwrap(); - assert_eq!(state.isolation, None, "the release of the consumed press must not isolate the group"); - assert_eq!(state.doc, document); - assert_eq!(state.selection, selection); - assert_eq!(state.revision, revision); - assert_eq!((state.history.undo.len(), state.history.redo.len()), history); - assert_eq!(app.session.paint, paint); - assert_eq!(app.session.tool_id(), "selection"); - // The consumed release must not take the next independent ordinary gesture with it. - let next = start + 4.0 * step + delay + 1.0; - frame_at(&mut app, &ctx, next, vec![Event::PointerMoved(at), press(true)]); - frame_at(&mut app, &ctx, next + step, vec![press(false)]); - assert!(!ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); - assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the next ordinary first click selects the group"); - assert_eq!(app.session.active().unwrap().isolation, None); - frame_at(&mut app, &ctx, next + 3.0 * step, vec![press(true)]); - frame_at(&mut app, &ctx, next + 4.0 * step, vec![press(false)]); - assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); - assert_eq!(app.session.active().unwrap().isolation, Some(group), "the next ordinary double-click still isolates the group"); - } else { - assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the ordinary first click really selects the group"); - frame_at(&mut app, &ctx, start + 3.0 * step, vec![press(true)]); - frame_at(&mut app, &ctx, start + 4.0 * step, vec![press(false)]); - assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); - assert_eq!(app.session.active().unwrap().isolation, Some(group), "the legitimate unarmed double-click isolates the same group"); - } + if sampler { + assert_eq!(app.session.tool_id(), "eyedropper", "the first click is a source-image miss"); + assert!(app.ui.trace_ignore_sampler.is_some(), "the miss keeps sampling armed"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![source], "the miss does not select the group"); + // No intervening UI frame: canvas refresh must consume the stale second press. + app.run("select.none", json!({})).unwrap(); + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + frame_at(&mut app, &ctx, start + 3.0 * step, vec![press(true)]); + assert_eq!(app.session.tool_id(), "selection"); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert_eq!(app.session.active().unwrap().selection, selection, "the second press was consumed"); + frame_at(&mut app, &ctx, start + 4.0 * step, vec![press(false)]); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)), "egui recognizes the timed release as a double-click"); + let state = app.session.active().unwrap(); + assert_eq!(state.isolation, None, "the release of the consumed press must not isolate the group"); + assert_eq!(state.doc, document); + assert_eq!(state.selection, selection); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert_eq!(app.session.paint, paint); + assert_eq!(app.session.tool_id(), "selection"); + // The consumed release must not take the next independent ordinary gesture with it. + let next = start + 4.0 * step + delay + 1.0; + frame_at(&mut app, &ctx, next, vec![Event::PointerMoved(at), press(true)]); + frame_at(&mut app, &ctx, next + step, vec![press(false)]); + assert!(!ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the next ordinary first click selects the group"); + assert_eq!(app.session.active().unwrap().isolation, None); + frame_at(&mut app, &ctx, next + 3.0 * step, vec![press(true)]); + frame_at(&mut app, &ctx, next + 4.0 * step, vec![press(false)]); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "the next ordinary double-click still isolates the group"); + } else { + assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the ordinary first click really selects the group"); + frame_at(&mut app, &ctx, start + 3.0 * step, vec![press(true)]); + frame_at(&mut app, &ctx, start + 4.0 * step, vec![press(false)]); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "the legitimate unarmed double-click isolates the same group"); } } From a8041ce586df6486644a0a3a4b1c31331636387c Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 12:53:20 -0800 Subject: [PATCH 19/34] Separate the following ordinary gesture control from sampler setup --- .../tests/image_trace_ignore_sampler.rs | 57 ++++++++++--------- 1 file changed, 31 insertions(+), 26 deletions(-) diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs index 6a05c7f086..0e7d5a1ba1 100644 --- a/crates/ui-egui/tests/image_trace_ignore_sampler.rs +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -413,24 +413,37 @@ fn a_consumed_stale_sampler_press_does_not_complete_a_double_click() { check_sampler_double_click(true); } -fn check_sampler_double_click(sampler: bool) { - fn frame_at(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec) { - let mut raw = RawInput { - time: Some(time), - events, - focused: true, - screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1400.0))), - ..Default::default() - }; - app.raw_input_hook(ctx, &mut raw); - let mut out = ctx.run_ui(raw, |ui| { - app.tick(ui.ctx()); - app.ui(ui); - }); - out.textures_delta.clear(); - assert_eq!(ctx.time(), time, "the real UI frame uses the supplied gesture time"); - } +fn frame_at(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec) { + let mut raw = RawInput { + time: Some(time), + events, + focused: true, + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1400.0))), + ..Default::default() + }; + app.raw_input_hook(ctx, &mut raw); + let mut out = ctx.run_ui(raw, |ui| { + app.tick(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + assert_eq!(ctx.time(), time, "the real UI frame uses the supplied gesture time"); +} +fn check_next_ordinary_double_click(app: &mut VectorcraftApp, ctx: &egui::Context, at: Pos2, group: NodeId, next: f64, step: f64) { + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame_at(app, ctx, next, vec![Event::PointerMoved(at), press(true)]); + frame_at(app, ctx, next + step, vec![press(false)]); + assert!(!ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the next ordinary first click selects the group"); + assert_eq!(app.session.active().unwrap().isolation, None); + frame_at(app, ctx, next + 3.0 * step, vec![press(true)]); + frame_at(app, ctx, next + 4.0 * step, vec![press(false)]); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "the next ordinary double-click still isolates the group"); +} + +fn check_sampler_double_click(sampler: bool) { let (mut app, ctx) = fixture(true, [37, 83, 149], false); let source = selected(&app).id; app.session.prefs.double_click_to_isolate = true; @@ -487,15 +500,7 @@ fn check_sampler_double_click(sampler: bool) { assert_eq!(app.session.tool_id(), "selection"); // The consumed release must not take the next independent ordinary gesture with it. let next = start + 4.0 * step + delay + 1.0; - frame_at(&mut app, &ctx, next, vec![Event::PointerMoved(at), press(true)]); - frame_at(&mut app, &ctx, next + step, vec![press(false)]); - assert!(!ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); - assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the next ordinary first click selects the group"); - assert_eq!(app.session.active().unwrap().isolation, None); - frame_at(&mut app, &ctx, next + 3.0 * step, vec![press(true)]); - frame_at(&mut app, &ctx, next + 4.0 * step, vec![press(false)]); - assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); - assert_eq!(app.session.active().unwrap().isolation, Some(group), "the next ordinary double-click still isolates the group"); + check_next_ordinary_double_click(&mut app, &ctx, at, group, next, step); } else { assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the ordinary first click really selects the group"); frame_at(&mut app, &ctx, start + 3.0 * step, vec![press(true)]); From a07eac2e9f8b26e262ac8f7d614ae528bdd9d289 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 14:25:05 -0800 Subject: [PATCH 20/34] #8068: test held sampler ownership, fresh clicks and preset cancellation --- .../tests/image_trace_ignore_sampler.rs | 334 ++++++++++++++++++ 1 file changed, 334 insertions(+) diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs index 0e7d5a1ba1..6d26b0816a 100644 --- a/crates/ui-egui/tests/image_trace_ignore_sampler.rs +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -690,3 +690,337 @@ fn cancelling_a_borrowed_sampler_clears_the_restored_eyedropper() { assert_eq!(ordinary_sample(&mut app, &ctx, point), expected_sample_effects, "the next real click follows the ordinary eyedropper path"); } } + +fn review_gesture_group_fixture() -> (VectorcraftApp, egui::Context, Point, NodeId) { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let source = selected(&app).id; + app.session.prefs.double_click_to_isolate = true; + let first = app.run("shape.rectangle", json!({"x": 100, "y": 140, "width": 20, "height": 20})).unwrap()["id"].clone(); + let second = app.run("shape.rectangle", json!({"x": 120, "y": 140, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [first.clone(), second.clone()], "color": "#cc3322"})).unwrap(); + app.run("select.set", json!({"ids": [first, second]})).unwrap(); + let group = NodeId(app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [source.0]})).unwrap(); + settle(&mut app, &ctx); + let point = Point::new(110.0, 150.0); + assert!(point.x < source_point(&app, 0.0).x - 40.0, "the gesture group is outside the sampled image"); + (app, ctx, point, group) +} + +fn review_gesture_screen(app: &VectorcraftApp, ctx: &egui::Context, point: Point) -> Pos2 { + let rect = app.canvas_rect.unwrap(); + let at = canvas::Xf::at(rect, app.view().unwrap(), ctx.zoom_factor()).to_screen(point); + assert!(rect.contains(at), "the real canvas contains the gesture point"); + at +} + +fn review_gesture_times(ctx: &egui::Context) -> (f64, f64) { + let (delay, hold) = ctx.options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_duration)); + assert!(delay.is_finite() && delay > 0.0 && hold.is_finite() && hold > 0.0); + (ctx.time() + delay + 1.0, delay.min(hold) / 8.0) +} + +fn review_gesture_press(app: &mut VectorcraftApp, ctx: &egui::Context, at: Pos2, time: f64) { + let event = Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Default::default() }; + frame_at(app, ctx, time, vec![Event::PointerMoved(at), event]); +} + +fn review_gesture_release(app: &mut VectorcraftApp, ctx: &egui::Context, at: Pos2, time: f64) { + let event = Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame_at(app, ctx, time, vec![event]); +} + +fn review_gesture_state(app: &VectorcraftApp) -> impl PartialEq + std::fmt::Debug + use<> { + let state = app.session.active().unwrap(); + ( + state.doc.clone(), + state.selection.clone(), + state.revision, + (state.history.undo.len(), state.history.redo.len()), + app.session.paint.clone(), + state.isolation, + ) +} + +fn review_gesture_observation(app: &VectorcraftApp, ctx: &egui::Context) -> (bool, bool, Vec, Option) { + let state = app.session.active().unwrap(); + ( + ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)), + ctx.input(|i| i.pointer.button_triple_clicked(PointerButton::Primary)), + state.selection.objects.clone(), + state.isolation, + ) +} + +fn review_gesture_ordinary_pair(app: &mut VectorcraftApp, ctx: &egui::Context, first: Pos2, second: Pos2, group: NodeId) { + let (start, step) = review_gesture_times(ctx); + review_gesture_press(app, ctx, first, start); + review_gesture_release(app, ctx, first, start + step); + assert!(!ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the ordinary first click selects the group"); + assert_eq!(app.session.active().unwrap().isolation, None); + review_gesture_press(app, ctx, second, start + 3.0 * step); + frame_at(app, ctx, start + 3.5 * step, vec![]); + review_gesture_release(app, ctx, second, start + 4.0 * step); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "the ordinary held double-click isolates the group"); +} + +#[test] +fn review_followup_sampler_cancelled_mid_hold_keeps_release_owned() { + let (mut control, control_ctx, control_point, control_group) = review_gesture_group_fixture(); + let control_at = review_gesture_screen(&control, &control_ctx, control_point); + review_gesture_ordinary_pair(&mut control, &control_ctx, control_at, control_at, control_group); + + let (mut app, ctx, point, _) = review_gesture_group_fixture(); + let source = selected(&app).id; + click_control(&mut app, &ctx, SAMPLE_TIP); + let at = review_gesture_screen(&app, &ctx, point); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + review_gesture_release(&mut app, &ctx, at, start + step); + assert_eq!(app.session.tool_id(), "eyedropper"); + assert!(app.ui.trace_ignore_sampler.is_some(), "the first canvas click is a sampler miss"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![source]); + assert_eq!(app.session.active().unwrap().isolation, None); + review_gesture_press(&mut app, &ctx, at, start + 3.0 * step); + assert!(app.ui.trace_ignore_sampler.is_some(), "the second Down still belongs to the valid sampler"); + app.run("select.none", json!({})).unwrap(); + let expected = review_gesture_state(&app); + frame_at(&mut app, &ctx, start + 3.5 * step, vec![]); + assert!(ctx.input(|i| i.pointer.primary_down())); + assert!(!ctx.input(|i| i.pointer.primary_pressed())); + assert_eq!(app.session.tool_id(), "selection"); + assert!(app.ui.trace_ignore_sampler.is_none(), "the held frame cancelled the invalid binding"); + review_gesture_release(&mut app, &ctx, at, start + 4.0 * step); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(review_gesture_state(&app), expected, "a mid-hold cancellation must retain ownership through release"); + assert_eq!(app.session.tool_id(), "selection"); +} + +#[test] +fn review_followup_consumed_prefix_keeps_two_fresh_clicks_single_then_double() { + let (mut control, control_ctx, control_point, control_group) = review_gesture_group_fixture(); + let control_at = review_gesture_screen(&control, &control_ctx, control_point); + review_gesture_ordinary_pair(&mut control, &control_ctx, control_at, control_at, control_group); + + let (mut app, ctx, point, group) = review_gesture_group_fixture(); + click_control(&mut app, &ctx, SAMPLE_TIP); + app.run("select.none", json!({})).unwrap(); + let at = review_gesture_screen(&app, &ctx, point); + let expected = review_gesture_state(&app); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + review_gesture_release(&mut app, &ctx, at, start + step); + assert!(!ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(review_gesture_state(&app), expected, "the single stale prefix itself is consumed"); + assert_eq!(app.session.tool_id(), "selection"); + + review_gesture_press(&mut app, &ctx, at, start + 3.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 4.0 * step); + let first = review_gesture_observation(&app, &ctx); + // Always run the second fresh click, even when the first app-level oracle was wrong. + review_gesture_press(&mut app, &ctx, at, start + 6.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 7.0 * step); + let second = review_gesture_observation(&app, &ctx); + assert!(first.0 && !first.1 && !second.0 && second.1, "expected raw Double then Triple: first={first:?}, second={second:?}"); + assert!( + first.2 == vec![group] && first.3.is_none() && second.3 == Some(group), + "fresh clicks must select without isolation, then isolate: first={first:?}, second={second:?}" + ); +} + +fn review_gesture_enclose_source(app: &mut VectorcraftApp, source: NodeId) -> NodeId { + let background = app.run("shape.rectangle", json!({"x": 50, "y": 30, "width": 300, "height": 240})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [background.clone()], "color": "#e020c0"})).unwrap(); + app.run("select.set", json!({"ids": [source.0, background]})).unwrap(); + let group = NodeId(app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [source.0]})).unwrap(); + group +} + +fn review_gesture_original_pixels(app: &VectorcraftApp) { + let trace = selected(app); + let original = trace.children().unwrap()[0].as_ref(); + let NodeKind::Image(image) = &original.kind else { panic!("the fixture retains its original image") }; + let state = app.session.active().unwrap(); + let blob = &state.doc.images[&image.key]; + assert!(blob.sample_object(19.5, 10.0, (image.width, image.height), 1).is_none(), "the first point is really transparent"); + assert_eq!(blob.sample_object(5.0, 10.0, (image.width, image.height), 1), Some([37, 83, 149, 255]), "the second point has a distinct nonwhite source color"); +} + +fn review_gesture_close_pair(app: &VectorcraftApp, ctx: &egui::Context, miss: Point, hit: Point) -> (Pos2, Pos2) { + let miss = review_gesture_screen(app, ctx, miss); + let hit = review_gesture_screen(app, ctx, hit); + let distance = ctx.options(|o| o.input_options.max_click_dist); + assert!(distance.is_finite() && distance > 0.0); + assert!(miss.distance_sq(hit) < distance * distance, "the actual transformed miss/hit pair satisfies egui's click distance"); + (miss, hit) +} + +fn review_gesture_completion_fixture() -> (VectorcraftApp, egui::Context, Point, Point, NodeId) { + let (mut app, ctx) = fixture_with_transparent_edge(true, [37, 83, 149], false, true); + let source = selected(&app).id; + review_gesture_original_pixels(&app); + app.session.prefs.double_click_to_isolate = true; + let group = review_gesture_enclose_source(&mut app, source); + // view.setZoom takes display percent; use its public 10% setting, then assert actual geometry. + app.run("view.setZoom", json!({"zoom": 10.0, "center": [200, 150]})).unwrap(); + settle(&mut app, &ctx); + let miss = source_point(&app, 0.975); + let hit = source_point(&app, 0.25); + (app, ctx, miss, hit, group) +} + +#[test] +fn review_followup_valid_sampler_down_completes_without_lending_its_release() { + let (mut control, control_ctx, control_miss, control_hit, control_group) = review_gesture_completion_fixture(); + control.run("select.none", json!({})).unwrap(); + settle(&mut control, &control_ctx); + let (control_miss, control_hit) = review_gesture_close_pair(&control, &control_ctx, control_miss, control_hit); + review_gesture_ordinary_pair(&mut control, &control_ctx, control_miss, control_hit, control_group); + + let (mut app, ctx, miss, hit, _) = review_gesture_completion_fixture(); + click_control(&mut app, &ctx, SAMPLE_TIP); + let (miss, hit) = review_gesture_close_pair(&app, &ctx, miss, hit); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, miss, start); + review_gesture_release(&mut app, &ctx, miss, start + step); + assert_eq!(app.session.tool_id(), "eyedropper"); + assert!(app.ui.trace_ignore_sampler.is_some(), "the transparent first click keeps the sampler armed"); + let expected = review_gesture_state(&app); + review_gesture_press(&mut app, &ctx, hit, start + 3.0 * step); + assert_eq!(app.session.tool_id(), "selection", "the opaque Down completes sampling and restores the tool"); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert_eq!(review_gesture_state(&app), expected, "Preview off sampling changes only the panel draft"); + review_gesture_release(&mut app, &ctx, hit, start + 4.0 * step); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(review_gesture_state(&app), expected, "a completed sampler still owns its matching release"); + assert_eq!(app.session.tool_id(), "selection"); + // A fix that merely cancels the valid Down must not pass without accepting its actual color. + click_control(&mut app, &ctx, "Trace"); + assert_eq!(settings(&app)["params"]["ignoreColor"], "#255395", "Trace persists the real opaque source sample"); + assert_eq!(settings(&app)["params"]["ignoreWhite"], true); +} + +fn review_preset_checkbox(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) -> bool { + for _ in 0..3 { + let mut output = frame(app, ctx, vec![]); + let checked = output.platform_output.accesskit_update.as_ref().and_then(|update| { + update.nodes.iter().find(|(_, node)| node.label() == Some(label) && node.role() == egui::accesskit::Role::CheckBox).and_then(|(_, node)| { + match node.toggled() { + Some(egui::accesskit::Toggled::True) => Some(true), + Some(egui::accesskit::Toggled::False) => Some(false), + _ => None, + } + }) + }); + output.textures_delta.clear(); + if let Some(checked) = checked { + return checked; + } + } + panic!("fixture: missing accessible Image Trace checkbox state: {label}"); +} + +fn review_preset_assert_shown(app: &mut VectorcraftApp, ctx: &egui::Context, preset: &str) { + fn contains(shape: &egui::Shape, text: &str) -> bool { + match shape { + egui::Shape::Text(drawn) => drawn.galley.text() == text, + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| contains(shape, text)), + _ => false, + } + } + let mut output = frame(app, ctx, vec![]); + let shown = output.shapes.iter().any(|clipped| contains(&clipped.shape, preset)); + output.textures_delta.clear(); + assert!(shown, "fixture: the real Preset control must show {preset}"); +} + +fn review_preset_click_opaque_source(app: &mut VectorcraftApp, ctx: &egui::Context) { + let point = source_point(app, 0.25); + let source = selected(app); + let original = source.children().and_then(|children| children.first()).unwrap(); + let NodeKind::Image(image) = &original.kind else { panic!("fixture: the live trace retains its original image") }; + assert_eq!( + app.session.active().unwrap().doc.images[&image.key].sample_object( + f64::from(image.width) * 0.25, + f64::from(image.height) * 0.5, + (image.width, image.height), + 1, + ), + Some([37, 83, 149, 255]), + "fixture: the actual canvas point is an opaque original pixel" + ); + let at = canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), ctx.zoom_factor()).to_screen(point); + assert!(app.canvas_rect.unwrap().contains(at), "fixture: the source point lies on the actual canvas"); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![Event::PointerMoved(at), press(true)]).textures_delta.clear(); + frame(app, ctx, vec![press(false)]).textures_delta.clear(); + settle(app, ctx); +} + +fn review_preset_enhanced_on_control() { + // Legitimate control first: the real Enhanced pair retains Ignore Color and a valid pick. + let (mut control, control_ctx) = fixture(true, [37, 83, 149], false); + click_control(&mut control, &control_ctx, "Black and White"); + review_preset_assert_shown(&mut control, &control_ctx, "Black and White Logo"); + assert!(review_preset_checkbox(&mut control, &control_ctx, "Ignore Color")); + let enhanced = review_preset_checkbox(&mut control, &control_ctx, "Enhanced"); + click_control(&mut control, &control_ctx, SAMPLE_TIP); + assert_eq!(control.session.tool_id(), "eyedropper"); + assert!(control.ui.trace_ignore_sampler.is_some()); + click_control(&mut control, &control_ctx, "Enhanced"); + assert_ne!(review_preset_checkbox(&mut control, &control_ctx, "Enhanced"), enhanced, "fixture: the real Enhanced checkbox changed"); + assert!(review_preset_checkbox(&mut control, &control_ctx, "Ignore Color"), "Enhanced keeps this preset's Ignore Color on"); + assert!(control.ui.trace_ignore_sampler.is_some(), "an on-to-on settings change keeps the pick armed"); + assert_eq!(control.session.tool_id(), "eyedropper"); + assert!(!control.session.tool_options()["imageTraceIgnoreColor"].is_null()); + review_preset_click_opaque_source(&mut control, &control_ctx); + assert!(control.ui.trace_ignore_sampler.is_none(), "the opaque pick completes normally"); + assert_eq!(control.session.tool_id(), "selection"); + click_control(&mut control, &control_ctx, "Trace"); + assert_eq!(settings(&control)["params"]["ignoreWhite"], true); + assert_eq!(settings(&control)["params"]["ignoreColor"], "#255395", "the on-to-on control really accepted the source color"); + +} + +#[test] +fn review_followup_preset_off_cancels_sampler_but_enhanced_on_keeps_it() { + review_preset_enhanced_on_control(); + + // Separate causal fixture: Preview off leaves the target/revision valid when a preset turns Ignore Color off. + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let presets = app.run("imageTrace.presets", json!({})).unwrap(); + let expected = presets["presets"].as_array().unwrap().iter().find(|preset| preset["name"] == "High Fidelity Photo").unwrap()["params"].clone(); + assert_eq!(expected["ignoreWhite"], false, "fixture: High Color's public preset disables Ignore Color"); + assert_ne!(expected["ignoreColor"], "#255395"); + click_control(&mut app, &ctx, "Black and White"); + assert!(review_preset_checkbox(&mut app, &ctx, "Ignore Color")); + click_control(&mut app, &ctx, SAMPLE_TIP); + assert!(app.ui.trace_ignore_sampler.is_some()); + assert_eq!(app.session.tool_id(), "eyedropper"); + let state = app.session.active().unwrap(); + let (document, revision) = (state.doc.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + click_control(&mut app, &ctx, "High Color"); + review_preset_assert_shown(&mut app, &ctx, "High Fidelity Photo"); + assert!(!review_preset_checkbox(&mut app, &ctx, "Ignore Color"), "the actual preset button made Ignore Color off"); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document, "Preview off changes the panel draft, not the document"); + assert_eq!(state.revision, revision, "the sampler target binding was not invalidated by a trace"); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert!(app.ui.trace_ignore_sampler.is_none(), "choosing an Ignore Color-off preset must cancel the armed sampler"); + assert_eq!(app.session.tool_id(), "selection", "cancelling the panel pick restores the previous tool"); + assert!(app.session.tool_options_of("eyedropper")["imageTraceIgnoreColor"].is_null()); + review_preset_click_opaque_source(&mut app, &ctx); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert_eq!(app.session.tool_id(), "selection"); + assert_eq!(app.session.paint, paint); + review_preset_assert_shown(&mut app, &ctx, "High Fidelity Photo"); + assert!(!review_preset_checkbox(&mut app, &ctx, "Ignore Color")); + click_control(&mut app, &ctx, "Trace"); + assert_eq!(settings(&app)["preset"], "High Fidelity Photo", "the following opaque canvas click cannot turn the off preset into Custom"); + assert_eq!(settings(&app)["params"], expected, "the hidden pick cannot replace the off preset's ignored color"); +} From b956474dbf255bfa294dcb538b49a14a3afad369 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 14:38:10 -0800 Subject: [PATCH 21/34] Format sampler review follow-up witnesses --- .../ui-egui/tests/image_trace_ignore_sampler.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs index 6d26b0816a..7d7f63f8ac 100644 --- a/crates/ui-egui/tests/image_trace_ignore_sampler.rs +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -846,7 +846,11 @@ fn review_gesture_original_pixels(app: &VectorcraftApp) { let state = app.session.active().unwrap(); let blob = &state.doc.images[&image.key]; assert!(blob.sample_object(19.5, 10.0, (image.width, image.height), 1).is_none(), "the first point is really transparent"); - assert_eq!(blob.sample_object(5.0, 10.0, (image.width, image.height), 1), Some([37, 83, 149, 255]), "the second point has a distinct nonwhite source color"); + assert_eq!( + blob.sample_object(5.0, 10.0, (image.width, image.height), 1), + Some([37, 83, 149, 255]), + "the second point has a distinct nonwhite source color" + ); } fn review_gesture_close_pair(app: &VectorcraftApp, ctx: &egui::Context, miss: Point, hit: Point) -> (Pos2, Pos2) { @@ -907,13 +911,13 @@ fn review_preset_checkbox(app: &mut VectorcraftApp, ctx: &egui::Context, label: for _ in 0..3 { let mut output = frame(app, ctx, vec![]); let checked = output.platform_output.accesskit_update.as_ref().and_then(|update| { - update.nodes.iter().find(|(_, node)| node.label() == Some(label) && node.role() == egui::accesskit::Role::CheckBox).and_then(|(_, node)| { - match node.toggled() { + update.nodes.iter().find(|(_, node)| node.label() == Some(label) && node.role() == egui::accesskit::Role::CheckBox).and_then( + |(_, node)| match node.toggled() { Some(egui::accesskit::Toggled::True) => Some(true), Some(egui::accesskit::Toggled::False) => Some(false), _ => None, - } - }) + }, + ) }); output.textures_delta.clear(); if let Some(checked) = checked { @@ -982,7 +986,6 @@ fn review_preset_enhanced_on_control() { click_control(&mut control, &control_ctx, "Trace"); assert_eq!(settings(&control)["params"]["ignoreWhite"], true); assert_eq!(settings(&control)["params"]["ignoreColor"], "#255395", "the on-to-on control really accepted the source color"); - } #[test] From fdbab6e06d76f5da6567eec4e8e8239f8932734f Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 14:54:41 -0800 Subject: [PATCH 22/34] #8068: retain sampler gesture ownership and exclude consumed clicks --- crates/ui-egui/src/canvas.rs | 132 ++++++++++++++++++++--- crates/ui-egui/src/canvas/input.rs | 16 ++- crates/ui-egui/src/panels/image_trace.rs | 4 + 3 files changed, 131 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 7392ad73b8..77487cc9ab 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -263,7 +263,15 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if app.ui.home.is_some_and(|k| k != crate::menus::home_key(app)) { app.ui.home = None; } - if crate::menus::home_showing(app) { + let home_showing = crate::menus::home_showing(app); + if home_showing || app.session.active().is_none() { + // Home and the empty window still advance egui's click history. Observe the same + // correction there so it retires after the two ordinary clicks that replace a pick. + let id = egui::Id::unique("canvas"); + begin_ignore_sampler_pointer(ui, id, false); + end_ignore_sampler_pointer(ui, id); + } + if home_showing { // No IME owner this pass (`ime_caret_rect` stays None): the end-of-pass observation marks // the context absent and keeps any marked text as typed. home(app, ui, full); @@ -466,25 +474,115 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } -/// A press arriving with an invalidated sampler and its release belong to that cancelled pick. -fn input_after_sampler_refresh(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect, cancelled: bool) { - let (pressed, released, down, any_pressed) = - ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_released(), i.pointer.primary_down(), i.pointer.any_pressed())); - let consumed_primary = ui.data_mut(|data| { - let id = resp.id.with("image-trace-consumed-primary"); - // A fresh press replaces any ownership whose release this canvas did not observe. - let consumed = if pressed { cancelled } else { data.get_temp::(id).unwrap_or(false) }; - if consumed && down { - data.insert_temp(id, true); - } else { - data.remove::(id); - } - // egui classifies double/triple clicks on release, independently of the tool's Down. - consumed && (pressed || released || down) +/// Two non-sampler clicks replace egui's last two click times after a consumed pick. +#[derive(Clone, Copy)] +struct IgnoreSamplerClicks { + last: Option<(f64, Pos2)>, + remaining: u8, +} + +fn ignore_sampler_primary_id(id: egui::Id) -> egui::Id { + id.with("image-trace-consumed-primary") +} + +fn ignore_sampler_owns_primary(ui: &Ui, id: egui::Id) -> bool { + ui.data(|data| data.get_temp::(ignore_sampler_primary_id(id)).unwrap_or(false)) +} + +fn reset_ignore_sampler_clicks(ui: &Ui, id: egui::Id) { + ui.data_mut(|data| data.insert_temp(id.with("image-trace-clicks"), IgnoreSamplerClicks { last: None, remaining: 2 })); +} + +/// Reclassify only the two clicks whose raw history can still contain a consumed pick. +/// Other widgets' clicks count too, as they do in egui; its pointer state stays untouched. +fn ignore_sampler_clicks(ui: &Ui, id: egui::Id, consumed: bool) { + let (delay, distance) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist)); + let (clicked, primary, at, time) = ui.input(|i| { + ( + i.pointer.any_click(), + i.pointer.button_clicked(egui::PointerButton::Primary), + i.pointer.interact_pos(), + i.time, + ) }); - if !consumed_primary && (!cancelled || !any_pressed) { + ui.data_mut(|data| data.remove::(id.with("image-trace-click-count"))); + if !clicked { + return; + } + if consumed { + reset_ignore_sampler_clicks(ui, id); + return; + } + let Some(at) = at else { return }; + ui.data_mut(|data| { + let history_id = id.with("image-trace-clicks"); + let Some(mut clicks) = data.remove_temp::(history_id) else { return }; + let double = clicks.last.is_some_and(|(last, pos)| time - last < delay && pos.distance_sq(at) < distance * distance); + if primary { + data.insert_temp(id.with("image-trace-click-count"), if double { 2u8 } else { 1u8 }); + } + clicks.last = Some((time, at)); + clicks.remaining -= 1; + if clicks.remaining != 0 { + data.insert_temp(history_id, clicks); + } + }); +} + +fn primary_click_count(ui: &Ui, resp: &egui::Response) -> u8 { + if !resp.clicked_by(egui::PointerButton::Primary) { + return 0; + } + ui.data(|data| data.get_temp::(resp.id.with("image-trace-click-count"))) + .unwrap_or_else(|| if resp.triple_clicked() { 3 } else if resp.double_clicked() { 2 } else { 1 }) +} + +/// Remove only the pointer sequence acquired by this sampler, never a view or tool drag. +fn clear_ignore_sampler_gesture(ui: &Ui, id: egui::Id) { + ui.data_mut(|data| { + data.remove::(ignore_sampler_primary_id(id)); + if matches!(data.get_temp::(drag::drag_id()), Some(Drag::Gesture)) { + data.remove::(drag::drag_id()); + data.remove::(drag::drag_pos_id()); + data.remove::(drag::tool_drag_doc_id()); + data.remove::(drag::tool_press_doc_id()); + } + }); +} + +fn begin_ignore_sampler_pointer(ui: &Ui, id: egui::Id, cancelled: bool) -> bool { + let (pressed, released, down) = ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_released(), i.pointer.primary_down())); + if pressed { + // A fresh press replaces the complete sampler gesture if its release was not observed. + if ignore_sampler_owns_primary(ui, id) { + clear_ignore_sampler_gesture(ui, id); + } + if cancelled { + ui.data_mut(|data| data.insert_temp(ignore_sampler_primary_id(id), true)); + } + } + let consumed = ignore_sampler_owns_primary(ui, id) && (pressed || released || down); + ignore_sampler_clicks(ui, id, consumed); + consumed +} + +fn end_ignore_sampler_pointer(ui: &Ui, id: egui::Id) { + // A valid Down can acquire ownership and complete in the same frame. + if ignore_sampler_owns_primary(ui, id) && !ui.input(|i| i.pointer.primary_down()) { + if ui.input(|i| i.pointer.button_clicked(egui::PointerButton::Primary)) { + reset_ignore_sampler_clicks(ui, id); + } + clear_ignore_sampler_gesture(ui, id); + } +} + +/// A sampler press keeps its release, even if its Down completes or its binding expires held. +fn input_after_sampler_refresh(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect, cancelled: bool) { + let consumed = begin_ignore_sampler_pointer(ui, resp.id, cancelled); + if !consumed && (!cancelled || !ui.input(|i| i.pointer.any_pressed())) { canvas_input(app, ui, resp, rect); } + end_ignore_sampler_pointer(ui, resp.id); } /// The pointer on the canvas: the tool's input, unless the context menu or the 3D gizmo has the press. diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 9467596cf7..3aa3b48613 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -186,13 +186,15 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo .unwrap_or(m.shift); select_named_artboard(app, i, shift || release_shift); } - if resp.double_clicked() + if !super::ignore_sampler_owns_primary(ui, resp.id) + && super::primary_click_count(ui, resp) == 2 && !f.modal && let Some(p) = at { double_click(app, ui, &f, p); } - if resp.triple_clicked() + if !super::ignore_sampler_owns_primary(ui, resp.id) + && super::primary_click_count(ui, resp) == 3 && !f.modal && let Some(p) = at { @@ -343,9 +345,15 @@ fn begin_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { pressure: pen_pressure(ui, app, true), pen: pen_pose(app, &xf), }; + // Only a Down actually sent to this sampler owns the gesture. Cmd/Ctrl's borrowed + // selection press keeps the ordinary tool path. + let sampler = app.ui.trace_ignore_sampler.is_some() && tool == "eyedropper" && app.session.lent_tool_id(&ev.mods).is_none(); + if sampler { + ui.data_mut(|data| data.insert_temp(super::ignore_sampler_primary_id(resp.id), true)); + } dispatch(app, &ev, view); crate::document_drag::begin(app, ui.ctx(), ev.pos); - Drag::Tool + if sampler { Drag::Gesture } else { Drag::Tool } }; // A drag of the Zoom, Hand or Rotate View tool uses the tool of a held shortcut; held Space's // view tools are not that tool. @@ -527,7 +535,7 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po // The second click of a double-click: don't fit another artboard on this release. // A double-click on an object does not open Artboard Options. Empty artboard // space still does. - if resp.double_clicked() && app.session.tool_id() == "artboard" { + if super::primary_click_count(ui, resp) == 2 && app.session.tool_id() == "artboard" { app.session.set_tool_option("suppressFitClick", &json!(true)); } // A move that came in the release's own frame shapes the preview first: the diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index 1d646a8c87..04000ee0d4 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -1070,6 +1070,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if is_trace || !preview { st.preview_off = !preview; } + // Presets and restored panel settings can turn Ignore Color off without its checkbox. + if st.params["ignoreWhite"] != true { + cancel_ignore_sampler(app, true); + } if retrace && is_trace && preview { trace(app, ui.ctx(), &mut st); } From 6b594abbd9ba7cb86639dcdfa7e2d9e95b193a0d Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 14:56:59 -0800 Subject: [PATCH 23/34] Format sampler click classification --- crates/ui-egui/src/canvas.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 77487cc9ab..8ae8a897c6 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -497,14 +497,8 @@ fn reset_ignore_sampler_clicks(ui: &Ui, id: egui::Id) { /// Other widgets' clicks count too, as they do in egui; its pointer state stays untouched. fn ignore_sampler_clicks(ui: &Ui, id: egui::Id, consumed: bool) { let (delay, distance) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist)); - let (clicked, primary, at, time) = ui.input(|i| { - ( - i.pointer.any_click(), - i.pointer.button_clicked(egui::PointerButton::Primary), - i.pointer.interact_pos(), - i.time, - ) - }); + let (clicked, primary, at, time) = + ui.input(|i| (i.pointer.any_click(), i.pointer.button_clicked(egui::PointerButton::Primary), i.pointer.interact_pos(), i.time)); ui.data_mut(|data| data.remove::(id.with("image-trace-click-count"))); if !clicked { return; @@ -533,8 +527,15 @@ fn primary_click_count(ui: &Ui, resp: &egui::Response) -> u8 { if !resp.clicked_by(egui::PointerButton::Primary) { return 0; } - ui.data(|data| data.get_temp::(resp.id.with("image-trace-click-count"))) - .unwrap_or_else(|| if resp.triple_clicked() { 3 } else if resp.double_clicked() { 2 } else { 1 }) + ui.data(|data| data.get_temp::(resp.id.with("image-trace-click-count"))).unwrap_or_else(|| { + if resp.triple_clicked() { + 3 + } else if resp.double_clicked() { + 2 + } else { + 1 + } + }) } /// Remove only the pointer sequence acquired by this sampler, never a view or tool drag. From 0343bbf2a404a842617c22ada000d0922c124d53 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 15:00:11 -0800 Subject: [PATCH 24/34] Satisfy egui temporary click-state removal bound --- crates/ui-egui/src/canvas.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8ae8a897c6..11f681cb39 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -475,7 +475,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } /// Two non-sampler clicks replace egui's last two click times after a consumed pick. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Default)] struct IgnoreSamplerClicks { last: Option<(f64, Pos2)>, remaining: u8, From 20791a7314ff6b82d9a3337923dd3cf2e46199be Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 15:03:14 -0800 Subject: [PATCH 25/34] Keep sampler lifecycle conditions in focused helpers --- crates/ui-egui/src/canvas.rs | 18 +++++++++++------- crates/ui-egui/src/panels/image_trace.rs | 12 ++++++++---- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 11f681cb39..3aa4c262fc 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -264,13 +264,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { app.ui.home = None; } let home_showing = crate::menus::home_showing(app); - if home_showing || app.session.active().is_none() { - // Home and the empty window still advance egui's click history. Observe the same - // correction there so it retires after the two ordinary clicks that replace a pick. - let id = egui::Id::unique("canvas"); - begin_ignore_sampler_pointer(ui, id, false); - end_ignore_sampler_pointer(ui, id); - } + observe_hidden_ignore_sampler_pointer(app, ui, home_showing); if home_showing { // No IME owner this pass (`ime_caret_rect` stays None): the end-of-pass observation marks // the context absent and keeps any marked text as typed. @@ -577,6 +571,16 @@ fn end_ignore_sampler_pointer(ui: &Ui, id: egui::Id) { } } +fn observe_hidden_ignore_sampler_pointer(app: &VectorcraftApp, ui: &Ui, home_showing: bool) { + if home_showing || app.session.active().is_none() { + // Home and the empty window still advance egui's click history. Observe the same + // correction there so it retires after the two ordinary clicks that replace a pick. + let id = egui::Id::unique("canvas"); + begin_ignore_sampler_pointer(ui, id, false); + end_ignore_sampler_pointer(ui, id); + } +} + /// A sampler press keeps its release, even if its Down completes or its binding expires held. fn input_after_sampler_refresh(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect, cancelled: bool) { let consumed = begin_ignore_sampler_pointer(ui, resp.id, cancelled); diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index 04000ee0d4..0303467c3c 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -316,6 +316,13 @@ pub(crate) fn cancel_ignore_sampler(app: &mut VectorcraftApp, restore: bool) { } } +/// Presets and restored panel settings can turn Ignore Color off without its checkbox. +fn cancel_disabled_ignore_sampler(app: &mut VectorcraftApp, params: &Value) { + if params["ignoreWhite"] != true { + cancel_ignore_sampler(app, true); + } +} + /// Also runs when the panel is closed: document changes and tool changes end the pick. pub(crate) fn refresh_ignore_sampler(app: &mut VectorcraftApp) -> bool { let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return false }; @@ -1070,10 +1077,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if is_trace || !preview { st.preview_off = !preview; } - // Presets and restored panel settings can turn Ignore Color off without its checkbox. - if st.params["ignoreWhite"] != true { - cancel_ignore_sampler(app, true); - } + cancel_disabled_ignore_sampler(app, &st.params); if retrace && is_trace && preview { trace(app, ui.ctx(), &mut st); } From 3a8fa06f9ea83a456c1fa40e3f4618e17d62e337 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 15:06:44 -0800 Subject: [PATCH 26/34] Keep click release positions separate from later hover moves --- crates/ui-egui/src/canvas.rs | 10 ++++-- .../tests/image_trace_ignore_sampler.rs | 31 +++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 3aa4c262fc..d1406d77d6 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -491,8 +491,14 @@ fn reset_ignore_sampler_clicks(ui: &Ui, id: egui::Id) { /// Other widgets' clicks count too, as they do in egui; its pointer state stays untouched. fn ignore_sampler_clicks(ui: &Ui, id: egui::Id, consumed: bool) { let (delay, distance) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist)); - let (clicked, primary, at, time) = - ui.input(|i| (i.pointer.any_click(), i.pointer.button_clicked(egui::PointerButton::Primary), i.pointer.interact_pos(), i.time)); + let (clicked, primary, at, time) = ui.input(|i| { + // A hover move after the release is not the position egui put in its click history. + let at = i.events.iter().rev().find_map(|event| match event { + egui::Event::PointerButton { pos, button, pressed: false, .. } if i.pointer.button_clicked(*button) => Some(*pos), + _ => None, + }); + (i.pointer.any_click(), i.pointer.button_clicked(egui::PointerButton::Primary), at, i.time) + }); ui.data_mut(|data| data.remove::(id.with("image-trace-click-count"))); if !clicked { return; diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs index 7d7f63f8ac..167f275a96 100644 --- a/crates/ui-egui/tests/image_trace_ignore_sampler.rs +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -1027,3 +1027,34 @@ fn review_followup_preset_off_cancels_sampler_but_enhanced_on_keeps_it() { assert_eq!(settings(&app)["preset"], "High Fidelity Photo", "the following opaque canvas click cannot turn the off preset into Custom"); assert_eq!(settings(&app)["params"], expected, "the hidden pick cannot replace the off preset's ignored color"); } + +#[test] +fn review_followup_release_position_survives_a_later_hover_move() { + let (mut app, ctx, point, group) = review_gesture_group_fixture(); + click_control(&mut app, &ctx, SAMPLE_TIP); + app.run("select.none", json!({})).unwrap(); + let at = review_gesture_screen(&app, &ctx, point); + let hover = at + vec2(80.0, 0.0); + assert!(app.canvas_rect.unwrap().contains(hover)); + assert!(at.distance(hover) > ctx.options(|o| o.input_options.max_click_dist)); + let expected = review_gesture_state(&app); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + review_gesture_release(&mut app, &ctx, at, start + step); + assert_eq!(review_gesture_state(&app), expected, "the stale prefix is consumed"); + review_gesture_press(&mut app, &ctx, at, start + 3.0 * step); + frame_at( + &mut app, + &ctx, + start + 4.0 * step, + vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Default::default() }, Event::PointerMoved(hover)], + ); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(ctx.input(|i| i.pointer.interact_pos()), Some(hover)); + assert_eq!(app.session.active().unwrap().selection.objects, vec![group]); + assert_eq!(app.session.active().unwrap().isolation, None, "the first fresh click remains single"); + review_gesture_press(&mut app, &ctx, at, start + 6.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 7.0 * step); + assert!(ctx.input(|i| i.pointer.button_triple_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "the fresh pair uses release positions, not subsequent hover positions"); +} From 518f9b4eb59b16838c51d37b7317a0bacfb0b7ff Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 15:08:45 -0800 Subject: [PATCH 27/34] Format release-position control input events --- crates/ui-egui/tests/image_trace_ignore_sampler.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs index 167f275a96..af8e9d6757 100644 --- a/crates/ui-egui/tests/image_trace_ignore_sampler.rs +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -1047,7 +1047,10 @@ fn review_followup_release_position_survives_a_later_hover_move() { &mut app, &ctx, start + 4.0 * step, - vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Default::default() }, Event::PointerMoved(hover)], + vec![ + Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Default::default() }, + Event::PointerMoved(hover), + ], ); assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); assert_eq!(ctx.input(|i| i.pointer.interact_pos()), Some(hover)); From 67c446b31345e91074265c3ff7358b1662b24e1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 18:16:47 -0800 Subject: [PATCH 28/34] PSD import: a knockout that cuts nothing gives back the warnings of a merge it left short of memory A visible knockout whose trial merge cut nothing kept the warnings that drawing the layers below it recorded while its canvas was held. A merge below it that only failed for want of that memory then came in merged, with a warning that it hadn't been applied. Such a trial now gives back what it counted, and the layers count again when they come in. The PSD catalog test compares the whole numbers of each warning and its translation, and checks that each complete catalog puts the translated reason inside the warnings that carry one. --- crates/engine/src/cmd/fileio/psdlayers.rs | 11 ++++++++++ .../engine/src/cmd/fileio/tests_psdlayers.rs | 22 +++++++++++++++++++ crates/ui-egui/src/i18n/tests.rs | 11 ++++++---- 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 3779b72745..17e6c3f814 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -863,6 +863,8 @@ struct Builder<'a, F> { laid_blank: Vec, /// The groups of both, in the order they were found. blank_log: Vec, + /// How many times a merge was counted as not made because it needed more memory than allowed. + squeezed: usize, } impl [f32; 3]> Builder<'_, F> { @@ -1274,6 +1276,7 @@ impl [f32; 3]> Builder<'_, F> { /// Count record `i` as a clipped layer left unclipped (once). fn unclip(&mut self, i: usize) { + self.squeezed += 1; if let Some(s) = self.unclipped.get_mut(i) && !*s { @@ -1305,6 +1308,7 @@ impl [f32; 3]> Builder<'_, F> { if self.knocks(&u, &out, level)? { let saved = self.saved(); let noted = self.noted_so_far(); + let squeezed = self.squeezed; let outer = self.try_from_here(); let knocked = self.knock(&out, &u)?; self.tried(outer, u.visible && matches!(knocked, Knocked::Merged(_)))?; @@ -1334,9 +1338,14 @@ impl [f32; 3]> Builder<'_, F> { self.restore(saved)?; self.unnote(noted); } + // A merge below it that its held canvas left without the memory it needed may + // be made when they come in without it: what drawing them counted is given back + // and counted again then. + Knocked::Nothing if self.squeezed != squeezed => self.restore(saved)?, Knocked::Nothing => self.refund(saved.spent)?, Knocked::TooLarge => { self.restore(saved)?; + self.squeezed += 1; self.unknock(u.record); } } @@ -1382,6 +1391,7 @@ impl [f32; 3]> Builder<'_, F> { } } else { self.restore(saved)?; + self.squeezed += 1; self.notes.unmerged += 1; u.blend = Blend::Mode(BlendMode::Normal); out.push(u); @@ -2025,6 +2035,7 @@ pub(super) fn import( blank: vec![None; records.len()], laid_blank: vec![false; records.len()], blank_log: vec![], + squeezed: 0, }; let layers = b.list(&items, Level::Top)?; // A drawing for a knockout or a clip leaves hidden layers out; those that came in anyway aren't. diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index d197658c20..d5dccfd662 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -890,6 +890,28 @@ fn a_knockout_merge_past_the_memory_allowed_leaves_the_layers_apart() { } } +/// A knockout that cuts nothing gives back what drawing the layers below it counted: here a +/// knockout at 0 fill beside a group, whose own knockout doesn't fit 192 bytes while the outer +/// knockout's canvas is held, but merges when the group comes in. +#[test] +fn a_knockout_that_cuts_nothing_doesnt_keep_what_drawing_below_it_counted() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let layers = [ + group_end(), + group_end(), + layer("Opaque", [0, 0, 2, 2], [255, 0, 0, 255]), + knockout(layer("Inner cut", [0, 0, 1, 2], [0, 0, 255, 255]), 1, 0), + group("Inner", b"norm"), + knockout(layer("Outer cut", [2, 2, 4, 4], [0, 0, 255, 255]), 1, 0), + group("Outer", b"norm"), + ]; + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 192, cms).unwrap().unwrap(); + let outer = doc.layers[0].children().unwrap(); + assert_eq!(outer.iter().map(|c| name(c)).collect::>(), ["Inner", "Outer cut"], "{warnings:?}"); + assert_eq!(outer[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Opaque + Inner cut"], "{warnings:?}"); + assert!(warnings.is_empty(), "{warnings:?}"); +} + /// A knockout merge that can't be made leaves the import the whole allowance for reading the layers /// apart: here the merge decodes 22 layers over one another before the layer beside them makes its /// canvas too large, which used up nearly all of eight times 64 KiB. The merge has that allowance diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 8cdd1a490e..34d4c3f9f1 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -625,12 +625,15 @@ fn psd_import_strings_are_in_complete_catalogs() { for s in &shown { let tr = message(lang, s); assert_ne!(&tr, s, "{code}"); - for n in numbers(s) { - assert!(tr.contains(&n), "{code}: {tr} lost {n}"); - } + let (mut source, mut translated) = (numbers(s), numbers(&tr)); + source.sort(); + translated.sort(); + assert_eq!(source, translated, "{code}: {tr}"); } for (s, inner) in [(unread_slices, nested), (unread_layers, damaged)] { - assert!(!message(lang, s).contains(inner), "{code}: {s}"); + let reason = message(lang, inner); + assert_ne!(reason, inner, "{code}"); + assert!(message(lang, s).contains(&reason), "{code}: {s}"); } assert!(message(lang, &merged).contains("Hue, Luminosity"), "{code}"); assert!(message(lang, &opened_with_notes(1, &one)).ends_with(&message(lang, &one)), "{code}"); From eb7f64d5b3311f5995f4ccebb288b6a0f7b2e244 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 18:25:27 -0800 Subject: [PATCH 29/34] Transform: a shape turn past the coordinate limit is an error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - object.setLiveShape checks every shape named in `ids` against the coordinate limit (±4,000,000 pt) after the edit, so a rectangle, ellipse or polygon that is not selected can no longer be turned out of range; the call is an error and changes nothing. - LiveShape::set_shape_angle brings the angle into [0, 360) before it works out the turn, so a very large angle reaches the same final angle from any starting angle. - The params text and docs/mcp.md say that `null` counts as an omitted key, that a pixel-aligned shape goes back on the pixel grid after the turn, and that a turn out of range is an error. - The panel test reads the Rotate and Angle fields by name, and checks that the Angle field is empty for mixed angles. --- crates/doc/src/node/live_shape.rs | 2 ++ crates/doc/src/node/tests.rs | 14 ++++++++ crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/object/shape.rs | 5 +++ crates/engine/src/tests/livecorners.rs | 22 +++++++++++++ crates/ui-egui/src/panels/transform/tests.rs | 34 +++++++++++++++----- docs/mcp.md | 11 ++++--- 7 files changed, 77 insertions(+), 13 deletions(-) diff --git a/crates/doc/src/node/live_shape.rs b/crates/doc/src/node/live_shape.rs index 42544be99b..0a17301331 100644 --- a/crates/doc/src/node/live_shape.rs +++ b/crates/doc/src/node/live_shape.rs @@ -164,6 +164,8 @@ impl LiveShape { if !angle.is_finite() { return; } + // Brought into [0, 360) first: `now - angle` loses `now` for a very large angle. + let angle = angle.rem_euclid(360.0); let (xf, local) = match self { LiveShape::Rectangle { w, h, xf, .. } | LiveShape::Ellipse { w, h, xf, .. } => (xf, Point::new(*w / 2.0, *h / 2.0)), LiveShape::Polygon { xf, .. } => (xf, Point::ZERO), diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 789e0f66b2..cdcbf2cf85 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -184,6 +184,20 @@ fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() { assert_eq!((e.polygon_radius(), e.polygon_angle()), (None, None)); } +/// A very large angle turns a rectangle to that angle modulo 360, whatever angle it had before. +#[test] +fn a_shape_takes_a_very_large_angle() { + let close = |a: f64, b: f64| (a - b).abs() < 1e-6; + let want = 1e20f64.rem_euclid(360.0); + for turned in [0.0, 90.0] { + let xf = Affine::translate((50.0, 50.0)) * Affine::rotate(-f64::to_radians(turned)); + let mut r = LiveShape::Rectangle { w: 100.0, h: 50.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf }; + assert!(close(r.shape_angle().unwrap(), turned), "{:?}", r.shape_angle()); + r.set_shape_angle(1e20); + assert!(close(r.shape_angle().unwrap(), want), "from {turned}°: {:?}, not {want}", r.shape_angle()); + } +} + /// A node holding a live rectangle (`w` × `h`, all radii `r`, placed by `xf`) and its path. fn live_rect(w: f64, h: f64, r: f64, xf: Affine) -> Node { let live = LiveShape::Rectangle { w, h, radii: [r; 4], kinds: Default::default(), radii_relative: false, xf }; diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index d0ab36bfd0..39e9d3eab5 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -305,7 +305,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; an angle that is not a number is an error; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index dcefca2501..b2e69cc279 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -361,6 +361,11 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { for id in &ids { super::pixelgrid::resnap(d, *id); } + // A shape named in `ids` and not selected is not checked after the edit: one that a turn or + // a new radius would take past the coordinate limit is an error here, and nothing changes. + if !crate::sanity::objects_in_range(d, &ids) { + return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)"))); + } Ok(()) })?; ok() diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 89958d66f1..1ea6e5091f 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -663,6 +663,28 @@ fn a_rectangle_and_an_ellipse_take_their_angle() { assert!(close(angle(&s, rect), 20.0) && close(before.x, after.x) && close(before.y, after.y), "{before:?} → {after:?}"); } +/// A shape named in `ids` that a turn would take past the coordinate limit (±4,000,000 pt) is an +/// error that changes nothing, whether or not it is selected. +#[test] +fn a_turn_past_the_coordinate_limit_is_an_error() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let mut add = |cmd: &str, p: Value| s.execute(cmd, &p).unwrap()["id"].as_u64().unwrap(); + // Each reaches within 10 pt of the limit and past it when turned. + let rect = add("shape.rectangle", json!({"x": 3_999_890, "y": 100, "width": 100, "height": 100})); + let ellipse = add("shape.ellipse", json!({"x": 3_999_950, "y": 100, "width": 40, "height": 100})); + let polygon = add("shape.polygon", json!({"cx": 3_999_955, "cy": 200, "radius": 50, "sides": 6})); + for (id, key, angle) in [(rect, "rectangleAngle", 45), (ellipse, "ellipseAngle", 90), (polygon, "polygonAngle", 90)] { + for selected in [false, true] { + s.execute("select.set", &json!({"ids": if selected { vec![id] } else { vec![] }})).unwrap(); + let (doc, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let e = s.execute("object.setLiveShape", &json!({"ids": [id], key: angle})).unwrap_err(); + assert!(e.to_string().contains("out of range"), "{key}, selected {selected}: {e}"); + assert!(*s.doc().unwrap().doc == *doc && s.doc().unwrap().history.undo.len() == steps, "{key}, selected {selected}: changed"); + } + } +} + /// A live line's Line Properties: Line Length keeps its first end in place, Line Angle (degrees /// counterclockwise, any finite value brought into 0 to 360) turns it about its midpoint, the /// length applies before the angle, every selected line takes them in one undo step, and a value diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index 0e86ac39fe..dfd6ed66b3 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -171,21 +171,39 @@ fn a_rectangle_and_an_ellipse_show_their_angle() { ids.push(id); } app.run("select.set", json!({"ids": [ids[0]]})).unwrap(); - for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section] { - let shown = texts(&mut app, draw); - for t in ["Angle:", "0°", "30°"] { - assert!(shown.iter().any(|s| s == t), "{t} in {shown:?}"); - } + for (draw, rotate) in [(show as fn(&mut VectorcraftApp, &mut Ui), "Rotate"), (crate::panels::properties::transform_section, "Rotation")] { + assert_eq!(field_text(&mut app, draw, rotate), "0°", "{shape}: {rotate}"); + assert_eq!(field_text(&mut app, draw, "Angle:"), "30°", "{shape}: {rotate}"); } assert!(texts(&mut app, show).iter().any(|s| s == heading), "{heading}"); app.run("select.set", json!({"ids": ids})).unwrap(); - let shown = texts(&mut app, show); - assert!(shown.iter().any(|s| s == "Angle:") && !shown.iter().any(|s| s == "30°" || s == "60°"), "{shape}: {shown:?}"); + assert_eq!(field_text(&mut app, show, "Angle:"), "", "{shape}: mixed angles"); app.run("select.set", json!({"ids": [ids[1]]})).unwrap(); - assert!(texts(&mut app, show).iter().any(|s| s == "60°"), "{shape}"); + assert_eq!(field_text(&mut app, show, "Angle:"), "60°", "{shape}"); } } +/// The text in `draw`'s input named `label`, read from the accessibility tree of a headless frame. +fn field_text(app: &mut VectorcraftApp, draw: fn(&mut VectorcraftApp, &mut Ui), label: &str) -> String { + use egui_kittest::kittest::Queryable; + let state = std::mem::replace(app, VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(320.0, 900.0)).with_accessibility_check(false).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + draw(app, ui); + }, + state, + ); + h.run_steps(3); + let text = h.get_by_role_and_label(egui::accesskit::Role::TextInput, label).value().unwrap_or_default(); + *app = h.into_state(); + text +} + /// Ellipse Properties' Constrain Pie Angle link, in the Transform panel and the Properties panel's /// Transform section: off at first, a click or Space with the keyboard on it toggles it, and while /// it is on a typed Pie Start or End Angle moves the other angle by as much, keeping the span, in diff --git a/docs/mcp.md b/docs/mcp.md index 071a5f21f3..16b212f64f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7061,11 +7061,14 @@ A live rectangle's Rectangle Angle and a live ellipse's Ellipse Angle are `recta (https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) lists both as the shape's rotation on the canvas from 0° to 360°. The rest are VectorCraft's own rules: each selected shape of that kind turns about its own center, keeping its size, corners and pie (an ellipse's pie turns with it), and other -objects stay as they are. The Transform and Properties panels show the angle in each shape's Properties section, blank -when the selected shapes of that kind differ. It is the shape's own angle: after Reset Bounding Box +objects stay as they are. A pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move +its center or change its size. The Transform and Properties panels show the angle in each shape's Properties section, +blank when the selected shapes of that kind differ. It is the shape's own angle: after Reset Bounding Box (`object.resetBoundingBox`) the Rotate field reads 0° while the shape angle keeps the turn. An angle that is not a -number is an error and changes nothing, and the angle the shape already has records no undo step; the same holds for -`polygonAngle`, and the Polygon Properties angle is blank, too, when the selected polygons differ. +number is an error and changes nothing (`null` counts as an omitted key), a shape that the turn would take past the +coordinate limit (±4,000,000 pt) is an error that changes nothing, whether or not it is selected, and the angle the +shape already has records no undo step; the same holds for `polygonAngle`, and the Polygon Properties angle is blank, +too, when the selected polygons differ. ```json {"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"rectangleAngle":30}}} From 2108617fa5ce248ddcd2f37ee86200691cb55097 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 21:13:03 -0800 Subject: [PATCH 30/34] Image Trace: preserve sampler gesture and target ownership Keep consumed releases separate from fresh canvas presses, use click release positions, share the engine trace target selector, reject source misses before sampling, and return from the temporary tool without fresh activation. --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/buildcmds.rs | 2 +- crates/engine/src/cmd/buildcmds/trace.rs | 44 +-- crates/ui-egui/src/canvas.rs | 138 +++++++++- crates/ui-egui/src/canvas/input.rs | 15 +- crates/ui-egui/src/panels/image_trace.rs | 40 ++- .../tests/image_trace_ignore_sampler.rs | 257 ++++++++++++++++++ 7 files changed, 435 insertions(+), 63 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 359fc8761f..250110527c 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -903,7 +903,7 @@ pub use gradpresets::{GradientPreset, GradientPresetEntry}; pub use buildcmds::{TracePreset, TracePresetChange}; /// An Image Trace made off the UI thread, and what it traced (#3098). -pub use buildcmds::{TraceRun, Traced}; +pub use buildcmds::{TraceRun, Traced, image_trace_target}; /// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them). pub(crate) use buildcmds::TracePresetChanges; diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index b739ca5f7e..905372fd06 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -42,7 +42,7 @@ pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, iso use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge}; use shape_builder::{sb_merge, sb_regions}; pub(crate) use trace::TracePresetChanges; -pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced}; +pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target}; use trace::{trace_expand, trace_make, trace_presets_delete, trace_presets_save, trace_release, trace_set_view}; /// Name of an Image Trace group. diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 203fd62338..3ef8edc5c4 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -600,6 +600,30 @@ struct Prepared { library: Vec<([u8; 3], Paint)>, } +/// The object `imageTrace.make` would trace, without preparing settings or reading image bytes. +pub fn image_trace_target(s: &Session, p: &Value) -> Result { + target_image(s, "imageTrace.make", p).map(|(target, _)| target) +} + +fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box)> { + let roots = root_ids(s, p)?; + let d = &s.doc()?.doc; + roots + .iter() + .find_map(|r| { + let n = d.node(*r)?; + match &n.kind { + NodeKind::Image(i) => Some((*r, i.clone())), + _ if is_trace_group(n) => match &n.children()?.first()?.kind { + NodeKind::Image(i) => Some((*r, i.clone())), + _ => None, + }, + _ => None, + } + }) + .ok_or_else(|| bad(c, "select an image (or an Image Trace group)")) +} + /// What command `c` with params `p` traces, and how, from the session: everything but the trace. fn prepare(s: &Session, c: &str, p: &Value) -> Result { let mut params = trace_params(s, c, p)?; @@ -619,25 +643,7 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result { None if is(tr::preset(named)) || is(tr::enhanced_preset(named)) => named.to_string(), None => "Custom".to_string(), }; - let roots = root_ids(s, p)?; - // The image (inside a trace group, or selected directly). - let (target, image) = { - let d = &s.doc()?.doc; - roots - .iter() - .find_map(|r| { - let n = d.node(*r)?; - match &n.kind { - NodeKind::Image(i) => Some((*r, i.clone())), - _ if is_trace_group(n) => match &n.children()?.first()?.kind { - NodeKind::Image(i) => Some((*r, i.clone())), - _ => None, - }, - _ => None, - } - }) - .ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))? - }; + let (target, image) = target_image(s, c, p)?; if by_color && s.doc()?.doc.node(target).is_some_and(vectorcraft_render::effects::has_pathfinder) { return Err(bad(c, LIVE_PATHFINDER_BY_COLOR)); } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index d1406d77d6..bfb89b5833 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -490,7 +490,6 @@ fn reset_ignore_sampler_clicks(ui: &Ui, id: egui::Id) { /// Reclassify only the two clicks whose raw history can still contain a consumed pick. /// Other widgets' clicks count too, as they do in egui; its pointer state stays untouched. fn ignore_sampler_clicks(ui: &Ui, id: egui::Id, consumed: bool) { - let (delay, distance) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist)); let (clicked, primary, at, time) = ui.input(|i| { // A hover move after the release is not the position egui put in its click history. let at = i.events.iter().rev().find_map(|event| match event { @@ -508,6 +507,11 @@ fn ignore_sampler_clicks(ui: &Ui, id: egui::Id, consumed: bool) { return; } let Some(at) = at else { return }; + record_ignore_sampler_click(ui, id, at, time, primary); +} + +fn record_ignore_sampler_click(ui: &Ui, id: egui::Id, at: Pos2, time: f64, primary: bool) { + let (delay, distance) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist)); ui.data_mut(|data| { let history_id = id.with("image-trace-clicks"); let Some(mut clicks) = data.remove_temp::(history_id) else { return }; @@ -551,20 +555,126 @@ fn clear_ignore_sampler_gesture(ui: &Ui, id: egui::Id) { }); } -fn begin_ignore_sampler_pointer(ui: &Ui, id: egui::Id, cancelled: bool) -> bool { - let (pressed, released, down) = ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_released(), i.pointer.primary_down())); - if pressed { - // A fresh press replaces the complete sampler gesture if its release was not observed. - if ignore_sampler_owns_primary(ui, id) { - clear_ignore_sampler_gesture(ui, id); +#[derive(Clone, Copy)] +struct IgnoreSamplerRelease { + button: egui::PointerButton, + at: Pos2, + clicked: bool, +} + +#[derive(Default)] +struct IgnoreSamplerPointer { + owned: bool, + replaced: bool, + ordinary_pressed: bool, + consumed_release: bool, + releases: Vec, +} + +/// Attribute a fresh press after an owned release before egui's per-frame flags lose their order. +fn ignore_sampler_pointer_frame(ui: &Ui, id: egui::Id, cancelled: bool) -> IgnoreSamplerPointer { + let owned = ignore_sampler_owns_primary(ui, id); + if !owned && !cancelled { + return IgnoreSamplerPointer::default(); + } + let (distance, duration) = ui.ctx().options(|o| (o.input_options.max_click_dist, o.input_options.max_click_duration)); + ui.input(|i| { + let mut frame = IgnoreSamplerPointer { owned, ..Default::default() }; + let mut first_press_owned = cancelled; + let mut press = None; + let mut moved = false; + let mut primary_pressed = false; + for event in &i.events { + match event { + egui::Event::PointerMoved(at) => { + if let Some((_, origin)) = press { + moved |= Pos2::distance(origin, *at) > distance; + } + } + egui::Event::PointerButton { pos, button, pressed, .. } => { + if *pressed { + press = Some((*button, *pos)); + moved = false; + if *button == egui::PointerButton::Primary { + primary_pressed = true; + frame.replaced |= frame.owned; + // An observed old Up ends that cancelled sequence; without it, + // a fresh invalid press keeps the existing cancellation gate. + frame.owned = first_press_owned && !frame.consumed_release; + first_press_owned = false; + frame.ordinary_pressed |= !frame.owned; + } + } else { + // A fresh primary click needs its own Down, not an earlier owned click. + // Slop/origin are shared by buttons in egui; each press resets them, and + // a release clears its press time. In-frame presses have the same time. + let clicked = ignore_sampler_release_clicked(press, moved, primary_pressed, *button, duration); + ignore_sampler_release(&mut frame, *button, *pos, clicked); + if *button == egui::PointerButton::Primary { + primary_pressed = false; + } + press = None; + } + } + _ => {} + } } - if cancelled { - ui.data_mut(|data| data.insert_temp(ignore_sampler_primary_id(id), true)); + frame + }) +} + +fn ignore_sampler_release_clicked( + press: Option<(egui::PointerButton, Pos2)>, + moved: bool, + primary_pressed: bool, + button: egui::PointerButton, + duration: f64, +) -> bool { + let matched = if button == egui::PointerButton::Primary { primary_pressed } else { press.is_some_and(|(b, _)| b == button) }; + matched && !moved && (press.is_none() || !matches!(duration.partial_cmp(&0.0), Some(std::cmp::Ordering::Less))) +} + +fn ignore_sampler_release(frame: &mut IgnoreSamplerPointer, button: egui::PointerButton, at: Pos2, clicked: bool) { + if button == egui::PointerButton::Primary && frame.owned { + frame.consumed_release = true; + frame.releases.clear(); + } else if frame.consumed_release { + frame.releases.push(IgnoreSamplerRelease { button, at, clicked }); + } +} + +fn ignore_sampler_frame_clicks(ui: &Ui, id: egui::Id, frame: &IgnoreSamplerPointer, consumed: bool) { + if !frame.consumed_release || !frame.ordinary_pressed { + ignore_sampler_clicks(ui, id, consumed); + return; + } + // Consume the old sequence, then classify only subsequent ordinary releases. A new Down + // still reaches the tool when the last release belongs to the consumed sequence. + reset_ignore_sampler_clicks(ui, id); + ui.data_mut(|data| data.insert_temp(id.with("image-trace-click-count"), 0u8)); + let time = ui.input(|i| i.time); + for release in &frame.releases { + let primary = release.button == egui::PointerButton::Primary; + if release.clicked { + record_ignore_sampler_click(ui, id, release.at, time, primary); + } else if primary { + ui.data_mut(|data| data.insert_temp(id.with("image-trace-click-count"), 0u8)); } } - let consumed = ignore_sampler_owns_primary(ui, id) && (pressed || released || down); - ignore_sampler_clicks(ui, id, consumed); - consumed +} + +fn begin_ignore_sampler_pointer(ui: &Ui, id: egui::Id, cancelled: bool) -> (bool, bool) { + let frame = ignore_sampler_pointer_frame(ui, id, cancelled); + if frame.replaced { + // This also replaces an abandoned sampler Down whose release was not observed. + clear_ignore_sampler_gesture(ui, id); + } + if frame.owned { + ui.data_mut(|data| data.insert_temp(ignore_sampler_primary_id(id), true)); + } + let consumed = frame.owned && ui.input(|i| i.pointer.primary_pressed() || i.pointer.primary_released() || i.pointer.primary_down()); + ignore_sampler_frame_clicks(ui, id, &frame, consumed); + (consumed, frame.ordinary_pressed) } fn end_ignore_sampler_pointer(ui: &Ui, id: egui::Id) { @@ -589,8 +699,8 @@ fn observe_hidden_ignore_sampler_pointer(app: &VectorcraftApp, ui: &Ui, home_sho /// A sampler press keeps its release, even if its Down completes or its binding expires held. fn input_after_sampler_refresh(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect, cancelled: bool) { - let consumed = begin_ignore_sampler_pointer(ui, resp.id, cancelled); - if !consumed && (!cancelled || !ui.input(|i| i.pointer.any_pressed())) { + 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); } end_ignore_sampler_pointer(ui, resp.id); diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 3aa3b48613..748ad07654 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -136,7 +136,7 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo drag_held(app, ui, &f, d, p); } else { // The drag ends where its button went up: the moves after the release in this frame are hover. - drag_released(app, ui, &f, d, release_pos(ui, button).unwrap_or(p)); + drag_released(app, ui, &f, d, release_pos(ui, button, false).unwrap_or(p)); } } else if let Some(p) = hover_tool // A press on an artboard's name starts no drag: the moves while it is held are not hover. @@ -189,14 +189,14 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo if !super::ignore_sampler_owns_primary(ui, resp.id) && super::primary_click_count(ui, resp) == 2 && !f.modal - && let Some(p) = at + && let Some(p) = release_pos(ui, egui::PointerButton::Primary, true).or(at) { double_click(app, ui, &f, p); } if !super::ignore_sampler_owns_primary(ui, resp.id) && super::primary_click_count(ui, resp) == 3 && !f.modal - && let Some(p) = at + && let Some(p) = release_pos(ui, egui::PointerButton::Primary, true).or(at) { triple_click(app, ui, &f, p); } @@ -638,13 +638,14 @@ fn triple_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { dispatch(app, &ev, view); } -/// Where `button` went up in this frame, if it did. -fn release_pos(ui: &Ui, button: egui::PointerButton) -> Option { +/// Where `button` went up: the first release ends a drag, the last classifies this frame's click. +fn release_pos(ui: &Ui, button: egui::PointerButton, last: bool) -> Option { ui.input(|i| { - i.events.iter().find_map(|e| match e { + let mut releases = i.events.iter().filter_map(|e| match e { egui::Event::PointerButton { pos, button: b, pressed: false, .. } if *b == button => Some(*pos), _ => None, - }) + }); + if last { releases.next_back() } else { releases.next() } }) } diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index 0303467c3c..b669f972b3 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -171,28 +171,17 @@ thread_local! { static TARGET_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// The object Trace acts on: the first selected image or Image Trace object in paint order, as -/// `imageTrace.make` takes it, else the first selected object. Only the selected images and Image -/// Trace objects are put in paint order. +/// The image or Image Trace object `imageTrace.make` takes from the selected roots, else the +/// first selected non-traceable object's metadata. Release and Expand keep their own selection scope. fn find_target(app: &VectorcraftApp) -> Target { let Some(st) = app.session.active() else { return Target::default() }; #[cfg(test)] TARGET_LOOKUPS.with(|n| n.set(n.get() + 1)); - let mut any_trace = false; - let traceable: Vec = st - .selection - .objects - .iter() - .copied() - .filter(|id| { - st.doc.node(*id).is_some_and(|n| { - let trace = is_trace(n); - any_trace |= trace; - trace || matches!(n.kind, NodeKind::Image(_)) - }) - }) - .collect(); - let node = st.doc.paint_order(traceable).into_iter().find_map(|id| st.doc.node(id)).or_else(|| first_node(app)); + let any_trace = st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(is_trace)); + let node = vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null) + .ok() + .and_then(|id| st.doc.node(id)) + .or_else(|| first_node(app).filter(|n| !is_trace(n) && !matches!(n.kind, NodeKind::Image(_)))); let Some(n) = node else { return Target { any_trace, ..Target::default() } }; Target { object: Some((st.uid, n.id)), @@ -388,6 +377,15 @@ fn sampled_ignore_color(app: &VectorcraftApp, s: &crate::state::TraceIgnoreSampl return None; } let pixel = image.xf.inverse() * point; + if !pixel.x.is_finite() + || !pixel.y.is_finite() + || pixel.x < 0.0 + || pixel.y < 0.0 + || pixel.x >= f64::from(image.width.max(1)) + || pixel.y >= f64::from(image.height.max(1)) + { + return None; + } let [r, g, b, alpha] = doc.images.get(&image.key)?.sample_object(pixel.x, pixel.y, (image.width, image.height), 1)?; (alpha != 0).then(|| format!("#{r:02x}{g:02x}{b:02x}")) } @@ -431,9 +429,9 @@ pub(crate) fn apply_ignore_color_sample(app: &mut VectorcraftApp, p: &Value) { } set_pstate(&ctx, "image-trace", st); ctx.request_repaint(); - // The old deferred SwitchTool ran after the panel accepted the color. Keep that order and - // fresh tool choice; a miss above has no switch request and remains armed. - app.select_tool(&s.back); + // Complete the temporary tool without treating its return as a fresh explicit tool choice. + // A miss above has no switch request and remains armed. + app.return_to_tool(&s.back); } /// The selected Image Trace object's View row (Control bar, Properties). diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs index af8e9d6757..4496089271 100644 --- a/crates/ui-egui/tests/image_trace_ignore_sampler.rs +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -1061,3 +1061,260 @@ fn review_followup_release_position_survives_a_later_hover_move() { assert!(ctx.input(|i| i.pointer.button_triple_clicked(PointerButton::Primary))); assert_eq!(app.session.active().unwrap().isolation, Some(group), "the fresh pair uses release positions, not subsequent hover positions"); } + +fn review_596866_button(at: Pos2, pressed: bool) -> Event { + Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() } +} + +fn review_596866_owned_release_then_press(coalesced: bool) { + let (mut app, ctx, point, group) = review_gesture_group_fixture(); + click_control(&mut app, &ctx, SAMPLE_TIP); + app.run("select.none", json!({})).unwrap(); + let at = review_gesture_screen(&app, &ctx, point); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + assert_eq!(app.session.tool_id(), "selection"); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert!(ctx.input(|i| i.pointer.primary_down())); + let document = app.session.active().unwrap().doc.clone(); + let paint = app.session.paint.clone(); + let history = (app.session.active().unwrap().history.undo.len(), app.session.active().unwrap().history.redo.len()); + if coalesced { + frame_at(&mut app, &ctx, start + step, vec![review_596866_button(at, false), review_596866_button(at, true)]); + assert!(ctx.input(|i| i.pointer.primary_released() && i.pointer.primary_pressed() && i.pointer.primary_down())); + } else { + review_gesture_release(&mut app, &ctx, at, start + step); + assert_eq!(app.session.active().unwrap().selection.objects, Vec::::new(), "CONTROL: the owned Up remains consumed"); + review_gesture_press(&mut app, &ctx, at, start + 3.0 * step); + } + let before_release = review_gesture_observation(&app, &ctx); + review_gesture_release(&mut app, &ctx, at, start + 4.0 * step); + let after_release = review_gesture_observation(&app, &ctx); + assert!(after_release.0 && !after_release.1, "the owned prefix and one fresh click form egui's raw Double"); + assert!( + before_release.2 == vec![group] && before_release.3.is_none() && after_release.2 == vec![group] && after_release.3.is_none(), + "coalesced={coalesced}: the first fresh click must select without isolation: before={before_release:?}, after={after_release:?}" + ); + assert_eq!(app.session.active().unwrap().doc, document); + assert_eq!(app.session.paint, paint); + assert_eq!((app.session.active().unwrap().history.undo.len(), app.session.active().unwrap().history.redo.len()), history); + if !coalesced { + review_gesture_press(&mut app, &ctx, at, start + 6.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 7.0 * step); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "CONTROL: the second fresh click still isolates"); + } +} + +#[test] +fn review_596866_owned_up_then_new_down_in_one_frame_keeps_the_next_click_single() { + review_596866_owned_release_then_press(false); + review_596866_owned_release_then_press(true); +} + +#[test] +fn review_596866_second_corrected_release_uses_its_release_position() { + let (mut control, control_ctx, control_point, control_group) = review_gesture_group_fixture(); + let control_at = review_gesture_screen(&control, &control_ctx, control_point); + review_gesture_ordinary_pair(&mut control, &control_ctx, control_at, control_at, control_group); + + let (mut app, ctx, point, group) = review_gesture_group_fixture(); + click_control(&mut app, &ctx, SAMPLE_TIP); + app.run("select.none", json!({})).unwrap(); + let at = review_gesture_screen(&app, &ctx, point); + let hover = review_gesture_screen(&app, &ctx, Point::new(340.0, 250.0)); + assert!(at.distance(hover) > ctx.options(|o| o.input_options.max_click_dist)); + let expected = review_gesture_state(&app); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + review_gesture_release(&mut app, &ctx, at, start + step); + assert_eq!(review_gesture_state(&app), expected, "the stale prefix is consumed"); + review_gesture_press(&mut app, &ctx, at, start + 3.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 4.0 * step); + assert_eq!(app.session.active().unwrap().selection.objects, vec![group]); + assert_eq!(app.session.active().unwrap().isolation, None, "the first fresh click is single"); + review_gesture_press(&mut app, &ctx, at, start + 6.0 * step); + frame_at(&mut app, &ctx, start + 7.0 * step, vec![review_596866_button(at, false), Event::PointerMoved(hover)]); + assert!(ctx.input(|i| i.pointer.button_triple_clicked(PointerButton::Primary))); + assert_eq!(ctx.input(|i| i.pointer.interact_pos()), Some(hover)); + assert_eq!( + app.session.active().unwrap().isolation, + Some(group), + "the corrected Double belongs to its release on the group, not the later blank hover" + ); +} + +fn review_596866_bound_point(app: &VectorcraftApp, target: NodeId) -> Point { + let state = app.session.active().unwrap(); + let node = state.doc.node(target).unwrap(); + let original = node.children().and_then(|children| children.first()).map_or(node, |child| child.as_ref()); + let NodeKind::Image(image) = &original.kind else { panic!("the retained binding has a source image") }; + image.xf * Point::new(f64::from(image.width) * 0.25, f64::from(image.height) * 0.5) +} + +fn review_596866_source_image(app: &VectorcraftApp, target: NodeId) -> NodeId { + let state = app.session.active().unwrap(); + let node = state.doc.node(target).unwrap(); + let original = node.children().and_then(|children| children.first()).map_or(node, |child| child.as_ref()); + assert!(matches!(original.kind, NodeKind::Image(_)), "the retained binding has an original source image"); + original.id +} + +fn review_596866_pick_binding(app: &mut VectorcraftApp, ctx: &egui::Context) -> NodeId { + click_control(app, ctx, SAMPLE_TIP); + let target = app.ui.trace_ignore_sampler.as_ref().unwrap().target; + let source = review_596866_source_image(app, target); + let point = review_596866_bound_point(app, target); + let at = review_gesture_screen(app, ctx, point); + let (start, step) = review_gesture_times(ctx); + review_gesture_press(app, ctx, at, start); + review_gesture_release(app, ctx, at, start + step); + settle(app, ctx); + assert!(app.ui.trace_ignore_sampler.is_none(), "an opaque original pixel completes the pick"); + source +} + +fn review_596866_ignore_color(app: &VectorcraftApp, source: NodeId) -> Value { + let doc = &app.session.active().unwrap().doc; + assert!(matches!(doc.node(source).unwrap().kind, NodeKind::Image(_)), "retrace retains the original source image identity"); + let trace = doc.node(doc.parent_of(source).unwrap()).unwrap(); + assert_eq!(trace.children().unwrap().first().unwrap().id, source, "the source remains the trace's first child"); + trace.extras().trace.as_ref().expect("the source's current parent is an Image Trace")["params"]["ignoreColor"].clone() +} + +fn review_596866_nested_trace_selection() -> (VectorcraftApp, egui::Context, NodeId, NodeId) { + let (mut app, ctx) = fixture(true, [37, 83, 149], true); + let first = selected(&app).id; + let parent = review_gesture_enclose_source(&mut app, first); + let bytes = { + let state = app.session.active().unwrap(); + let original = state.doc.node(first).unwrap().children().unwrap()[0].as_ref(); + let NodeKind::Image(image) = &original.kind else { panic!("the first trace retains its input") }; + state.doc.images[&image.key].bytes.clone() + }; + app.run( + "file.place", + json!({"name": "second-sampler-source.png", "dataBase64": vectorcraft_format::base64_encode(&bytes), "link": false, "at": [280, 150]}), + ) + .unwrap(); + app.run("imageTrace.make", json!({"preset": "Default", "params": {"mode": "blackAndWhite", "threshold": 127, "noise": 1, "ignoreWhite": false}})) + .unwrap(); + let second = selected(&app).id; + assert_ne!(first, second); + app.run("select.set", json!({"ids": [parent.0, first.0, second.0]})).unwrap(); + settle(&mut app, &ctx); + let state = app.session.active().unwrap(); + assert_eq!(state.selection.objects, vec![parent, first, second], "CONTROL: the public selection keeps the ordinary ancestor and nested trace"); + assert!(state.doc.node(parent).unwrap().extras().trace.is_none(), "the selected ancestor is not itself traceable"); + assert_eq!(state.doc.paint_order([first, second]), vec![first, second], "the nested trace precedes the top-level trace"); + (app, ctx, first, second) +} + +#[test] +fn review_596866_preview_retraces_the_retained_sampler_binding() { + let (mut control, control_ctx) = fixture(true, [37, 83, 149], true); + let control_source = review_596866_pick_binding(&mut control, &control_ctx); + assert_eq!(review_596866_ignore_color(&control, control_source), "#255395", "CONTROL: a single trace receives its sampled color"); + + let (mut app, ctx, first, second) = review_596866_nested_trace_selection(); + click_control(&mut app, &ctx, SAMPLE_TIP); + let bound = app.ui.trace_ignore_sampler.as_ref().unwrap().target; + assert!(bound == first || bound == second); + let other = if bound == first { second } else { first }; + let other_before = app.session.active().unwrap().doc.node(other).unwrap().clone(); + let bound_source = review_596866_source_image(&app, bound); + assert_ne!(review_596866_ignore_color(&app, bound_source), "#255395", "CONTROL: the sample must change the bound trace's stored color"); + let point = review_596866_bound_point(&app, bound); + let at = review_gesture_screen(&app, &ctx, point); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + review_gesture_release(&mut app, &ctx, at, start + step); + settle(&mut app, &ctx); + let bound_color = review_596866_ignore_color(&app, bound_source); + let other_after = app.session.active().unwrap().doc.node(other).cloned(); + assert!( + bound_color == "#255395" && other_after.as_ref() == Some(&other_before), + "Preview must update only retained sampler target {bound:?}: bound_color={bound_color}, other_changed_or_missing={}", + other_after.as_ref() != Some(&other_before) + ); +} + +fn review_596866_grid_visible(app: &VectorcraftApp) -> bool { + vectorcraft_tools::distort::perspective::PerspectiveGrid::current(&app.session.active().unwrap().doc).visible +} + +fn review_596866_hidden_grid_fixture() -> (VectorcraftApp, egui::Context) { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + app.select_tool("perspectiveGrid"); + assert!(review_596866_grid_visible(&app), "CONTROL: a deliberate fresh tool choice shows the grid"); + app.run("perspective.grid.show", json!({"visible": false})).unwrap(); + settle(&mut app, &ctx); + assert_eq!(app.session.tool_id(), "perspectiveGrid"); + assert!(!review_596866_grid_visible(&app)); + (app, ctx) +} + +#[test] +fn review_596866_successful_pick_preserves_a_hidden_perspective_grid() { + let (mut control, _) = review_596866_hidden_grid_fixture(); + let revision = control.session.active().unwrap().revision; + control.select_tool("perspectiveGrid"); + assert!(review_596866_grid_visible(&control), "CONTROL: explicitly choosing the tool again still shows the grid"); + assert!(control.session.active().unwrap().revision > revision); + + let (mut app, ctx) = review_596866_hidden_grid_fixture(); + let expected = review_gesture_state(&app); + let source = review_596866_pick_binding(&mut app, &ctx); + assert_eq!(app.session.tool_id(), "perspectiveGrid"); + let observed = review_gesture_state(&app); + let visible = review_596866_grid_visible(&app); + click_control(&mut app, &ctx, "Trace"); + assert_eq!(review_596866_ignore_color(&app, source), "#255395", "CONTROL: the valid Preview-off pick really changed the panel draft"); + assert!(!visible, "returning from the temporary sampler must not show the hidden grid"); + assert_eq!(observed, expected, "the Preview-off pick must not change document, selection, revision, history or paint"); +} + +fn review_596866_coalesced_fresh_suffix(dragged: bool) { + let (mut app, ctx, point, group) = review_gesture_group_fixture(); + click_control(&mut app, &ctx, SAMPLE_TIP); + app.run("select.none", json!({})).unwrap(); + let at = review_gesture_screen(&app, &ctx, point); + let distance = ctx.options(|o| o.input_options.max_click_dist); + let away = at + vec2(distance + 8.0, 0.0); + assert!(away.distance(at) > distance && app.canvas_rect.unwrap().contains(away)); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + assert_eq!(app.session.tool_id(), "selection"); + assert!(app.ui.trace_ignore_sampler.is_none() && ctx.input(|i| i.pointer.primary_down())); + let mut events = vec![review_596866_button(at, false), review_596866_button(at, true)]; + if dragged { + events.extend([Event::PointerMoved(away), Event::PointerMoved(at)]); + } + events.push(review_596866_button(at, false)); + frame_at(&mut app, &ctx, start + step, events); + assert!(ctx.input(|i| i.pointer.primary_pressed() && i.pointer.primary_released() && !i.pointer.primary_down())); + assert!(ctx.input(|i| i.pointer.button_clicked(PointerButton::Primary)), "the old owned release really contributed a raw click"); + assert_eq!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)), !dragged, "only the valid fresh suffix is a second raw click"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the fresh Down still selects the group"); + assert_eq!(app.session.active().unwrap().isolation, None, "neither the first fresh click nor an out-and-back drag may isolate"); + // The ordinary tool receives its Up in the next empty frame; no document/history oracle + // forbids legitimate drag completion work. + frame_at(&mut app, &ctx, start + 2.0 * step, vec![]); + assert_eq!(app.session.active().unwrap().isolation, None); + review_gesture_press(&mut app, &ctx, at, start + 3.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 4.0 * step); + if dragged { + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().selection.objects, vec![group]); + assert_eq!(app.session.active().unwrap().isolation, None, "the invalid suffix must not advance ordinary click history"); + review_gesture_press(&mut app, &ctx, at, start + 6.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 7.0 * step); + } + assert!(ctx.input(|i| i.pointer.button_triple_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "the second qualifying ordinary click still isolates: dragged={dragged}"); +} + +#[test] +fn review_596866_coalesced_fresh_release_qualifies_its_own_click() { + review_596866_coalesced_fresh_suffix(false); + review_596866_coalesced_fresh_suffix(true); +} From 04242429756abd9fabcc6d71b0d0edea75eba341 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 18 Nov 2026 22:01:29 -0800 Subject: [PATCH 31/34] Image Trace test: enable sampling on both candidate traces --- crates/ui-egui/tests/image_trace_ignore_sampler.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs index 4496089271..5de21672f7 100644 --- a/crates/ui-egui/tests/image_trace_ignore_sampler.rs +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -1196,7 +1196,7 @@ fn review_596866_nested_trace_selection() -> (VectorcraftApp, egui::Context, Nod json!({"name": "second-sampler-source.png", "dataBase64": vectorcraft_format::base64_encode(&bytes), "link": false, "at": [280, 150]}), ) .unwrap(); - app.run("imageTrace.make", json!({"preset": "Default", "params": {"mode": "blackAndWhite", "threshold": 127, "noise": 1, "ignoreWhite": false}})) + app.run("imageTrace.make", json!({"preset": "Default", "params": {"mode": "blackAndWhite", "threshold": 127, "noise": 1, "ignoreWhite": true}})) .unwrap(); let second = selected(&app).id; assert_ne!(first, second); From 4b40c56f691a2e5766fcdbd07b4c3502c12d9ba7 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 19 Nov 2026 08:30:32 +0000 Subject: [PATCH 32/34] Image Trace: preserve qualified click provenance and temporary tool return --- crates/ui-egui/src/app/input.rs | 1 + crates/ui-egui/src/canvas.rs | 174 ++++++++++-------- crates/ui-egui/src/canvas/drag.rs | 20 +- crates/ui-egui/src/canvas/input.rs | 21 ++- .../ui-egui/src/panels/image_trace/tests.rs | 36 +++- .../tests/image_trace_ignore_sampler.rs | 109 +++++++++++ 6 files changed, 273 insertions(+), 88 deletions(-) diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 95f719d08b..5960a80187 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -179,6 +179,7 @@ impl VectorcraftApp { /// injected until the batch was actually applied, so a burst of hidden ticks cannot queue /// several steps of a drag or replay them together later. pub fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + crate::canvas::capture_pointer_before_input(ctx, raw.viewport_id); self.fill_raw_input(ctx, raw); crate::font_menu::sync_wheel_target(self, ctx, raw.viewport_id); crate::font_menu::take_raw_wheel(ctx, raw); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index bfb89b5833..d779b2a08b 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -468,6 +468,51 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +#[derive(Clone, Copy, Default)] +struct CanvasClick { + count: u8, + at: Option, +} + +fn pointer_before_input_id(viewport: egui::ViewportId) -> egui::Id { + egui::Id::unique("canvas-pointer-before-input").with(viewport) +} + +/// The existing host hook calls this before egui updates the pointer for this batch. +pub(crate) fn capture_pointer_before_input(ctx: &egui::Context, viewport: egui::ViewportId) { + let pointer = ctx.input_for(viewport, |i| i.pointer.clone()); + ctx.data_mut(|data| data.insert_temp(pointer_before_input_id(viewport), pointer)); +} + +/// Each release keeps egui's own qualification, including earlier releases in this batch. +fn canvas_pointer_releases(ui: &Ui) -> Vec { + let previous = ui.data(|data| data.get_temp::(pointer_before_input_id(ui.ctx().viewport_id()))).unwrap_or_default(); + let options = ui.ctx().options(|o| o.input_options); + let pixels_per_point = ui.ctx().pixels_per_point(); + ui.input(|i| { + let mut counts = [0usize; egui::NUM_POINTER_BUTTONS]; + for event in &i.events { + if let egui::Event::PointerButton { button, pressed: false, .. } = event { + counts[*button as usize] += 1; + } + } + i.events.iter().enumerate().filter_map(|(index, event)| { + let egui::Event::PointerButton { pos, button, pressed: false, .. } = event else { return None }; + let clicked = if counts[*button as usize] == 1 { + i.pointer.button_clicked(*button) + } else { + // Aggregated flags cannot identify a later non-click release. Replay only + // an ambiguous button's prefix, before its Up, through egui's public API. + let mut before = i.clone(); + before.pointer = previous.clone(); + let raw = egui::RawInput { time: Some(i.time), events: i.events[..index].to_vec(), ..i.raw.clone() }; + before.begin_pass(raw, false, pixels_per_point, options).pointer.could_any_button_be_click() + }; + Some(IgnoreSamplerRelease { button: *button, at: *pos, clicked }) + }).collect() + }) +} + /// Two non-sampler clicks replace egui's last two click times after a consumed pick. #[derive(Clone, Copy, Default)] struct IgnoreSamplerClicks { @@ -489,35 +534,34 @@ fn reset_ignore_sampler_clicks(ui: &Ui, id: egui::Id) { /// Reclassify only the two clicks whose raw history can still contain a consumed pick. /// Other widgets' clicks count too, as they do in egui; its pointer state stays untouched. -fn ignore_sampler_clicks(ui: &Ui, id: egui::Id, consumed: bool) { - let (clicked, primary, at, time) = ui.input(|i| { - // A hover move after the release is not the position egui put in its click history. - let at = i.events.iter().rev().find_map(|event| match event { - egui::Event::PointerButton { pos, button, pressed: false, .. } if i.pointer.button_clicked(*button) => Some(*pos), - _ => None, - }); - (i.pointer.any_click(), i.pointer.button_clicked(egui::PointerButton::Primary), at, i.time) - }); - ui.data_mut(|data| data.remove::(id.with("image-trace-click-count"))); - if !clicked { +fn ignore_sampler_clicks(ui: &Ui, id: egui::Id, consumed: bool, releases: &[IgnoreSamplerRelease]) { + ui.data_mut(|data| data.remove::(id.with("image-trace-click-count"))); + if !releases.iter().any(|release| release.clicked) { return; } if consumed { reset_ignore_sampler_clicks(ui, id); return; } - let Some(at) = at else { return }; - record_ignore_sampler_click(ui, id, at, time, primary); + let time = ui.input(|i| i.time); + for release in releases.iter().filter(|release| release.clicked) { + record_ignore_sampler_click(ui, id, release.at, time, release.button == egui::PointerButton::Primary); + } } fn record_ignore_sampler_click(ui: &Ui, id: egui::Id, at: Pos2, time: f64, primary: bool) { let (delay, distance) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist)); ui.data_mut(|data| { let history_id = id.with("image-trace-clicks"); - let Some(mut clicks) = data.remove_temp::(history_id) else { return }; + let Some(mut clicks) = data.remove_temp::(history_id) else { + if primary { + data.remove::(id.with("image-trace-click-count")); + } + return; + }; let double = clicks.last.is_some_and(|(last, pos)| time - last < delay && pos.distance_sq(at) < distance * distance); if primary { - data.insert_temp(id.with("image-trace-click-count"), if double { 2u8 } else { 1u8 }); + data.insert_temp(id.with("image-trace-click-count"), CanvasClick { count: if double { 2 } else { 1 }, at: Some(at) }); } clicks.last = Some((time, at)); clicks.remaining -= 1; @@ -527,21 +571,21 @@ fn record_ignore_sampler_click(ui: &Ui, id: egui::Id, at: Pos2, time: f64, prima }); } -fn primary_click_count(ui: &Ui, resp: &egui::Response) -> u8 { +fn primary_click(ui: &Ui, resp: &egui::Response) -> CanvasClick { if !resp.clicked_by(egui::PointerButton::Primary) { - return 0; + return CanvasClick::default(); } - ui.data(|data| data.get_temp::(resp.id.with("image-trace-click-count"))).unwrap_or_else(|| { - if resp.triple_clicked() { - 3 - } else if resp.double_clicked() { - 2 - } else { - 1 - } + ui.data(|data| data.get_temp::(resp.id.with("image-trace-click-count"))).unwrap_or_else(|| { + let count = if resp.triple_clicked() { 3 } else if resp.double_clicked() { 2 } else { 1 }; + let at = ui.data(|data| data.get_temp::(resp.id.with("canvas-qualified-primary-release"))); + CanvasClick { count, at } }) } +fn primary_click_count(ui: &Ui, resp: &egui::Response) -> u8 { + primary_click(ui, resp).count +} + /// Remove only the pointer sequence acquired by this sampler, never a view or tool drag. fn clear_ignore_sampler_gesture(ui: &Ui, id: egui::Id) { ui.data_mut(|data| { @@ -572,68 +616,36 @@ struct IgnoreSamplerPointer { } /// Attribute a fresh press after an owned release before egui's per-frame flags lose their order. -fn ignore_sampler_pointer_frame(ui: &Ui, id: egui::Id, cancelled: bool) -> IgnoreSamplerPointer { +fn ignore_sampler_pointer_frame(ui: &Ui, id: egui::Id, cancelled: bool, releases: &[IgnoreSamplerRelease]) -> IgnoreSamplerPointer { let owned = ignore_sampler_owns_primary(ui, id); if !owned && !cancelled { return IgnoreSamplerPointer::default(); } - let (distance, duration) = ui.ctx().options(|o| (o.input_options.max_click_dist, o.input_options.max_click_duration)); ui.input(|i| { let mut frame = IgnoreSamplerPointer { owned, ..Default::default() }; let mut first_press_owned = cancelled; - let mut press = None; - let mut moved = false; - let mut primary_pressed = false; + let mut releases = releases.iter(); for event in &i.events { - match event { - egui::Event::PointerMoved(at) => { - if let Some((_, origin)) = press { - moved |= Pos2::distance(origin, *at) > distance; + if let egui::Event::PointerButton { pos, button, pressed, .. } = event { + if *pressed { + if *button == egui::PointerButton::Primary { + frame.replaced |= frame.owned; + // An observed old Up ends that cancelled sequence; without it, + // a fresh invalid press keeps the existing cancellation gate. + frame.owned = first_press_owned && !frame.consumed_release; + first_press_owned = false; + frame.ordinary_pressed |= !frame.owned; } + } else { + let clicked = releases.next().is_some_and(|release| release.clicked); + ignore_sampler_release(&mut frame, *button, *pos, clicked); } - egui::Event::PointerButton { pos, button, pressed, .. } => { - if *pressed { - press = Some((*button, *pos)); - moved = false; - if *button == egui::PointerButton::Primary { - primary_pressed = true; - frame.replaced |= frame.owned; - // An observed old Up ends that cancelled sequence; without it, - // a fresh invalid press keeps the existing cancellation gate. - frame.owned = first_press_owned && !frame.consumed_release; - first_press_owned = false; - frame.ordinary_pressed |= !frame.owned; - } - } else { - // A fresh primary click needs its own Down, not an earlier owned click. - // Slop/origin are shared by buttons in egui; each press resets them, and - // a release clears its press time. In-frame presses have the same time. - let clicked = ignore_sampler_release_clicked(press, moved, primary_pressed, *button, duration); - ignore_sampler_release(&mut frame, *button, *pos, clicked); - if *button == egui::PointerButton::Primary { - primary_pressed = false; - } - press = None; - } - } - _ => {} } } frame }) } -fn ignore_sampler_release_clicked( - press: Option<(egui::PointerButton, Pos2)>, - moved: bool, - primary_pressed: bool, - button: egui::PointerButton, - duration: f64, -) -> bool { - let matched = if button == egui::PointerButton::Primary { primary_pressed } else { press.is_some_and(|(b, _)| b == button) }; - matched && !moved && (press.is_none() || !matches!(duration.partial_cmp(&0.0), Some(std::cmp::Ordering::Less))) -} - fn ignore_sampler_release(frame: &mut IgnoreSamplerPointer, button: egui::PointerButton, at: Pos2, clicked: bool) { if button == egui::PointerButton::Primary && frame.owned { frame.consumed_release = true; @@ -643,28 +655,34 @@ fn ignore_sampler_release(frame: &mut IgnoreSamplerPointer, button: egui::Pointe } } -fn ignore_sampler_frame_clicks(ui: &Ui, id: egui::Id, frame: &IgnoreSamplerPointer, consumed: bool) { +fn ignore_sampler_frame_clicks(ui: &Ui, id: egui::Id, frame: &IgnoreSamplerPointer, consumed: bool, releases: &[IgnoreSamplerRelease]) { if !frame.consumed_release || !frame.ordinary_pressed { - ignore_sampler_clicks(ui, id, consumed); + ignore_sampler_clicks(ui, id, consumed, releases); return; } // Consume the old sequence, then classify only subsequent ordinary releases. A new Down // still reaches the tool when the last release belongs to the consumed sequence. reset_ignore_sampler_clicks(ui, id); - ui.data_mut(|data| data.insert_temp(id.with("image-trace-click-count"), 0u8)); + ui.data_mut(|data| data.insert_temp(id.with("image-trace-click-count"), CanvasClick::default())); let time = ui.input(|i| i.time); for release in &frame.releases { let primary = release.button == egui::PointerButton::Primary; if release.clicked { record_ignore_sampler_click(ui, id, release.at, time, primary); - } else if primary { - ui.data_mut(|data| data.insert_temp(id.with("image-trace-click-count"), 0u8)); } } } fn begin_ignore_sampler_pointer(ui: &Ui, id: egui::Id, cancelled: bool) -> (bool, bool) { - let frame = ignore_sampler_pointer_frame(ui, id, cancelled); + let releases = canvas_pointer_releases(ui); + ui.data_mut(|data| { + let position_id = id.with("canvas-qualified-primary-release"); + data.remove::(position_id); + if let Some(release) = releases.iter().rev().find(|release| release.clicked && release.button == egui::PointerButton::Primary) { + data.insert_temp(position_id, release.at); + } + }); + let frame = ignore_sampler_pointer_frame(ui, id, cancelled, &releases); if frame.replaced { // This also replaces an abandoned sampler Down whose release was not observed. clear_ignore_sampler_gesture(ui, id); @@ -673,7 +691,7 @@ fn begin_ignore_sampler_pointer(ui: &Ui, id: egui::Id, cancelled: bool) -> (bool ui.data_mut(|data| data.insert_temp(ignore_sampler_primary_id(id), true)); } let consumed = frame.owned && ui.input(|i| i.pointer.primary_pressed() || i.pointer.primary_released() || i.pointer.primary_down()); - ignore_sampler_frame_clicks(ui, id, &frame, consumed); + ignore_sampler_frame_clicks(ui, id, &frame, consumed, &releases); (consumed, frame.ordinary_pressed) } diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index c72539aba9..512df6e9a9 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -425,11 +425,27 @@ fn pressed_with(app: &mut VectorcraftApp, index: Option, pos: Point, tool pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result>) { match r { Ok(reqs) => { + let mut sampler_return = None; for r in reqs { match r { - vectorcraft_engine::UiRequest::Dialog(kind, p) => crate::dialogs::open_tool_dialog(app, &kind, p), + vectorcraft_engine::UiRequest::Dialog(kind, p) => { + let back = if kind == "imageTraceIgnoreColor" && p["cancel"] == true { + app.ui.trace_ignore_sampler.as_ref().map(|sampler| sampler.back.clone()) + } else { + None + }; + crate::dialogs::open_tool_dialog(app, &kind, p); + // A matching callback must actually consume the active sampler. + sampler_return = back.filter(|_| app.ui.trace_ignore_sampler.is_none()); + } vectorcraft_engine::UiRequest::Panel(panel) => activate_panel(app, &panel), - vectorcraft_engine::UiRequest::SwitchTool(t) => app.select_tool(&t), + vectorcraft_engine::UiRequest::SwitchTool(t) => { + if sampler_return.take().is_some_and(|back| back == t) { + app.return_to_tool(&t); + } else { + app.select_tool(&t); + } + } vectorcraft_engine::UiRequest::Status(msg) => app.status(msg), vectorcraft_engine::UiRequest::Place(p) => crate::place::place_from_cursor(app, &p), // In the document the press was made in, which may no longer be the active one. diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 748ad07654..ef8e596c4e 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -186,17 +186,18 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo .unwrap_or(m.shift); select_named_artboard(app, i, shift || release_shift); } + let click = super::primary_click(ui, resp); if !super::ignore_sampler_owns_primary(ui, resp.id) - && super::primary_click_count(ui, resp) == 2 + && click.count == 2 && !f.modal - && let Some(p) = release_pos(ui, egui::PointerButton::Primary, true).or(at) + && let Some(p) = click.at.or(at) { double_click(app, ui, &f, p); } if !super::ignore_sampler_owns_primary(ui, resp.id) - && super::primary_click_count(ui, resp) == 3 + && click.count == 3 && !f.modal - && let Some(p) = release_pos(ui, egui::PointerButton::Primary, true).or(at) + && let Some(p) = click.at.or(at) { triple_click(app, ui, &f, p); } @@ -337,7 +338,7 @@ fn begin_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { Drag::RotateView { start_angle: (p.y - c.y).atan2(p.x - c.x) as f64, start_rot: v.rotation, snaps: !space } } else { // Cmd with another tool drags with the selection tool used last (the session lends it). - let ev = PointerEvent { + let mut ev = PointerEvent { kind: PointerKind::Down, pos: xf.to_doc(p), mods: mods(m, space), @@ -349,6 +350,16 @@ fn begin_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { // selection press keeps the ordinary tool path. let sampler = app.ui.trace_ignore_sampler.is_some() && tool == "eyedropper" && app.session.lent_tool_id(&ev.mods).is_none(); if sampler { + // A later hover move is not the source pixel that was pressed. + let pressed = ui.input(|i| { + i.events.iter().find_map(|event| match event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => Some(*pos), + _ => None, + }) + }); + if let Some(pressed) = pressed { + ev.pos = xf.to_doc(pressed); + } ui.data_mut(|data| data.insert_temp(super::ignore_sampler_primary_id(resp.id), true)); } dispatch(app, &ev, view); diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index af2ec39921..c6d5922661 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -1663,7 +1663,8 @@ fn lookup_fixture() -> (VectorcraftApp, std::collections::HashMap<&'static str, /// The panel's lookup gives what putting the whole selection in paint order gave, field for field, /// for every kind of selection: images in either selection order, an Image Trace object with its /// own image, a clipping group named Image Trace, nested groups, hidden and locked images, two -/// layers, repeated ids, ids the document lacks, and nothing selected. The result kept for a +/// layers, repeated ids, ids the document lacks, and nothing selected. Selected ancestors with +/// their descendants have separate canonical-root expectations below. The result kept for a /// revision follows each change of the selection, an edit, Undo and a switch of document. #[test] fn the_target_lookup_matches_sorting_the_whole_selection() { @@ -1679,10 +1680,8 @@ fn the_target_lookup_matches_sorting_the_whole_selection() { &["trace image", "trace"], &["rect", "trace image"], &["clip"], - &["clip", "clipped"], &["rect", "clipped"], &["outer"], - &["outer", "deep"], &["inner", "rect"], &["deep", "back"], &["hidden", "locked"], @@ -1738,6 +1737,37 @@ fn the_target_lookup_matches_sorting_the_whole_selection() { assert_eq!(target(&none, &ctx), Target::default()); } +/// Trace only accepts selected roots: a selected parent blocks its image descendant. +/// Missing implicit-selection ids are dropped, while explicit ids are validated. +#[test] +fn the_target_lookup_obeys_canonical_roots_and_explicit_id_validation() { + let (mut app, ids) = lookup_fixture(); + let ctx = egui::Context::default(); + for (parent, child) in [("clip", "clipped"), ("outer", "deep")] { + select_as_is(&mut app, &[ids[parent], ids[child]]); + let uid = app.session.active().unwrap().uid; + let expected = Target { object: Some((uid, ids[parent])), ..Default::default() }; + assert_eq!(find_target(&app), expected, "the selected {parent} supplies metadata, not its pruned image"); + assert_eq!(target(&app, &ctx), expected); + assert_eq!(target(&app, &ctx), expected, "the canonical result is also cached"); + assert!(vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null).is_err()); + let document = app.session.active().unwrap().doc.clone(); + assert!(app.run("imageTrace.make", json!({})).is_err(), "Trace rejects that non-image root"); + assert_eq!(app.session.active().unwrap().doc, document); + select_as_is(&mut app, &[ids[child]]); + assert_eq!(vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null).unwrap(), ids[child], "the image alone remains eligible"); + } + let stale = NodeId(u64::MAX); + select_as_is(&mut app, &[stale, ids["front"]]); + assert_eq!(target(&app, &ctx).object.map(|(_, id)| id), Some(ids["front"]), "implicit stale entries do not hide a valid image"); + assert_eq!(vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null).unwrap(), ids["front"]); + let explicit = json!({"ids": [stale.0, ids["front"].0]}); + let document = app.session.active().unwrap().doc.clone(); + assert!(vectorcraft_engine::cmd::image_trace_target(&app.session, &explicit).is_err(), "explicit missing ids are invalid"); + assert!(app.run("imageTrace.make", explicit).is_err()); + assert_eq!(app.session.active().unwrap().doc, document); +} + /// The panel and its menu look the object Trace acts on up once for each revision of the document, /// however many frames show it, and again once the revision moves. #[test] diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs index 5de21672f7..64d3efcff2 100644 --- a/crates/ui-egui/tests/image_trace_ignore_sampler.rs +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -1318,3 +1318,112 @@ fn review_596866_coalesced_fresh_release_qualifies_its_own_click() { review_596866_coalesced_fresh_suffix(false); review_596866_coalesced_fresh_suffix(true); } + +fn review_597048_key(pressed: bool) -> Event { + Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() } +} + +#[test] +fn review_597048_escape_returns_to_a_hidden_grid_without_fresh_activation() { + let (mut control, _) = review_596866_hidden_grid_fixture(); + control.select_tool("perspectiveGrid"); + assert!(review_596866_grid_visible(&control), "CONTROL: explicit fresh selection still shows the grid"); + let (mut app, ctx) = review_596866_hidden_grid_fixture(); + let expected = review_gesture_state(&app); + click_control(&mut app, &ctx, SAMPLE_TIP); + assert_eq!(app.session.tool_id(), "eyedropper"); + frame(&mut app, &ctx, vec![review_597048_key(true)]).textures_delta.clear(); + frame(&mut app, &ctx, vec![review_597048_key(false)]).textures_delta.clear(); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert_eq!(app.session.tool_id(), "perspectiveGrid"); + assert!(!review_596866_grid_visible(&app), "Escape returns without revealing the grid"); + assert_eq!(review_gesture_state(&app), expected, "cancellation changes no document, revision, history, selection or paint"); +} + +fn review_597048_down_pixel(later_move: bool) { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let source = review_596866_source_image(&app, selected(&app).id); + let pressed = review_gesture_screen(&app, &ctx, source_point(&app, 0.25)); + let hover = review_gesture_screen(&app, &ctx, source_point(&app, 0.75)); + assert_ne!(pressed, hover); + let expected = review_gesture_state(&app); + click_control(&mut app, &ctx, SAMPLE_TIP); + let mut events = vec![Event::PointerMoved(pressed), review_596866_button(pressed, true)]; + if later_move { + events.push(Event::PointerMoved(hover)); + } + frame(&mut app, &ctx, events).textures_delta.clear(); + assert_eq!(ctx.input(|i| i.pointer.interact_pos()), Some(if later_move { hover } else { pressed })); + assert_eq!(app.session.tool_id(), "selection"); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert_eq!(review_gesture_state(&app), expected, "Preview off stores a panel draft only"); + frame(&mut app, &ctx, vec![review_596866_button(if later_move { hover } else { pressed }, false)]).textures_delta.clear(); + click_control(&mut app, &ctx, "Trace"); + assert_eq!(review_596866_ignore_color(&app, source), "#255395", "the sampled pixel belongs to Down, later_move={later_move}"); +} + +#[test] +fn review_597048_sampler_uses_down_pixel_before_a_later_move() { + review_597048_down_pixel(false); + review_597048_down_pixel(true); +} + +fn review_597048_coalesced_pair(sampler_prefix: bool) { + let (mut app, ctx, point, group) = review_gesture_group_fixture(); + let at = review_gesture_screen(&app, &ctx, point); + if sampler_prefix { + click_control(&mut app, &ctx, SAMPLE_TIP); + } + app.run("select.none", json!({})).unwrap(); + let (start, step) = review_gesture_times(&ctx); + if sampler_prefix { + let expected = review_gesture_state(&app); + review_gesture_press(&mut app, &ctx, at, start); + review_gesture_release(&mut app, &ctx, at, start + step); + assert_eq!(review_gesture_state(&app), expected, "the stale prefix was consumed in the earlier frame"); + } + frame_at(&mut app, &ctx, start + 3.0 * step, vec![ + Event::PointerMoved(at), review_596866_button(at, true), review_596866_button(at, false), + review_596866_button(at, true), review_596866_button(at, false), + ]); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(ctx.input(|i| i.pointer.button_triple_clicked(PointerButton::Primary)), sampler_prefix); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "two ordinary clicks isolate after an earlier-frame prefix"); + app.run("object.exitIsolation", json!({"all": true})).unwrap(); + review_gesture_press(&mut app, &ctx, at, start + 5.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 6.0 * step); + assert!(ctx.input(|i| i.pointer.button_triple_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().isolation, None, "the next ordinary Triple must not inherit a corrected Double"); +} + +#[test] +fn review_597048_two_ordinary_clicks_in_one_frame_survive_sampler_correction() { + review_597048_coalesced_pair(false); + review_597048_coalesced_pair(true); +} + +#[test] +fn review_597048_a_later_drag_release_does_not_replace_a_qualified_double_click() { + let (mut control, control_ctx, point, group) = review_gesture_group_fixture(); + let at = review_gesture_screen(&control, &control_ctx, point); + review_gesture_ordinary_pair(&mut control, &control_ctx, at, at, group); + let (mut app, ctx, point, group) = review_gesture_group_fixture(); + app.run("select.none", json!({})).unwrap(); + let at = review_gesture_screen(&app, &ctx, point); + let blank = review_gesture_screen(&app, &ctx, Point::new(340.0, 250.0)); + let distance = ctx.options(|o| o.input_options.max_click_dist); + let away = blank + vec2(distance + 8.0, 0.0); + assert!(app.canvas_rect.unwrap().contains(away) && away.distance(blank) > distance); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + review_gesture_release(&mut app, &ctx, at, start + step); + review_gesture_press(&mut app, &ctx, at, start + 3.0 * step); + frame_at(&mut app, &ctx, start + 4.0 * step, vec![ + review_596866_button(at, false), Event::PointerMoved(blank), review_596866_button(blank, true), + Event::PointerMoved(away), review_596866_button(away, false), + ]); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert!(!ctx.input(|i| i.pointer.button_triple_clicked(PointerButton::Primary)), "the out-of-slop drag is not a third 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"); +} From 18793ed27db0dcea221350d2f05649972972e9c9 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 19 Nov 2026 03:45:18 -0800 Subject: [PATCH 33/34] Fix redundant color-management closure borrow --- crates/engine/src/cmd/colormgmt.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 0ac4f8c3b0..bfaece3d77 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -1003,7 +1003,7 @@ impl PasteProfile { if o.keys().any(|k| k != "rgb" && k != "cmyk") { return Err(refuse()); } - let model = |m: &str| o.get(m).map(&one).transpose(); + let model = |m: &str| o.get(m).map(one).transpose(); Ok(Some(PasteChoice { rgb: model("rgb")?, cmyk: model("cmyk")? })) } Some(v) => { From 24da5d29360ae2028f9579b43281072718098728 Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Thu, 19 Nov 2026 15:26:45 +0500 Subject: [PATCH 34/34] Tests: script_io makes its temp folders by their real paths On macOS the temp folder /var/... is a link to /private/var/.... Kept script file grants hold real paths, and ScriptScope refuses a path by its names alone when they don't start with a granted path, so the 11 grant tests that name their files under the temp folder were refused and asked again. folder() now returns the real path of the folder it makes. ui_inspect_script_report_leaves_out_files_outside_the_read_root failed on macOS for the same reason: the report names the included file by its real path, and the test compared it with the /var spelling. It now compares with the real path. No change outside the tests. Fixes #8693 --- crates/engine/src/tests/script_io.rs | 6 ++++-- crates/ui-egui/src/tests/automation.rs | 4 +++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 7c8c167527..7653dc083d 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -12,12 +12,14 @@ use crate::*; const DENIED: &str = "Script file access denied"; -/// A fresh folder for test `name`, with a `main` folder inside it for the script. +/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real +/// path: kept grants hold real paths, and a path named through a link (macOS's `/var` is +/// `/private/var`) is refused by its names alone. fn folder(name: &str) -> PathBuf { let base = std::env::temp_dir().join(format!("vc-script-io-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&base); std::fs::create_dir_all(base.join("main")).unwrap(); - base + std::fs::canonicalize(&base).unwrap() } fn write(path: &Path, bytes: &[u8]) { diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index 7a904e4646..00505b84cc 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -1310,7 +1310,9 @@ fn ui_inspect_script_report_leaves_out_files_outside_the_read_root() { std::fs::write(base.join("outside/bad.jsxinc"), "\nthrow new Error('stopped here');\n").unwrap(); finish(&mut app, json!({"path": s(base.join("outside/run.jsx"))})); let person = crate::control::inspect(&app, &ctx); - assert_eq!(person["scriptReport"]["file"], json!(s(base.join("outside/bad.jsxinc"))), "{person}"); + // The report names the file by its real path (on macOS the temp folder is reached through a link). + let bad = std::fs::canonicalize(base.join("outside/bad.jsxinc")).unwrap(); + assert_eq!(person["scriptReport"]["file"], json!(s(bad)), "{person}"); let r = request(&mut app, &tx, "ui.inspect", json!({})); assert_eq!(r["result"]["scriptReport"]["file"], "bad.jsxinc", "{r}"); assert!(r["result"]["scriptReport"]["console"].to_string().contains("bad.jsxinc:2:"), "{r}");