This commit is contained in:
bflatastic committed 2026-11-18 14:59:35 +07:00
commit fd18dab20a
18 files changed
+870 -28

No files matched your search

+4 -2
View File
@@ -189,12 +189,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.
+25 -5
View File
@@ -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<f64>,
}
#[derive(Deserialize)]
@@ -75,11 +79,17 @@ struct CustomArrowheadData {
name: String,
#[serde(default)]
path: PathData,
#[serde(default)]
stop: Option<f64>,
}
impl From<CustomArrowheadData> 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))
}
}
+11 -2
View File
@@ -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");
}
+2 -1
View File
@@ -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;
+1 -1
View File
@@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
+48
View File
@@ -8288,3 +8288,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::<bool>(),
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))?;
}
}
+1
View File
@@ -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;
+244
View File
@@ -0,0 +1,244 @@
//! 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, 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<CustomArrowhead> {
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 && plain(art) && !paints(art) => {
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 !plain(n) {
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() || 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() || s.opacity < 1.0 {
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` 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 {
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)))
}
#[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<Node> {
let points: Vec<Point> = 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<Node> {
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<Node> {
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<Arc<Node>>) -> 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<Node>| 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());
}
}
+7 -2
View File
@@ -124,8 +124,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};
@@ -540,6 +540,10 @@ struct Reader<'a> {
symbol_bounds: HashMap<String, Rect>,
/// The symbols read, by their name in the file → their name in the document.
symbol_names: HashMap<String, String>,
/// 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<String, Option<Arc<CustomArrowhead>>>,
/// 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<String>,
@@ -796,6 +800,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(),
@@ -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();
@@ -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);
+3 -1
View File
@@ -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);
@@ -1169,7 +1171,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);
+143 -10
View File
@@ -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 -------------------------------------------------------------------------
@@ -707,6 +710,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;
@@ -818,6 +845,7 @@ impl<'a> Reader<'a> {
brushes: &self.brush_drafts,
kept: &self.brushes_kept.kept,
bending: &self.brushes_kept.bending,
arrowheads: &self.arrowheads,
space,
},
)
@@ -1044,6 +1072,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<String, f64>,
/// The heads of the arrowhead symbols strokes name ([`Reader::arrowheads`]).
arrowheads: &'a HashMap<String, Option<Arc<CustomArrowhead>>>,
space: Affine,
}
@@ -1369,7 +1399,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) {
@@ -1382,7 +1412,89 @@ 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<Rect> {
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), or when both do
/// 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<Appearance> {
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): 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 {
let moves = c.stop() * s.arrow_weight(end) * k;
(shift, most) = (shift.min(moves), most.max(moves));
}
}
}
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);
let mut fits = vec![];
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 {
fits.push(align);
}
}
// Both fit when the bounds can't tell the placements apart (the end inside the bounds of the
// line's other segments), unless every head moves so little that either draws alike.
let align = match fits.as_slice() {
[one] => *one,
[first, _] if most < 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
@@ -1390,7 +1502,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<String, Gradient>) -> Option<Appearance> {
pub(super) fn appearance_from_art_style(
st: &crate::import::ai::style::ArtStyle,
gradients: &HashMap<String, Gradient>,
arrowheads: &HashMap<String, Option<Arc<CustomArrowhead>>>,
) -> Option<Appearance> {
use crate::import::ai::style::StyleItem;
if !st.plain {
return None;
@@ -1405,7 +1521,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,
};
@@ -1496,7 +1612,7 @@ pub(crate) fn read_parsed_style(parsed: &ParsedStyle, own_gradient: Option<&Pain
.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);
@@ -1511,12 +1627,27 @@ pub(crate) fn parsed_moves_with(parsed: &ParsedStyle, object: &Node) -> bool {
!parsed.style.moves_outline() || moves_with(object, &parsed.style)
}
/// A style's stroke as an appearance item (`None` for a fill).
fn stroke_layer(item: &crate::import::ai::style::StyleItem) -> Option<AppearanceItem> {
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<String, Option<Arc<CustomArrowhead>>>) -> Option<AppearanceItem> {
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<Arrowhead>, 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))
}
@@ -1701,6 +1832,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)))]);
@@ -1747,6 +1879,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)))]);
+97
View File
@@ -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<Box<StrokeArrows>>,
},
}
/// 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<Item = &str> {
[&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<f64> = 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<String, String>,
/// `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,
@@ -532,6 +564,11 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap<String, A
}
}
b"Array" => 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()) {
@@ -890,6 +927,7 @@ impl OnePaint {
profile: None,
align: StrokeAlign::Center,
brush: None,
arrows: None,
}),
_ => return Err(()),
}
@@ -1485,11 +1523,68 @@ fn stroke_item(f: &Filter, align: StrokeAlign) -> Result<Option<StyleItem>, ()>
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<Option<Box<StrokeArrows>>, ()> {
let end = |symbol: &str, scale: &str| -> Result<Option<(String, f64)>, ()> {
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<V>, other_entry: &mut Option<Option<String>>, 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();
// 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);
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.
@@ -1552,6 +1647,7 @@ fn calligraphic_stroke(f: &Filter) -> Option<StyleItem> {
profile: None,
align: StrokeAlign::Center,
brush: Some((name.clone(), PathBrush::Calligraphic(super::brush::calligraphic(values, variation, codes)))),
arrows: None,
})
}
@@ -1635,6 +1731,7 @@ fn art_stroke(f: &Filter) -> Option<StyleItem> {
profile: None,
align: StrokeAlign::Center,
brush: Some((name.clone(), PathBrush::Art(settings))),
arrows: None,
})
}
+31 -2
View File
@@ -1553,8 +1553,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:?}")
};
@@ -1595,3 +1597,30 @@ 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::<Vec<_>>());
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)));
}
+237
View File
@@ -6310,6 +6310,243 @@ 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<Node>, 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 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 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 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.
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
+2 -1
View File
@@ -1,6 +1,6 @@
# File format parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: 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` procLine truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **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: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: 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 teLine truncated
>
> Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865).
@@ -383,6 +383,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`, `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. |
+3 -1
View File
@@ -6026,7 +6026,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