Merge pull request #7433 from dotCooCoo/fix/instance-row-effects-outline-hit

Symbols: instance fill and stroke effects count in Pathfinder effects and clicks
This commit is contained in:
BFlat
2026-11-18 13:03:58 +07:00
committed by GitHub
7 changed files with 558 additions and 109 deletions
+142 -68
View File
@@ -82,8 +82,9 @@ impl Default for HitOptions {
}
}
/// The shapes that an image's own fills and strokes paint, each with its fill rule and the fill or
/// stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated
/// The shapes that an image's own fills and strokes paint, or the fills and strokes of the art of a
/// symbol instance whose own fill or stroke has a geometry effect, each with its fill rule and the
/// fill or stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated
/// above this crate, so the engine registers one with [`set_image_paint`]. It looks up swatches and
/// patterns in the document it is given.
pub type ImagePaint = fn(Option<&Document>, &Node) -> Vec<(BezPath, FillRule, AppearanceItem)>;
@@ -97,10 +98,58 @@ pub fn set_image_paint(f: ImagePaint) {
let _ = IMAGE_PAINT.set(f);
}
/// The shapes that the image `n`'s own fills and strokes paint ([`set_image_paint`]), none while
/// nothing is registered.
pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(doc, n))
/// The shapes that [`ImagePaint`] gives for one object.
type Painted = Vec<(BezPath, FillRule, AppearanceItem)>;
/// The shapes that the image or symbol instance `n` paints with its geometry effects
/// ([`set_image_paint`]), none while nothing is registered. The shapes of a symbol instance of
/// `doc` with an effect on a fill or stroke are kept on this thread ([`PAINT_KEPT`]) and measured
/// again when `n`, a symbol of `doc` or its 9-slice guides or natural size, a pattern of `doc`,
/// its swatches or color groups, or the
/// [`LiveInputs`] have changed since, and on every call while `n` or the document's symbols or
/// patterns hold a placed document or the symbols hold an image ([`symbols_hold_images`]).
pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Rc<Painted> {
let Some(f) = IMAGE_PAINT.get() else { return Rc::default() };
let row_effects = || n.appearance.items.iter().any(|i| !i.effects().is_empty());
let Some(d) = doc.filter(|_| matches!(n.kind, NodeKind::SymbolInstance { .. }) && row_effects()) else {
return Rc::new(f(doc, n));
};
let inputs = live_inputs();
if let Some(painted) = kept(&PAINTED, d, n, inputs) {
return painted;
}
#[cfg(test)]
PAINT_EVALUATED.with(|c| c.set(c.get() + 1));
let painted = Rc::new(f(doc, n));
if !symbols_hold_images(d) {
let size = painted.iter().fold(0usize, |s, (bp, _, _)| s.saturating_add(1 + bp.elements().len()));
keep(&PAINTED, d, n, inputs, &painted, size, PAINT_KEPT);
}
painted
}
/// Does the art of a symbol of `doc` hold an image? The shapes its fills and strokes paint can
/// follow its pixels, which change when its file is read again, so [`image_paint`] does not keep
/// the shapes of an instance then.
fn symbols_hold_images(doc: &Document) -> bool {
let mut image = false;
doc.symbols.iter().for_each(|s| s.art.walk(&mut |c| image |= matches!(c.kind, NodeKind::Image(_))));
image
}
/// How many symbol instances' shapes [`image_paint`] keeps on each thread: every click and every
/// hover measures each instance whose fill or stroke has a geometry effect.
const PAINT_KEPT: usize = 64;
thread_local! {
/// The shapes [`image_paint`] keeps, the latest first.
static PAINTED: RefCell<Vec<Evaluated<Painted>>> = const { RefCell::new(Vec::new()) };
}
#[cfg(test)]
thread_local! {
/// How many symbol instances [`image_paint`] measured on this thread.
static PAINT_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// One level of evaluation of a live object in a document, as the canvas draws it: type in an
@@ -127,21 +176,72 @@ fn live_inputs() -> u64 {
LIVE_ART.get().map_or(0, |(_, inputs)| inputs())
}
/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by
/// name and art), patterns, swatches and color groups and the [`LiveInputs`] as they were, the art
/// and its [`art_size`].
struct EvaluatedLive {
/// An object evaluated by [`live_art`] or [`image_paint`] on this thread: the object, its
/// document's symbols (by name and art), patterns, swatches and color groups, the document data
/// that symbols' 9-slice guides and natural sizes are kept in, and the [`LiveInputs`] as they
/// were, the result and its size.
struct Evaluated<T> {
node: Node,
symbols: Vec<(String, Arc<Node>)>,
patterns: Vec<crate::PatternDef>,
swatches: crate::Shared<Vec<vectorcraft_color::Swatch>>,
swatch_groups: crate::Shared<Vec<vectorcraft_color::SwatchGroup>>,
unknown: crate::Shared<serde_json::Map<String, serde_json::Value>>,
inputs: u64,
art: Rc<Vec<Node>>,
art: Rc<T>,
size: usize,
}
impl EvaluatedLive {
/// The evaluations kept on this thread in one store, the latest first.
type Store<T> = std::thread::LocalKey<RefCell<Vec<Evaluated<T>>>>;
/// The evaluation of `n` in `doc` with inputs `inputs` that `store` keeps, moved to the front.
fn kept<T>(store: &'static Store<T>, doc: &Document, n: &Node, inputs: u64) -> Option<Rc<T>> {
store.with_borrow_mut(|kept| {
let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?;
let e = kept.remove(i);
let art = e.art.clone();
kept.insert(0, e);
Some(art)
})
}
/// Keep `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, at the front
/// of `store`, which keeps `most` evaluations whose sizes add up to [`LIVE_KEPT_SIZE`] at most.
/// Nothing is kept when `art` alone is larger, or when `n` or the document's symbols or patterns
/// hold a placed document ([`holds_placed`]).
fn keep<T>(store: &'static Store<T>, doc: &Document, n: &Node, inputs: u64, art: &Rc<T>, size: usize, most: usize) {
if size > LIVE_KEPT_SIZE || holds_placed(doc, n) {
return;
}
let e = Evaluated::new(doc, n, inputs, art, size);
store.with_borrow_mut(|kept| {
kept.insert(0, e);
kept.truncate(most);
let mut total = 0usize;
kept.retain(|e| {
total = total.saturating_add(e.size);
total <= LIVE_KEPT_SIZE
});
});
}
impl<T> Evaluated<T> {
/// `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, as they are now.
fn new(doc: &Document, n: &Node, inputs: u64, art: &Rc<T>, size: usize) -> Self {
Self {
node: n.clone(),
symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(),
patterns: doc.patterns.clone(),
swatches: doc.swatches.clone(),
swatch_groups: doc.swatch_groups.clone(),
unknown: doc.unknown.clone(),
inputs,
art: art.clone(),
size,
}
}
/// Is this the evaluation of `n` in `doc`, with inputs `inputs`, as they are now?
fn is_of(&self, doc: &Document, n: &Node, inputs: u64) -> bool {
self.inputs == inputs
@@ -151,6 +251,7 @@ impl EvaluatedLive {
&& self.patterns == doc.patterns
&& self.swatches == doc.swatches
&& self.swatch_groups == doc.swatch_groups
&& self.unknown == doc.unknown
}
}
@@ -158,8 +259,9 @@ impl EvaluatedLive {
/// envelope's stroke band hits it again and again, and an envelope can hold a blend.
const LIVE_KEPT: usize = 4;
/// Most [`art_size`] the evaluations [`live_art`] keeps on one thread add up to. Art larger than
/// this is not kept.
/// Most size the evaluations [`live_art`] keeps on one thread add up to ([`art_size`]), and the
/// shapes [`image_paint`] keeps (each shape and its path elements). Art larger than this is not
/// kept.
const LIVE_KEPT_SIZE: usize = 250_000;
/// The size of `art` for [`LIVE_KEPT_SIZE`]: its objects and the anchors of their paths.
@@ -184,52 +286,23 @@ fn holds_placed(doc: &Document, n: &Node) -> bool {
thread_local! {
/// The evaluations [`live_art`] keeps, the latest first.
static EVALUATED: RefCell<Vec<EvaluatedLive>> = const { RefCell::new(Vec::new()) };
static EVALUATED: RefCell<Vec<Evaluated<Vec<Node>>>> = const { RefCell::new(Vec::new()) };
}
/// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while
/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of
/// `doc`, its swatches or color groups, or the [`LiveInputs`] have changed since, and on every
/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc` or its 9-slice
/// guides or natural size, a pattern of `doc`, its swatches or color groups, or the
/// [`LiveInputs`] have changed since, and on every
/// click while it or the document's symbols or patterns hold a placed document ([`holds_placed`]).
fn live_art(doc: &Document, n: &Node) -> Rc<Vec<Node>> {
let inputs = live_inputs();
let kept = EVALUATED.with_borrow_mut(|kept| {
let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?;
let e = kept.remove(i);
let art = e.art.clone();
kept.insert(0, e);
Some(art)
});
if let Some(art) = kept {
if let Some(art) = kept(&EVALUATED, doc, n, inputs) {
return art;
}
#[cfg(test)]
LIVE_EVALUATED.with(|c| c.set(c.get() + 1));
let art = Rc::new(LIVE_ART.get().map_or_else(|| crate::live::expand_live(n), |(f, _)| f(Some(doc), n)));
let size = art_size(&art);
if size > LIVE_KEPT_SIZE || holds_placed(doc, n) {
return art;
}
let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect();
let e = EvaluatedLive {
node: n.clone(),
symbols,
patterns: doc.patterns.clone(),
swatches: doc.swatches.clone(),
swatch_groups: doc.swatch_groups.clone(),
inputs,
art: art.clone(),
size,
};
EVALUATED.with_borrow_mut(|kept| {
kept.insert(0, e);
kept.truncate(LIVE_KEPT);
let mut total = 0usize;
kept.retain(|e| {
total = total.saturating_add(e.size);
total <= LIVE_KEPT_SIZE
});
});
keep(&EVALUATED, doc, n, inputs, &art, art_size(&art), LIVE_KEPT);
art
}
@@ -257,7 +330,7 @@ pub fn set_drawn_art(f: DrawnArt) {
/// The art of an object found by [`drawn`] (none, or one object), with what it was found from, and
/// the box round everything that art can paint.
struct EvaluatedDrawn {
of: EvaluatedLive,
of: Evaluated<Vec<Node>>,
reach: Option<Rect>,
}
@@ -310,7 +383,8 @@ fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T {
/// nothing is registered, while a [`DrawnOff`] guard lives, for objects whose art is not evaluated
/// ([`evaluates`]), and when nothing in `n`, nor the art of a symbol an instance in it shows, has a
/// visible effect ([`draws_effects`]). The art is evaluated again when `n`, a symbol of the
/// document, its patterns, swatches or color groups, or the [`LiveInputs`] have changed since, and
/// document or its 9-slice guides or natural size, its patterns, swatches or color groups, or the
/// [`LiveInputs`] have changed since, and
/// on every call while it holds a placed document ([`holds_placed`]). When the art kept is full, new
/// art replaces as much other art as it needs room for, and art larger than [`LIVE_KEPT_SIZE`] is
/// kept alone.
@@ -332,16 +406,7 @@ fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc<Vec<Node>>, Option<Rect>
let art = Rc::new(art.into_iter().collect::<Vec<_>>());
let size = art_size(&art).saturating_add(art_size(std::slice::from_ref(n)));
if !holds_placed(doc, n) {
let of = EvaluatedLive {
node: n.clone(),
symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(),
patterns: doc.patterns.clone(),
swatches: doc.swatches.clone(),
swatch_groups: doc.swatch_groups.clone(),
inputs,
art: art.clone(),
size,
};
let of = Evaluated::new(doc, n, inputs, &art, size);
DRAWN.with_borrow_mut(|(kept, total)| {
if let Some(old) = kept.remove(&n.id) {
*total = total.saturating_sub(old.of.size);
@@ -1439,22 +1504,21 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
if opt.outline {
return None;
}
image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item {
AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke),
AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
})
hit_painted(n, p, opt, symbols)
}
NodeKind::Text(_) | NodeKind::PlacedDocument(_) => {
n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds)
}
// A symbol instance is hit within its bounds, and outside them where its art paints
// ([`instance_art_hit`]). In the art of another instance walked outside that instance's
// bounds, it is hit only where its own art paints ([`ArtOnly`]).
// ([`instance_art_hit`]) or where the geometry effects of its active fill or stroke reshape
// the art it draws ([`image_paint`]) except in outline mode. In the art of another instance
// walked outside that instance's bounds, it is hit only where its own art paints
// ([`ArtOnly`]).
NodeKind::SymbolInstance { .. } => {
if !ArtOnly::on() && n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
return Some(HitKind::Bounds);
}
instance_art_hit(n, p, opt, symbols)
instance_art_hit(n, p, opt, symbols).or_else(|| if opt.outline { None } else { hit_painted(n, p, opt, symbols) })
}
// A blend or an envelope is hit within its bounds, and outside them where its evaluated
// art paints: a blend's keys and steps on a spine can reach past the keys and the spine,
@@ -1481,6 +1545,16 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
}
}
/// What a click at `p` hits among the shapes that the fills and strokes of `n` (an image or a
/// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a
/// stroke along its shape, a fill inside it except with Selection by Path Only.
fn hit_painted(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item {
AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke),
AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
})
}
/// Is `p` within `tol` of the type path of `t` (in `n`), what "Type Object Selection by Path
/// Only" picks type by: its baselines ([`crate::TextObject::baselines`]), area type's frame and
/// type on a path's path, drawn through `n`'s perspective projection if it has one.
+69 -2
View File
@@ -1262,6 +1262,60 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() {
assert_eq!(evaluated(), before + 2);
}
/// For instances of the symbol "Painted", a fill that paints the square from (300, 0) to
/// (320, 20); nothing for anything else.
fn painted_far_away(_: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if symbol == "Painted" => {
let square = shapes::rectangle(Rect::new(300.0, 0.0, 320.0, 20.0)).to_bezpath();
vec![(square, FillRule::NonZero, AppearanceItem::Fill(crate::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))))]
}
_ => vec![],
}
}
/// Clicks and hovers measure the shapes a symbol instance's fill and stroke effects paint once,
/// and again only after the instance or the symbols change.
#[test]
fn clicks_measure_a_symbol_instances_painted_shapes_once_until_it_changes() {
set_image_paint(painted_far_away);
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art());
d.symbols.push(crate::Symbol { dynamic: false, name: "Painted".into(), art: Arc::new(art) });
let inst = d.alloc_id();
let mut n = Node::new(inst, NodeKind::SymbolInstance { symbol: "Painted".into(), xf: vectorcraft_geom::Affine::IDENTITY });
n.appearance = Appearance::default_art().into();
let offset = crate::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 10}), visible: true };
n.appearance.items[0].effects_mut().push(offset);
d.insert(Some(l), 0, n).unwrap();
let measured = || PAINT_EVALUATED.with(std::cell::Cell::get);
let before = measured();
let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 10.0), HitOptions::default()).map(|h| h.leaf);
assert_eq!(at(&d, 310.0), Some(inst), "a click where the instance's fill paints");
assert_eq!(at(&d, 500.0), None);
assert_eq!(at(&d, 10.0), Some(inst));
assert_eq!(measured(), before + 1);
d.node_mut(inst).unwrap().appearance.items[0].effects_mut()[0].params = serde_json::json!({"offset": 12});
assert_eq!(at(&d, 310.0), Some(inst));
assert_eq!(measured(), before + 2, "a changed instance is measured again");
let other = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art());
d.symbols.push(crate::Symbol { dynamic: false, name: "Other".into(), art: Arc::new(other) });
assert_eq!(at(&d, 310.0), Some(inst));
assert_eq!(measured(), before + 3, "changed symbols measure it again");
assert_eq!(at(&d, 310.0), Some(inst));
assert_eq!(measured(), before + 3);
// An image's pixels change when its file is read again, so with one in a symbol's art every
// click measures the instance.
let xf = vectorcraft_geom::Affine::IDENTITY;
let im = crate::ImageObject { key: "k".into(), width: 10, height: 10, xf, link: None, placement: Default::default(), pixels: None };
let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
d.symbols.push(crate::Symbol { dynamic: false, name: "Photo".into(), art: Arc::new(image) });
assert_eq!(at(&d, 310.0), Some(inst));
assert_eq!(at(&d, 310.0), Some(inst));
assert!(measured() >= before + 5, "each click measures it: {}", measured() - before);
}
/// A kept evaluation is the evaluation of the object only while the fonts and plug-ins
/// ([`LiveInputs`]) are as they were.
#[test]
@@ -1274,19 +1328,32 @@ fn a_kept_evaluation_is_stale_after_the_live_inputs_change() {
}
/// An evaluation of `n` in `d`, with inputs 7, holding no symbols, patterns or art.
fn kept_evaluation(d: &Document, n: &Node) -> EvaluatedLive {
EvaluatedLive {
fn kept_evaluation(d: &Document, n: &Node) -> Evaluated<Vec<Node>> {
Evaluated {
node: n.clone(),
symbols: vec![],
patterns: vec![],
swatches: d.swatches.clone(),
swatch_groups: d.swatch_groups.clone(),
unknown: d.unknown.clone(),
inputs: 7,
art: std::rc::Rc::new(vec![]),
size: 0,
}
}
/// A kept evaluation is stale once a symbol's 9-slice guides or natural size change: they place
/// the symbol's art, and the document keeps them apart from the symbols.
#[test]
fn a_kept_evaluation_is_stale_after_a_symbols_placement_changes() {
let mut d = Document::new(100.0, 100.0);
let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
let e = kept_evaluation(&d, &n);
assert!(e.is_of(&d, &n, 7));
d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({"Logo": [40.0, 20.0]}));
assert!(!e.is_of(&d, &n, 7));
}
/// A kept evaluation is stale once a swatch changes, in a color group too: a painted live effect's
/// pieces name swatches.
#[test]
+21 -13
View File
@@ -216,8 +216,10 @@ impl Node {
/// path give it ([`crate::hit::set_clip_region`]). An image's box takes in
/// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers
/// without a clipping mask and Intertwine groups take in their members' boxes, grown by their
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box
/// takes in where its spine can put its keys and steps.
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`], taking in the
/// shapes their art paints with the geometry effects of their own fill or stroke
/// ([`crate::hit::set_image_paint`]). A blend's box takes in where its spine can put its keys
/// and steps.
pub fn reach_bounds(&self) -> Option<Rect> {
self.reach(None)
}
@@ -254,14 +256,8 @@ impl Node {
.map(|b| b.inflate(o, o))
}
NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))),
// The frame and each shape the image's own fills and strokes paint, a stroke's grown by
// the farthest it can reach from its shape.
NodeKind::Image(_) => {
crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| {
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
})
}
// The frame and each shape the image's own fills and strokes paint.
NodeKind::Image(_) => self.with_own_paint(self.geometric(symbols), symbols),
// Keys and steps placed on a spine, turned to it with Align to Path, can reach past the
// keys and the spine.
NodeKind::Blend { children, spec } => {
@@ -272,13 +268,15 @@ impl Node {
NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => {
vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c)))
}
// The live geometry effects of the clipping paths in the art can draw it past its box.
// The live geometry effects of the clipping paths in the art can draw it past its box,
// and the box takes in each shape the art paints with the geometry effects of the
// instance's own fill or stroke.
NodeKind::SymbolInstance { symbol, xf } => {
let Some((s, art, region)) = symbols.and_then(|s| {
let a = s.art(symbol)?;
Some((s, a, a.reshaped?))
}) else {
return self.visual(symbols);
return self.with_own_paint(self.visual(symbols), symbols);
};
let map = s.document().symbol_slice_map_of(symbol, art.geometric, *xf);
let placed = if moves_only(*xf) && map.is_none() {
@@ -294,12 +292,22 @@ impl Node {
map.map_or_else(|| xf.transform_rect_bbox(all), |m| m.placement_bounds(all)).inflate(grow, grow)
};
let o = self.appearance.outset();
vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o)))
self.with_own_paint(vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o))), symbols)
}
_ => self.visual(symbols),
}
}
/// `start` grown by each shape the node's own fills and strokes paint
/// ([`crate::hit::set_image_paint`]), a stroke's grown by the farthest it can reach from its
/// shape.
fn with_own_paint(&self, start: Option<Rect>, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(start, |acc, (bp, _, item)| {
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
})
}
/// Geometric bounds (no stroke), recursively. Clip groups are bounded by their clip path. A
/// symbol instance is measured as its transform applied to the 20 × 20 square around the origin
/// that symbols made in the app keep their art in ([`Node::geometric_bounds_with`] measures
+21 -4
View File
@@ -110,13 +110,15 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &S
// Every path of the outline art, at any depth, is drawn inside the object's opacity
// and blend mode. A symbol's art comes with the live objects and the instances of
// other symbols inside it given as their art, and the type inside it outlined, so the
// art has nothing left for `hook` to give.
// art has nothing left for `hook` to give. Its fills and strokes carry the geometry
// effects of the instance's active fill and stroke, as the canvas draws them.
if let Some(h) = hook
&& let Some(art) = h(n)
{
let art = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if nodes.charge(&art) => {
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
let mut art = instance_art(doc, &art, h, nodes, symbol);
crate::reshape::add_instance_row_effects(doc, n, &mut art);
crate::reshape::outline_nested_text(doc, &mut art, false);
transparency_into_members(&mut art);
art
@@ -134,6 +136,19 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &S
}
}
/// `art`, the art `hook` gave an instance of the symbol named `symbol`, with the live objects and
/// the instances of other symbols inside it given as their art
/// ([`crate::reshape::symbol_art_with`]). The art of each of those instances carries the geometry
/// effects of its own active fill and stroke ([`crate::reshape::add_instance_row_effects`]).
fn instance_art(doc: Option<&Document>, art: &Node, hook: OutlineHook, nodes: &SymbolNodes, symbol: &str) -> Node {
let drawn = |m: &Node| {
let mut a = hook(m)?;
crate::reshape::add_instance_row_effects(doc, m, &mut a);
Some(a)
};
crate::reshape::symbol_art_with(art, &drawn, nodes, symbol)
}
/// `l`, a path drawn inside `n`: its opacity multiplied by `n`'s, and `n`'s blend mode when it is
/// not Normal.
fn within(l: &mut Node, n: &Node) {
@@ -221,13 +236,15 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod
}
},
// A symbol instance with a warp: its symbol's art placed by the instance, with the type
// inside it outlined, reshaped as one piece, as the renderer draws it.
// inside it outlined, reshaped as one piece, as the renderer draws it. The fills and strokes
// of the art then carry the geometry effects of the instance's active fill and stroke.
NodeKind::SymbolInstance { symbol, .. } if !fx.is_empty() => {
let h = hook?;
let art = h(n).filter(|art| nodes.charge(art))?;
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
let mut art = instance_art(doc, &art, h, nodes, symbol);
crate::reshape::outline_nested_text(doc, &mut art, false);
members_as_drawn(doc, &mut art);
crate::reshape::add_instance_row_effects(doc, n, &mut art);
let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc);
// The art's own fills and strokes follow the effects as its members do.
if carry.moves(&art.appearance) {
+91 -22
View File
@@ -387,7 +387,7 @@ fn row_effects_of(fx: &[Effect]) -> Vec<Effect> {
/// of a symbol whose art (in `doc`) holds an instance of `n`'s symbol, at any depth, keeps its
/// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no
/// instance in the art takes them.
fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) {
pub(crate) fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return };
let fill = active_fill(n).map_or(vec![], |f| row_effects_of(&f.effects));
let stroke = active_stroke(n).map_or(vec![], |s| row_effects_of(&s.effects));
@@ -613,32 +613,101 @@ fn traced_opaque_area(bytes: &[u8]) -> Traced {
/// rule and the fill or stroke that paints it: the paths (or compound paths) that [`reshape`]
/// makes along its frame or, for those whose first effect is Outline Object, along the outline of
/// its opaque area ([`opaque_area`]), with each fill's or stroke's geometry effects applied as the
/// renderer applies them. Empty for anything but an image with such fills or strokes. The swatches
/// and patterns that live-effect plug-ins painting their pieces name are looked up in `doc`, and
/// the image's pixels in `doc` when the image does not hold them.
/// renderer applies them. For a symbol instance whose active fill or stroke has a visible geometry
/// effect ([`has_item_geometry`]), the shapes that the fills and strokes of the art it draws paint
/// ([`instance_paint`]). Empty for anything else. The swatches and patterns that live-effect
/// plug-ins painting their pieces name are looked up in `doc`, and the image's pixels in `doc` when
/// the image does not hold them.
pub fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) {
return vec![];
}
let Some(art) = reshape(doc, n, None) else { return vec![] };
let mut out = vec![];
art.walk(&mut |c| {
let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return };
let Some(g) = c.stroke_path() else { return };
let ctx = GeomContext { doc, ..GeomContext::of(c) };
for item in c.appearance.items.iter().filter(|i| crate::paints(i)) {
let fx = item.effects();
let shape = if crate::has_geometry(fx) && !g.elements().is_empty() {
crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item))
} else {
g.clone()
};
out.push((shape, *rule, item.clone()));
}
});
if matches!(n.kind, NodeKind::SymbolInstance { .. }) {
let mut budget = SYMBOL_ART_MAX_NODES;
instance_paint(doc, n, 1, &mut budget, &mut out);
return out;
}
if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) {
return out;
}
let Some(art) = reshape(doc, n, None) else { return out };
art.walk(&mut |c| push_painted(doc, c, &mut out));
out
}
/// The shapes that the fills and strokes of path or compound path `c` paint, each with the
/// geometry effects of that fill or stroke applied ([`image_paint`]); nothing for other objects.
fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) {
let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return };
let Some(g) = c.stroke_path() else { return };
let ctx = GeomContext { doc, ..GeomContext::of(c) };
for item in c.appearance.items.iter().filter(|i| crate::paints(i)) {
let fx = item.effects();
let shape = if crate::has_geometry(fx) && !g.elements().is_empty() {
crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item))
} else {
g.clone()
};
out.push((shape, *rule, item.clone()));
}
}
/// The shapes that symbol instance `n`, `depth` instances deep, paints with the geometry effects of
/// its active fill and stroke ([`has_item_geometry`]): the paths of the art [`reshape`] makes of it,
/// each with its own geometry effects and those of each fill and stroke applied
/// ([`crate::bake_type_appearance`], [`push_painted`]), the paths that the own fills and strokes of
/// the groups and layers in the art paint and the results of their Pathfinder effects
/// ([`crate::evaluate_container`]), the shapes that the own fills and strokes of the images in the
/// art paint ([`image_paint`]), and the instances in that art that took those effects, in turn.
/// Hidden objects, clipping paths, guides, the members of clip groups and the original shapes of
/// Shaper groups add nothing, and neither does an instance more than
/// [`vectorcraft_doc::depth::MAX_DEPTH`] deep or whose symbol's art would take the objects measured
/// so far past `budget`.
fn instance_paint(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return };
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_item_geometry(n) {
return;
}
let Some(sym) = doc.and_then(|d| d.symbols.iter().find(|s| s.name == *symbol)) else { return };
let count = sym.art.count() as u64;
if count > *budget {
return;
}
*budget -= count;
let Some(art) = reshape(doc, n, Some(&vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n))) else { return };
painted_in(doc, &art, depth, budget, out);
}
/// [`instance_paint`] of the objects in `n`, art of an instance `depth` instances deep.
fn painted_in(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) {
if !n.visible {
return;
}
match &n.kind {
NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. } => match crate::bake_type_appearance(doc, n) {
// One path for each fill and stroke, its effects applied.
Some(pieces) => painted_in(doc, &pieces, depth, budget, out),
None => push_painted(doc, n, out),
},
NodeKind::Path { .. } => {}
NodeKind::Image(_) => out.extend(image_paint(doc, n)),
NodeKind::SymbolInstance { .. } => instance_paint(doc, n, depth + 1, budget, out),
_ if n.clips() => {}
_ => {
// A Pathfinder effect paints its result, not the members it combines.
let evaluated = (crate::has_container_appearance(n) || crate::has_pathfinder(n)).then(|| crate::evaluate_container(doc, n)).flatten();
let g = evaluated.as_ref().unwrap_or(n);
if g.clips() {
return;
}
// A Shaper group's first member holds its original shapes, which are not drawn. The
// group's own fills and strokes can be painted before it, so it is found by its id.
let sources = n.extras().shaper.is_some().then(|| n.children().and_then(|c| c.first()).map(|c| c.id)).flatten();
for c in g.children().into_iter().flatten().filter(|c| Some(c.id) != sources) {
painted_in(doc, c, depth, budget, out);
}
}
}
}
/// The glyph outlines of type `t` in text space with its underline and strikethrough bars: one
/// path per run, and all of them as one.
pub(crate) fn glyph_outlines(t: &vectorcraft_doc::TextObject) -> (Vec<kurbo::BezPath>, kurbo::BezPath) {
+213
View File
@@ -260,6 +260,100 @@ fn a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds() {
assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the offset stroke: {b:?}");
let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn");
assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the offset stroke: {drawn:?}");
assert_eq!(hit_at(&s, 30.5, vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }), Some(id), "a click on the added stroke");
}
/// What a click at (`x`, 100) with `opt` hits.
fn hit_at(s: &Session, x: f64, opt: vectorcraft_doc::hit::HitOptions) -> Option<NodeId> {
vectorcraft_doc::hit::hit_test(&s.doc().unwrap().doc, vectorcraft_geom::Point::new(x, 100.0), opt).map(|h| h.leaf)
}
/// [`instance_with_row`] of a symbol whose art is an instance of another symbol made of the square.
fn nested_instance_with_row(s: &mut Session) -> (NodeId, usize) {
square(s);
let inner = NodeId(run(s, "symbol.new", json!({"name": "Inner"}))["id"].as_u64().unwrap());
run(s, "select.set", json!({"ids": [inner.0]}));
let id = NodeId(run(s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap());
run(s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(s, id).appearance.items.len() - 1;
run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
(id, row)
}
/// Effect › Pathfinder › Add on a group holding a symbol instance combines the art the instance
/// draws: the effects on the instance's fill and stroke reshape the result as they reshape the
/// instance, in a symbol placed inside another symbol too.
#[test]
fn pathfinder_takes_a_symbol_instance_fill_and_stroke_effects() {
for (fill, x, color) in [(true, 44, RED), (false, 40, BLUE)] {
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", fill);
offset_row(&mut s, id, row, 10.0);
let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"}));
let r = render(&s);
assert!(near(r.pixel(x, 100), color), "fill {fill}: the result keeps the offset: {:?}", r.pixel(x, 100));
assert!(near(r.pixel(100, 100), RED), "fill {fill}: the result keeps the art's fill: {:?}", r.pixel(100, 100));
}
// An effect of the instance's own reshapes the art as well.
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", true);
offset_row(&mut s, id, row, 10.0);
run(&mut s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 5}}));
assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the art on the canvas: {:?}", render(&s).pixel(37, 100));
let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"}));
assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the result: {:?}", render(&s).pixel(37, 100));
let mut s = session();
let (id, row) = nested_instance_with_row(&mut s);
offset_row(&mut s, id, row, 10.0);
assert!(near(render(&s).pixel(44, 100), RED), "the nested art grows on the canvas: {:?}", render(&s).pixel(44, 100));
let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"}));
assert!(near(render(&s).pixel(44, 100), RED), "the nested art grows in the result: {:?}", render(&s).pixel(44, 100));
}
/// A click where the effect on a symbol instance's fill or stroke paints its art outside the
/// instance's bounds selects the instance; a click past the drawn art, a fill with Selection by
/// Path Only and outline mode do not.
#[test]
fn a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() {
use vectorcraft_doc::hit::HitOptions;
let opt = HitOptions { tol: 1.0, ..Default::default() };
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", true);
assert_eq!(hit_at(&s, 44.0, opt), None);
offset_row(&mut s, id, row, 10.0);
assert_eq!(hit_at(&s, 44.0, opt), Some(id), "a click on the grown fill");
assert_eq!(hit_at(&s, 100.0, opt), Some(id), "a click inside the instance");
assert_eq!(hit_at(&s, 36.0, opt), None, "a click past the grown fill");
assert_eq!(hit_at(&s, 44.0, HitOptions { path_only: true, ..opt }), None, "Selection by Path Only leaves the fill out");
assert_eq!(hit_at(&s, 44.0, HitOptions { outline: true, ..opt }), None, "outline mode draws the art as it is");
let mut s = session();
let (id, row) = instance_with_row(&mut s, "Square", false);
offset_row(&mut s, id, row, 10.0);
assert_eq!(hit_at(&s, 40.0, opt), Some(id), "a click on the moved stroke");
assert_eq!(hit_at(&s, 45.0, opt), None, "a click between the moved stroke and the fill");
assert_eq!(hit_at(&s, 40.0, HitOptions { path_only: true, ..opt }), Some(id), "Selection by Path Only takes the stroke");
let mut s = session();
let (id, row) = nested_instance_with_row(&mut s);
offset_row(&mut s, id, row, 10.0);
assert_eq!(hit_at(&s, 44.0, opt), Some(id), "a click on the grown fill of the nested art");
// A path in the art with an Offset Path of its own: both offsets grow what it draws.
let mut s = session();
let art = square(&mut s);
run(&mut s, "effect.apply", json!({"ids": [art.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 5}}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Offset"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
offset_row(&mut s, id, row, 10.0);
assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the art on the canvas: {:?}", render(&s).pixel(37, 100));
assert_eq!(hit_at(&s, 37.0, opt), Some(id), "a click where both offsets grow the art");
}
/// A group in the symbol's art with a fill of its own: the instance's fill effect reshapes what
@@ -284,6 +378,7 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() {
assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the group's grown fill: {b:?}");
let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn");
assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the group's grown fill: {drawn:?}");
assert_eq!(hit_at(&s, 35.0, vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }), Some(id), "a click on the group's grown fill");
let before = render(&s);
run(&mut s, "effect.expandAppearance", json!({}));
@@ -292,6 +387,124 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() {
assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8));
}
/// An image in the symbol's art whose fill Convert to Shape gives a shape: the instance's fill
/// effect grows what that fill paints, and a click there selects the instance.
#[test]
fn a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance() {
let mut s = session();
let mut png = vec![];
image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
// The frame runs from 85 to 115; the fill's shape is 9 pt larger on each side.
let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]}));
let im = NodeId(r["ids"][0].as_u64().unwrap());
run(&mut s, "select.set", json!({"ids": [im.0]}));
run(&mut s, "appearance.addFill", json!({}));
run(&mut s, "paint.setFill", json!({"color": "#0000ff", "item": 0}));
run(&mut s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert_eq!(hit_at(&s, 70.0, opt), None);
offset_row(&mut s, id, row, 10.0);
assert!(near(render(&s).pixel(70, 100), BLUE), "the image's fill grows by the offset: {:?}", render(&s).pixel(70, 100));
assert_eq!(hit_at(&s, 70.0, opt), Some(id), "a click on the image's grown fill");
assert_eq!(hit_at(&s, 60.0, opt), None, "a click past the grown fill");
}
/// A group in the symbol's art with Effect › Pathfinder › Subtract: the instance's fill effect
/// grows the result, and a click past both shapes where only the subtracted shape would grow does
/// not select the instance.
#[test]
fn a_click_on_a_shape_a_pathfinder_effect_in_the_art_subtracts_misses_the_instance() {
let mut s = session();
// The back square runs from 50 to 110 and the front one from 80 to 140; the result runs from 50 to 80.
let back = NodeId(run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 60, "height": 100}))["id"].as_u64().unwrap());
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "paint.setStroke", json!({"color": "#0000ff"}));
run(&mut s, "stroke.set", json!({"weight": 4}));
let front = NodeId(run(&mut s, "shape.rectangle", json!({"x": 80, "y": 50, "width": 60, "height": 100}))["id"].as_u64().unwrap());
let g = NodeId(run(&mut s, "object.group", json!({"ids": [back.0, front.0]}))["id"].as_u64().unwrap());
run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.subtract"}));
run(&mut s, "select.set", json!({"ids": [g.0]}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Subtracted"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert_eq!(hit_at(&s, 45.0, opt), None);
offset_row(&mut s, id, row, 10.0);
let r = render(&s);
assert!(near(r.pixel(45, 100), RED), "the result's fill grows by the offset: {:?}", r.pixel(45, 100));
assert!(near(r.pixel(145, 100), WHITE), "the subtracted shape is not drawn: {:?}", r.pixel(145, 100));
assert_eq!(hit_at(&s, 45.0, opt), Some(id), "a click on the result's grown fill");
assert_eq!(hit_at(&s, 145.0, opt), None, "a click where only the subtracted shape would grow");
}
/// A Shaper group in the symbol's art: the instance's fill effect grows the faces it shows, and a
/// click where only its original shapes would grow does not select the instance.
#[test]
fn a_click_on_a_shaper_groups_original_shapes_in_the_art_misses_the_instance() {
let mut s = session();
run(&mut s, "paint.setStroke", json!({"none": true, "ids": []}));
for x in [0, 50] {
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": []}));
run(&mut s, "shape.rectangle", json!({"x": x, "y": 50, "width": 100, "height": 100}));
}
// The scribble inside the overlap removes the front rectangle's face; the face left runs from 0 to 50.
let g = NodeId(run(&mut s, "shaper.scribble", json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]}))["id"].as_u64().unwrap());
assert!(node(&s, g).extras().shaper.is_some());
run(&mut s, "select.set", json!({"ids": [g.0]}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Shaped"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert_eq!(hit_at(&s, 57.0, opt), None);
offset_row(&mut s, id, row, 10.0);
let r = render(&s);
assert!(near(r.pixel(57, 100), RED), "the face's fill grows by the offset: {:?}", r.pixel(57, 100));
assert!(near(r.pixel(125, 100), WHITE), "the original shapes are not drawn: {:?}", r.pixel(125, 100));
assert_eq!(hit_at(&s, 57.0, opt), Some(id), "a click on the face's grown fill");
assert_eq!(hit_at(&s, 125.0, opt), None, "a click on an original shape");
}
/// A Shaper group in the symbol's art with a stroke of its own below its Contents row: the
/// instance's stroke effect moves what that stroke paints, and a click selects the instance where
/// the canvas draws the moved stroke, not inside the original shapes.
#[test]
fn a_click_on_a_shaper_group_with_a_stroke_below_its_contents_selects_the_instance_where_it_draws() {
let mut s = session();
run(&mut s, "paint.setStroke", json!({"none": true, "ids": []}));
for x in [0, 50] {
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": []}));
run(&mut s, "shape.rectangle", json!({"x": x, "y": 50, "width": 100, "height": 100}));
}
// The scribble removes the front rectangle's face; the group's stroke outlines both rectangles.
let g = NodeId(run(&mut s, "shaper.scribble", json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addStroke", json!({"ids": [g.0]}));
let stroke = node(&s, g).appearance.items.len() - 1;
run(&mut s, "paint.setStroke", json!({"ids": [g.0], "item": stroke, "color": "#0000ff"}));
run(&mut s, "stroke.set", json!({"ids": [g.0], "item": stroke, "weight": 4}));
run(&mut s, "appearance.moveItem", json!({"ids": [g.0], "from": "contents", "to": stroke + 1}));
assert_eq!(node(&s, g).appearance.split_contents().0.len(), stroke + 1, "the group's stroke is below its Contents row");
run(&mut s, "select.set", json!({"ids": [g.0]}));
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Shaped"}))["id"].as_u64().unwrap());
run(&mut s, "appearance.addStroke", json!({"ids": [id.0]}));
let row = node(&s, id).appearance.items.len() - 1;
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
offset_row(&mut s, id, row, 10.0);
let r = render(&s);
let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() };
assert!(near(r.pixel(160, 100), BLUE), "the group's stroke moves out by the offset: {:?}", r.pixel(160, 100));
assert!(near(r.pixel(125, 100), WHITE), "the original shapes are not drawn: {:?}", r.pixel(125, 100));
assert_eq!(hit_at(&s, 160.0, opt), Some(id), "a click on the group's moved stroke");
assert_eq!(hit_at(&s, 125.0, opt), None, "a click inside an original shape");
}
/// Of several fills, only the topmost one's effects reach the art, and only while it is visible.
#[test]
fn only_the_topmost_visible_instance_fill_reshapes_the_art() {
+1
View File
@@ -1884,6 +1884,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
Outline Object on an image's own fill or stroke follows the outline of the image's opaque area, and the image's frame when the image has no transparency. Path effects apply to a fill or stroke added to a bitmap object ([archived reference manual, page 561](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=561)), and with Outline Object such a stroke follows the boundary of the art when the image has transparent areas and the image's frame when it has none ([CreativePro article on strokes for placed images](https://web.archive.org/web/20250815214529/https://creativepro.com/add-strokes-placed-images-illustrator/)). VectorCraft's own rules: the opaque area is the pixels at least 50% opaque, and its outline is traced as Image Trace's Black and White mode traces at threshold 128 and fitted with curves. Evidence: `tests::imageoutline` (vectorcraft-effects), `opaque::tests` (vectorcraft-trace), `tests::containers::an_images_stroke_with_outline_object_follows_its_opaque_area` and `tests::containers::an_images_outline_object_stroke_exports_selects_and_measures_along_its_opaque_area` (vectorcraft-engine), `tests::objectfx::an_images_outline_object_stroke_follows_new_pixels_under_the_same_key` (vectorcraft-render).
A geometry effect on one of type's own fills or strokes reshapes the whole outline that the fill or stroke paints, on the canvas and in exports; PDF, SVG, EPS and the other vector exports write such type as paths. On type that holds inline graphics, those effects are drawn and exported only when the type has a geometry effect or perspective of its own.
A geometry effect on a symbol instance's fill reshapes the filled shapes of the symbol's art and leaves their strokes as they are; one on the instance's stroke reshapes the stroked shapes and leaves their fills as they are. The shapes keep their colors. Only the instance's topmost fill and topmost stroke count, and only while they are visible with an opacity above 0. The canvas and Object › Expand Appearance use the same art, SVG and PDF export bake the same shapes, and Expand Appearance turns the instance into an editable group in one undo step. A group's own fills and strokes in the art take the effects too. An instance inside the art passes the effects on to its own art, and a dynamic symbol's instance reshapes the fills and strokes it paints on the art. How the effects map onto the symbol's art is VectorCraft's own rule. The help page <https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html> describes effects on one fill or stroke, and the help page <https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html> describes Expand Appearance (engine `expand::a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands`, `a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `only_the_topmost_visible_instance_fill_reshapes_the_art`, `a_nested_symbol_instance_takes_the_outer_fill_effect`, `export_bakes_a_symbol_instance_fill_effect`, `a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends`). Existing documents with a geometry effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing.
Effect › Pathfinder takes a symbol instance as the art it draws with the geometry effects of its fill and stroke, as they take a path with such effects: the result painted by the instance's art carries those effects, also when the instance has geometry effects of its own and when the instance sits inside another symbol's art. A click where those effects paint the art outside the instance's bounds selects the instance, a fill only when Selection by Path Only is off, and outline mode still takes the instance's bounds alone. A compound shape's area leaves out its members' fill and stroke effects for symbol instances as for paths, since the compound shape paints the area with its own appearance. These are VectorCraft's own rules (engine `expand::pathfinder_takes_a_symbol_instance_fill_and_stroke_effects`, `a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance`). Before, Pathfinder dropped those effects and clicks took only the instance's bounds.
Live effects inside a symbol's art (geometry effects, color adjustments and the rest that export bakes) are written where each instance places the art in PDF, print, EPS and DXF, as the canvas draws them: the art is placed first and its effects are applied after, so an instance that scales its art does not scale the distance a Transform effect moves it. Symbols nested in the art, a dynamic symbol instance's own paint changes and the stain an instance's fill gives its art are kept, and the art is stained before its effects apply. A linked instance's PDF link covers its art where the effects draw it. A symbol whose art holds itself stops at the nesting limit, and the symbols' own art keeps its effects. An instance stays an instance in these exports when the objects its art makes once baked (the copies a Transform effect makes included) would take the export's placed symbol art past 16,000,000 objects, or when its baked art would draw deeper than the 128 levels a document may draw; these are VectorCraft's own limits. Art baked for an instance that then stays an instance still counts toward that limit, and while an instance's art bakes, the art's own objects are held in the limit for the instances nested in it. Instances the export leaves out (hidden ones, those in hidden groups, on template layers, and on hidden layers or layers that do not print when the export leaves those out) are not placed and do not count toward that limit. Before, these exports wrote the art without its effects (effects `bake::placing_symbols_bakes_their_art_where_each_instance_places_it`, `placing_symbols_reaches_the_art_of_nested_instances`, `placing_a_symbol_that_holds_itself_stops`, `placing_symbols_keeps_dynamic_instances_changes`, `placing_symbols_keeps_the_instances_stain`, `placing_symbols_counts_the_baked_art`, `placing_symbols_counts_nested_art_once`, `placing_symbols_holds_the_outer_art_while_it_bakes`, `placing_symbols_counts_the_art_it_drops`, `placing_symbols_counts_art_dropped_for_depth_against_later_baked_art`, `placing_symbols_keeps_the_baked_art_within_the_drawn_depth`, `placing_symbols_skips_instances_the_export_leaves_out`; doc `depth::tests::drawn_heights_measure_objects_outside_the_layers`; PDF, print, EPS and DXF `symbol_art_effects_are_written_where_they_draw`, `symbol_art_effects_print_where_they_draw`; PDF `a_stained_instance_keeps_its_stain_when_its_art_has_effects`, `a_linked_instance_keeps_its_link_when_its_art_has_effects`).
EMF, WMF and SVG export write the same symbol art the same way: an instance of a symbol whose art, or the art of a symbol nested in it, has such effects is written as that art placed by the instance and then baked, so a square that a Transform effect moves 100 pt right draws 100 pt right of where the instance places it at any scale or rotation, and art the effect moves onto the artboard is written. EMF and SVG clip 9-slice cells and WMF does not, as each places other instances. In SVG those instances use no `<symbol>`, and instances of symbols without such effects still share one; named objects in a symbol's art take no ids there, as in an instance with its own copy of the art, so two instances do not write the same id; with Hidden Layers on, hidden instances are placed too and written hidden. An SVG instance nested in another instance's art is shared through `<use>` only when the transform it is drawn with, the outer instances' included, keeps the shared art as the canvas draws it, so a nested stroke keeps its weight in a scaled instance. Preserve Editing still embeds the document with its live effects. Before, these exports wrote the art without its effects (metafile `tests::import::symbol_art_effects_are_written_where_they_draw`; SVG `symbols_layers::symbol_art_effects_are_written_where_the_canvas_draws_them`, `a_kept_hidden_instance_is_written_with_its_symbols_effects`, `instances_written_as_their_art_give_its_names_no_id`, `a_nested_instance_is_shared_only_under_the_transform_it_is_drawn_with`; effects `bake::placing_symbols_skips_instances_the_export_leaves_out`).
EMF and WMF export with Use Artboards applies the document's live effects once for all the chosen artboards instead of once for each, and writes the same files byte for byte (metafile `tests::export_regions_writes_what_each_region_writes_alone`; `export_regions_perf` times it).