From 007356257f27b46c7ae546955e335903a56fa233 Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Mon, 16 Nov 2026 22:19:03 +0100 Subject: [PATCH 1/9] #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 2/9] #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 2d156c1bbe96ed59ec1d593d95aeeaf567c6120e Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Tue, 17 Nov 2026 20:15:20 +0100 Subject: [PATCH 3/9] #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 4/9] #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 411638852c4fd5c76c86509bca95555ddf0a6dbc Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Thu, 19 Nov 2026 12:24:58 +0500 Subject: [PATCH 5/9] =?UTF-8?q?Canvas=20context=20menu:=20Simplify?= =?UTF-8?q?=E2=80=A6=20next=20to=20Smooth=E2=80=A6=20(#8344)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A right-click on a path, a group of paths or a compound path lists Object › Path › Simplify… between Average… and Smooth…, in the Path menu's order. It runs through invoke as the menu item does, so it opens the Simplify slider at the Auto-Simplify level, or the Simplify dialog on its kept settings. prune leaves it out unless object.path.simplify can run. --- crates/ui-egui/src/menus/context.rs | 10 ++-- crates/ui-egui/src/tests/contextmenu.rs | 62 ++++++++++++++++++++++--- docs/ui-parity.md | 7 +-- 3 files changed, 66 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index 7a4566ae27..f99bbfef2e 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -82,10 +82,12 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { if !st.selection.anchors.is_empty() { v.extend([c("Remove Anchor Points", "path.removeAnchors"), c("Cut Path at Selected Anchor Points", "path.cutAtAnchors")]); } - // Object › Path › Smooth…, which opens the Smooth slider (`invoke`). `prune` leaves it out - // unless object.path.smooth can run: the selection holds a path, in a group or a compound - // path too. - v.push(c("Smooth…", "object.path.smooth")); + // Object › Path › Simplify… and Smooth…, in that menu's order (#8344). Each opens what the + // menu item opens (`invoke`): the Simplify slider, or the Simplify dialog when its "Open + // this dialog with these settings next time" was ticked, and the Smooth slider. `prune` + // leaves each out unless its command can run: the selection holds a path, in a group or a + // compound path too. + v.extend([c("Simplify…", "object.path.simplify"), c("Smooth…", "object.path.smooth")]); if several { v.push(c("Make Clipping Mask", "object.clippingMask.make")); } diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index 655c2efc4f..781924d1a1 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -354,10 +354,16 @@ fn isolation_context_item_skips_objects_outside_the_edited_symbol() { /// A closed path of 60 jagged anchors around (150, 150), filled so that a right-click inside it /// hits it, with nothing selected. fn jagged(app: &mut VectorcraftApp) -> NodeId { + ring(app, 4.0) +} + +/// A closed path of 60 anchors around (150, 150), every other one `wobble` pt further out, filled +/// so that a right-click inside it hits it, with nothing selected. +fn ring(app: &mut VectorcraftApp, wobble: f64) -> NodeId { let anchors: Vec<_> = (0..60) .map(|i| { let a = f64::from(i) * std::f64::consts::TAU / 60.0; - let r = 60.0 + f64::from(i % 2) * 4.0; + let r = 60.0 + f64::from(i % 2) * wobble; json!({"x": 150.0 + r * a.cos(), "y": 150.0 + r * a.sin()}) }) .collect(); @@ -405,15 +411,59 @@ fn right_click_on_a_path_opens_the_smooth_slider() { assert!(anchor_total(&app) < before, "the path was smoothed: {} anchor points from {before}", anchor_total(&app)); } -/// Smooth… is listed while the selection holds a path: a path, a group of paths, a compound path, -/// a path with type, and anchors selected with Direct Selection (whose Remove Anchor Points -/// stays). It is left out with nothing, only type or a group of type selected. +/// A right-click on a path lists Object › Path › Simplify… between Average… and Smooth…, as the +/// Path menu orders them (#8344). Simplify… opens the Simplify slider at Auto-Simplify's level, as +/// the menu item does, and adds no undo step while it is open; OK keeps the simplified path as one +/// undo step. After the Simplify dialog was confirmed with "Open this dialog with these settings +/// next time" ticked, Simplify… opens that dialog on its settings, as the menu item does. #[test] -fn smooth_follows_the_selections_paths() { +fn right_click_on_a_path_opens_simplify_as_the_menu_item_does() { + let mut app = app(); + // A circle drawn with 60 anchors, which Auto-Simplify's tolerance refits with far fewer. + let id = ring(&mut app, 0.0); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let p = screen(&app, 150.0, 150.0); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + assert_eq!(app.session.active().unwrap().selection.objects, [id], "the path right-clicked is selected"); + let y = |label| at(&texts, label).y; + assert!(y("Average…") < y("Simplify…") && y("Simplify…") < y("Smooth…"), "{texts:?}"); + let level = crate::dialogs::simplify_slider::fields(&app)["level"].as_f64().unwrap(); + let (undo, before) = (app.session.active().unwrap().history.undo.len(), anchor_total(&app)); + let after = click(&mut app, &ctx, at(&texts, "Simplify…"), PointerButton::Primary); + assert!(!has(&after, "Arrange"), "choosing Simplify… closes the menu"); + let open = app.ui.dialog.as_ref().map(|d| (d.kind.clone(), d.f64("level", -1.0))); + assert_eq!(open, Some((crate::dialogs::simplify_slider::KIND.to_string(), level)), "the slider at Auto-Simplify's level"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "no undo step while the slider is open"); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none() && !app.session.in_interaction()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "OK keeps the result as one undo step"); + assert!(anchor_total(&app) < before, "the path was simplified: {} anchor points from {before}", anchor_total(&app)); + + // The settings the Simplify dialog keeps for next time: Simplify… opens the dialog on them. + app.ui.simplify = json!({"tolerance": 0.5, "cornerAngle": 150, "straightLines": true, "retain": true}); + frame(&mut app, &ctx, vec![]); + let texts = click(&mut app, &ctx, p, PointerButton::Secondary); + click(&mut app, &ctx, at(&texts, "Simplify…"), PointerButton::Primary); + let d = app.ui.dialog.clone().expect("the Simplify dialog"); + assert_eq!((d.kind.as_str(), d.f64("tolerance", 0.0), d.bool("straightLines"), d.bool("retain")), ("simplify", 0.5, true, true)); +} + +/// Simplify… and Smooth… are listed while the selection holds a path: a path, a group of paths, a +/// compound path, a path with type, and anchors selected with Direct Selection (whose Remove +/// Anchor Points stays). They are left out with nothing, only type or a group of type selected. +#[test] +fn simplify_and_smooth_follow_the_selections_paths() { let mut app = app(); let (a, b) = (rect(&mut app, 0.0, 0.0), rect(&mut app, 150.0, 0.0)); let t = NodeId(app.run("text.create", json!({"x": 10, "y": 250, "text": "Type"})).unwrap()["id"].as_u64().unwrap()); - let smooth = |app: &VectorcraftApp| labels(&menus::context_items(app)).contains(&"Smooth…"); + // Both or neither, never one without the other. + let smooth = |app: &VectorcraftApp| { + let shown = labels(&menus::context_items(app)); + let (simplify, smooth) = (shown.contains(&"Simplify…"), shown.contains(&"Smooth…")); + assert_eq!(simplify, smooth, "Simplify… and Smooth… follow the same rule: {shown:?}"); + smooth + }; app.run("select.none", json!({})).unwrap(); assert!(!smooth(&app), "nothing selected"); app.run("select.set", json!({"ids": [t.0]})).unwrap(); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 64e6be0b94..ef31c1f2d9 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-18 · **Change:** minor (Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously minor: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -213,7 +213,7 @@ tools, never checked side by side) isn't captured row by row. | Average and Join in one step, with a corner or smooth choice for the joined anchor | done | Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, "Create corner or smooth join" in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): two open path ends meet at their midpoint and join, a corner or smooth point as the dialog's Points choice asks (Corner first, then the last choice), in one undo step | | Smooth tool smooths only the stretch of path under the drag | done | #1512 | | Drawing modes apply to pastes: Draw Inside takes Paste, Paste in Place and Paste on All Artboards inside the object; Draw Behind puts Paste in Place and Paste on All Artboards behind the selection; Shift+D cycles past Draw Behind with any selection ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | done | #3705; `pasting_in_draw_inside_puts_the_copies_inside_the_object`, `paste_in_place_in_draw_behind_goes_behind_the_selection`, `shift_d_goes_past_draw_behind_whatever_is_selected` | -| Simplify (slider, auto, corner angle threshold), of a whole path or of the part of it selected with Direct Selection ([manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html)) | done | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, opening at the Auto-Simplify level for the selection with that result previewed, and the dialog's option to open it directly with its last settings. With anchors or segments direct-selected, the slider, Auto-Simplify and the dialog refit only each run of selected segments between its end anchors, a closed path's run across its start point included; the rest of the path stays exactly as it was (`tests/simplify_part.rs`, `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`) | +| Simplify (slider, auto, corner angle threshold), of a whole path or of the part of it selected with Direct Selection ([manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html)) | done | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, opening at the Auto-Simplify level for the selection with that result previewed, and the dialog's option to open it directly with its last settings. The canvas context menu's Simplify…, listed with Smooth… while the selection holds a path, opens the same slider or dialog (#8344, `right_click_on_a_path_opens_simplify_as_the_menu_item_does`). With anchors or segments direct-selected, the slider, Auto-Simplify and the dialog refit only each run of selected segments between its end anchors, a closed path's run across its start point included; the rest of the path stays exactly as it was (`tests/simplify_part.rs`, `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`) | | Smooth (Object › Path › Smooth…: slider from minimum to maximum smoothing, Auto-Smooth) ([smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html)) | done | #4115: the slider under the selection previews `object.path.smooth {level}`, Auto-Smooth picks level 50 and takes a shaky line to one smooth curve, direct-selected anchors smooth only their section, Enter or a click outside keeps one undo step and Escape restores; the smoothing rule beyond the two ends is VectorCraft's own (`tests/smooth_path.rs`, `smooth_slider_previews_auto_smooth_and_keeps_the_result`) | | Draw Inside in isolation mode: art drawn or pasted inside the isolated object takes isolation mode into its clip group, clickable and undimmed ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html), [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | done | #3705; `drawing_inside_an_isolated_object_keeps_the_new_art_in_isolation_mode` | | Draw Inside marks the object it draws into: a dotted open rectangle round its corners, in its layer's colour, while the mode lasts, selected or not | done | #4319, `canvas::tests::draw_inside_marks_the_corners_of_its_object` ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) | @@ -482,7 +482,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Pathfinder panel › Pathfinder Options…: Precision, Remove Redundant Points, Divide and Outline Will Remove Unpainted Artwork | done | #3426; `object.pathfinder.options`, kept in the preferences; defaults (0.01 pt, both off) keep the earlier results; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) | | Cmd/Ctrl+4 repeats the last successful Shape Mode or Pathfinder operation on the selection | done | Panel operations, direct `object.pathfinder.*` commands and `command.batch` steps (Actions playback) set history; `action.batch`, Trap, compound-shape edits and live effects do not. Repeat uses current Pathfinder Options; [key spec](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), [menu spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html) | | Pathfinder panel: compound shapes (Make, Release and Expand Compound Shape in the panel menu, Alt-click a Shape Mode, a Shape Mode for selected members, the Expand button) | partial | #4522; `object.compoundShape.make`/`setMode`/`release`/`expand`; members stay editable, the area draws, exports and saves; the button of the members' shared mode is lit, and members in different modes put a question mark on each Shape Mode button; blends, envelopes and warped objects are members as they draw; [spec](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html); missing: hit-testing by the area | -| Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: other panels have none | +| Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. Right-clicking a path offers Object › Path › Simplify… and Smooth…, each opening what its menu item opens (#8344). Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: other panels have none | | Layers panel row context menu | done | Right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export; right-clicking a ruler guide row shows Hide/Show, Lock/Unlock, Release Guides, Delete and Locate Object; right-clicking a blend spine row shows Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object (#8592). | | Swatches item context menu (G12) | done | List and thumbnail items offer Swatch Options…, Duplicate Swatch and Delete Swatch for the clicked item. Right-click selects without applying paint; reserved/missing items disable actions. All 39 Swatches tests pass, including all five views and Undo; the regression fails with the menu hooks removed. Rendered headless menus inspected. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. | | SVG Interactivity panel: JavaScript for each object's events and the document's linked JavaScript files, written to SVG and read back as text | done | `svgInteractivity.*`, `ui.javascriptFilesDialog` | @@ -594,6 +594,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | Canvas context menu: a right-click on a path, a group of paths or a compound path offers Simplify… between Average… and Smooth…, in the Path menu's order, opening the Simplify slider at the Auto-Simplify level, or the Simplify dialog on its kept settings, as Object › Path › Simplify… does (#8344). Scores and estimates unchanged. | | 2026-11-18 | minor | Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538). Scores and estimates unchanged. | | 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | | 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. | From 42766fea241a2488b6b3764fac52b53e46f8a609 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 22:40:54 -0800 Subject: [PATCH 6/9] Live Paint: a fill given to a whole group paints its faces and a stroke paints its edges With a tool other than the Live Paint Bucket, a fill given to a whole selected Live Paint group paints its faces only and a stroke paints its edges only, instead of applying to the group as a whole. The hidden source paths keep their paint. - paint.setFill, paint.setStroke, paint.none, paint.lastColor, paint.lastGradient, paint.editGradient, paint.setGradientGeom, the paint.freeform point and line edits, paint.invert and paint.complement go to the faces for a fill and the edges for a stroke, also for a group given in ids or inside a selected group. - stroke.set, stroke.weightUp, stroke.weightDown and stroke.setAdvanced change the edges. - The Fill proxy shows the faces' fill, and the Stroke proxy, the Stroke panel and the Control bar show the edges' stroke. When the first selected object is a Live Paint group with no faces (or no edges), they show the next selected object's paint. - paint.swap gives the faces the stroke the edges share and gives the edges the fill the faces share, with a gradient fitted to each face or edge. A group whose faces' fills or edges' strokes differ, or that has no face or no edge, is left as it is. - paint.default leaves the faces with no fill and gives the edges a 0.5 pt black stroke; with only Live Paint groups selected, the settings for new art take the same. Docs: docs/mcp.md (Live Paint), docs/target-app-parity.md (Live Paint evidence), params text of the changed commands. --- crates/engine/src/cmd/appearance.rs | 22 ++ crates/engine/src/cmd/freeform.rs | 15 +- crates/engine/src/cmd/gradient.rs | 21 +- crates/engine/src/cmd/newart.rs | 8 +- crates/engine/src/cmd/paint.rs | 252 +++++++++++++++--- crates/engine/src/cmd/paint/tests.rs | 19 +- crates/engine/src/cmd/stroke.rs | 68 +++-- crates/engine/src/tests/build.rs | 385 +++++++++++++++++++++++++++ docs/mcp.md | 13 + docs/target-app-parity.md | 1 + 10 files changed, 724 insertions(+), 80 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 1b14e25391..6d2c7fd18f 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -278,6 +278,28 @@ impl ItemTarget { } } + /// [`ItemTarget::targets`] of a fill (`fill`) or a stroke edit: on the topmost fill or stroke, a + /// Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit + /// ([`super::paint::live_paint_parts_skipped`]). + pub(crate) fn targets_for(self, s: &Session, p: &Value, fill: bool) -> Result> { + Ok(self.targets_and_skipped(s, p, fill)?.0) + } + + /// [`ItemTarget::targets_for`], and whether it left out any object inside a Live Paint group: a + /// group with no part of the edited kind was still given or selected, so the edit does not go + /// to new art. + pub(crate) fn targets_and_skipped(self, s: &Session, p: &Value, fill: bool) -> Result<(Vec, bool)> { + let mut ids = self.targets(s, p)?; + let mut skipped_any = false; + if self == ItemTarget::Top { + let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill); + let before = ids.len(); + ids.retain(|id| !skipped.contains(id)); + skipped_any = ids.len() != before; + } + Ok((ids, skipped_any)) + } + /// The target of a fill (`fill`) or stroke edit: the panel's active item stands only for edits /// of its own kind, so a fill row leaves stroke edits on the topmost stroke of the painted /// leaves (as without an active item) and vice versa. Explicit items are kept (and checked). diff --git a/crates/engine/src/cmd/freeform.rs b/crates/engine/src/cmd/freeform.rs index 71a5e36ccf..b238dd865a 100644 --- a/crates/engine/src/cmd/freeform.rs +++ b/crates/engine/src/cmd/freeform.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Add Freeform Point", [], None, - "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}", + "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}", has_doc, add_point ), @@ -28,7 +28,7 @@ pub fn specs() -> Vec { "Edit Freeform Point", [], None, - "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}", + "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}", has_doc, set_point ), @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Delete Freeform Point", [], None, - "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}", + "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}", has_doc, delete_point ), @@ -46,7 +46,7 @@ pub fn specs() -> Vec { "Add Freeform Line", [], None, - "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}", + "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}", has_doc, add_line ), @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Split Freeform Line", [], None, - "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}", + "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}", has_doc, split_line ), @@ -182,8 +182,9 @@ fn edit(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freefor let item = item_target(s, p, cmd)?; let stroke = edits_stroke(s, p, item, !s.fill_active, cmd)?; let item = item.of_kind(s, !stroke); - // The art of a graph design in a series keeps the design's gradient. - let ids = super::appearance::without_design_art(&s.doc()?.doc, item.targets(s, p)?, cmd)?; + // The art of a graph design in a series keeps the design's gradient; a Live Paint group's fill is on its faces and its + // stroke on its edges. + let ids = super::appearance::without_design_art(&s.doc()?.doc, item.targets_for(s, p, !stroke)?, cmd)?; if ids.is_empty() { return Err(bad(cmd, "select an object with a freeform gradient")); } diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 53e0f5456f..746749235b 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)", has_doc, edit_gradient ), @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Gradient Vector", [], None, - "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without the placement this command sets, fitted to each label", + "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without the placement this command sets, fitted to each label; without item, a Live Paint group's faces take a fill edit and its edges take a stroke edit", has_doc, set_gradient_geom ), @@ -92,6 +92,9 @@ fn select_stop(s: &mut Session, p: &Value) -> Result { pub(crate) struct StopOwner { doc: Option, object: Option, + /// The object whose paint the active proxy shows: a Live Paint group without faces (or edges) + /// first in the selection shows the next object's. + source: Option, part: bool, fill: bool, item: Option, @@ -104,6 +107,7 @@ impl StopOwner { Self { doc: s.active, object: st.and_then(|d| d.selection.objects.first().copied()), + source: s.proxy_source(!s.fill_active).map(|(n, _)| n.id), part: st.is_some_and(|d| d.selection.symbol_part.is_some()), fill: s.fill_active, item: s.appearance_item(), @@ -539,10 +543,10 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { check_switches(p, &["reverse", "dither"], C)?; check_numbers(p, &["angle"], C)?; let item = item.of_kind(s, !stroke); - let ids = item.targets(s, p)?; - // Objects were given or selected, even when all of them are graph design art left out below: the stroke mode is then - // not one for new art. - let selected = !ids.is_empty(); + let (ids, skipped) = item.targets_and_skipped(s, p, !stroke)?; + // Objects were given or selected, even when all of them are graph design art left out below, or Live Paint group parts + // of the other kind left out above: the stroke mode is then not one for new art. + let selected = !ids.is_empty() || skipped; let ids = super::appearance::drop_design_art_rows(s, ids, item, !stroke, C)?; // How the gradient lies on a stroke (the panel's Stroke buttons). let mode = match str_param(p, "strokeMode") { @@ -778,7 +782,10 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result { let item = item.of_kind(s, !stroke); let targets = match item { ItemTarget::Top => { - leaf_targets(s, &super::given_objects(s, p, C)?.map_or_else(|| selected_roots(s), |ids| Ok(outermost(&s.doc()?.doc, ids)))?)? + let roots = super::given_objects(s, p, C)?.map_or_else(|| selected_roots(s), |ids| Ok(outermost(&s.doc()?.doc, ids)))?; + // A Live Paint group's fill gradient is on its faces and its stroke gradient on its edges. + let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &roots, !stroke); + leaf_targets(s, &roots)?.into_iter().filter(|id| !skipped.contains(id)).collect() } _ => item.targets(s, p)?, }; diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index 23b74f2fa6..d9d0905140 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -228,9 +228,11 @@ impl Session { if !self.prefs.new_art_basic { return; } - let has_paint = self - .proxy_source(false) - .is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty() || n.extras().colorize.is_some()); + // A Live Paint group with edges and no faces shows only a stroke. + let has_paint = [false, true].into_iter().any(|stroke| { + self.proxy_source(stroke) + .is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty() || n.extras().colorize.is_some()) + }); if !has_paint { return; } diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 6115e18b81..eb4b1e7443 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -4,7 +4,8 @@ use std::borrow::Cow; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint}; -use vectorcraft_doc::{Appearance, CharStyle, Document, GraySource, Node, NodeId, NodeKind}; +use vectorcraft_doc::appearance::{FillLayer, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, GraySource, Node, NodeId, NodeKind}; use super::appearance::{ItemTarget, edit_items, edit_items_then, item_target, row_targets}; use super::gradient::{item_paint_bounds, place_paint, place_run_paint, run_paint_mut, run_stroke_weight, unplaced}; @@ -25,7 +26,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), 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), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the color the bucket paints with) and the selection keeps its paint → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), 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), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the color the bucket paints with) and the selection keeps its paint → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -34,7 +35,7 @@ pub fn specs() -> Vec { "Stroke", [], None, - "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill", + "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill", has_doc, |s, p| { set_paint(s, p, false) } ), @@ -43,7 +44,7 @@ pub fn specs() -> Vec { "Swap Fill and Stroke", [], Some("Shift+X"), - "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change", + "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ, or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change", has_doc, swap ), @@ -52,7 +53,7 @@ pub fn specs() -> Vec { "Default Fill and Stroke", [], Some("D"), - "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change", + "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change", has_doc, default_paint ), @@ -100,7 +101,7 @@ pub fn proxy_specs() -> Vec { "Invert", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert) ), @@ -109,7 +110,7 @@ pub fn proxy_specs() -> Vec { "Complement", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), the default; no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), the default; no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model()) ), @@ -158,7 +159,7 @@ pub fn proxy_specs() -> Vec { "Fill and Stroke", [], None, - "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}", + "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}", always, proxies ), @@ -182,10 +183,11 @@ impl Session { /// The fill and stroke the Fill/Stroke proxies show: the Appearance panel's active item (in the /// first selected object's own stack) for the proxy of its kind, else the first selected - /// object's (a group's first painted object's; type: its first run's), else the defaults for - /// new art. When the object whose fill the proxy shows is a gradient mesh with points picked - /// ([`Session::fill_mesh_points`]), the fill is its first picked point's color, which a solid - /// fill color changes. + /// object's (a group's first painted object's; a Live Paint group's first face's fill and first + /// edge's stroke, or the next selected object's when it has no face or edge; type: its first + /// run's), else the defaults for new art. When the object whose fill the proxy shows is a + /// gradient mesh with points picked ([`Session::fill_mesh_points`]), the fill is its first + /// picked point's color, which a solid fill color changes. pub fn proxy_paints(&self) -> (Paint, Paint) { let points = self.fill_mesh_points(); let show = |stroke: bool| match self.proxy_source(stroke) { @@ -215,9 +217,20 @@ impl Session { if first.appearance.item_of_kind(item, !stroke).is_some() { return Some((Cow::Borrowed(first), item)); } - let mut nodes = vec![]; - painted(first, true, &mut nodes); - nodes.first().map(|n| (Cow::Borrowed(*n), None)) + // A Live Paint group without faces (or edges) shows the next selected object's paint; any other + // object without a painted object shows the defaults for new art. + for id in st.selection.subjects() { + let Some(n) = st.doc.node(*id) else { continue }; + let mut nodes = vec![]; + painted(n, true, stroke, &mut nodes); + if let Some(n) = nodes.first() { + return Some((Cow::Borrowed(*n), None)); + } + if !vectorcraft_tools::builder::is_live_paint(n) { + return None; + } + } + None } pub(crate) fn remember_paint_now(&mut self, p: &Paint) { @@ -258,21 +271,37 @@ fn same_in_proxy(a: &Paint, b: &Paint) -> bool { } } +/// The ids of the faces and edges of `n` when it is a Live Paint group, else none. +pub(crate) fn live_paint_parts(n: &Node) -> Vec { + use vectorcraft_tools::builder::{edges, faces, is_live_paint}; + if !is_live_paint(n) { + return vec![]; + } + faces(n).into_iter().chain(edges(n)).map(|part| part.id).collect() +} + /// The objects whose paints the proxies show for a selected `n`, the ones the paint commands /// change ([`leaf_targets`]): groups and layers stand for their contents (and so do blends and -/// other containers inside them), a compound path for its parts. -pub(crate) fn painted<'a>(n: &'a Node, top: bool, out: &mut Vec<&'a Node>) { +/// other containers inside them), a compound path for its parts. A Live Paint group stands for its +/// faces in the fill proxy (`stroke` false) and for its edges in the stroke proxy, the parts a fill +/// or a stroke given to it changes ([`live_paint_parts_skipped`]). +pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&'a Node>) { // A ruler guide has no paints. if n.is_ruler_guide() { return; } + if vectorcraft_tools::builder::is_live_paint(n) { + use vectorcraft_tools::builder::{edges, faces}; + out.extend(if stroke { edges(n) } else { faces(n) }.into_iter().map(|part| &**part)); + return; + } let expand = match n.kind { NodeKind::Group { .. } | NodeKind::Layer { .. } => true, NodeKind::Compound { .. } => false, _ => !top && n.is_container(), }; if expand { - n.children().into_iter().flatten().for_each(|c| painted(c, false, out)); + n.children().into_iter().flatten().for_each(|c| painted(c, false, stroke, out)); } else { out.push(n); } @@ -301,18 +330,31 @@ impl DocState { } // Looking the first object up builds the id cache when there is none. let first = self.selection.objects.first().and_then(|id| self.doc.node(*id)); - let (mut selected, mut nodes) = (vec![], vec![]); + let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]); + // The faces and edges of the selected Live Paint groups: selected as well, they count with their group's. + let mut covered = std::collections::HashSet::new(); // Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each // place it appears. for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) { #[cfg(test)] tests::note_gathered(); selected.push(n); - painted(n, true, &mut nodes); + if covered.contains(&n.id) { + continue; + } + covered.extend(live_paint_parts(n)); + painted(n, true, false, &mut fills); + painted(n, true, true, &mut strokes); } let differ = |stroke: bool| { let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke)); - let set = if item.is_some() { &selected } else { &nodes }; + let set = if item.is_some() { + &selected + } else if stroke { + &strokes + } else { + &fills + }; let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) { c if c.is_empty() => vec![proxy_paint(n, stroke, item)], c => c.into_iter().map(Paint::solid).collect(), @@ -568,7 +610,7 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) } // Resolve the requested targets before mutating defaults or the active proxy. let item = item_target(s, p, cmd)?.of_kind(s, fill); - let selected = item.targets(s, p)?; + let selected = item.targets_for(s, p, fill)?; let ids = super::graph::paint_targets(&s.doc()?.doc, &selected); let of = super::appearance::reference_of(s, p, item, cmd)?; let paint = if span { @@ -717,6 +759,69 @@ pub(crate) fn bucket_color_params(s: &Session, p: &Value, cmd: &str) -> Result