mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-10-14 19:26:56 -04:00
Symbols: instances of imported symbols are measured by their art
Every symbol instance was measured as its transform applied to the 20 × 20 square around the origin, which symbols made in the app keep their art in. The SVG and DXF importers keep symbol art as drawn, so the box of an instance of an imported symbol did not match its art. The SVG Star instance at x 20, y 30 draws from (20, 30) to (40, 50) and was measured from (10, 20) to (30, 40). Align moved such an instance by the wrong amount, clicks and marquees beside its art selected it, and the canvas, exports and prints left it out when its art reached the view or the page and the square did not. An instance is now measured by its symbol's art, which Document::symbol_boxes looks up in the document each time (Node::geometric_bounds_with, visual_bounds_with and reach_bounds_with). With Use Preview Bounds on, the strokes in the art count at their own weight, as the canvas draws them, and object.setBounds counts them at that weight when it sizes an instance or an object that holds one. When strokes do not scale and a width or height of 0 or more is smaller than what a path's stroke adds, object.setBounds now gives the path no width or height, as it does for an instance whose art has strokes; before, it mirrored the path. With Use Preview Bounds on, object.setBounds now measures the margins that strokes add object by object, the members of groups and the objects in symbol instances' art included, and solves for the width, height and reference point asked for when the width and height are 0 or more. Before, it measured the margins of the whole selection and could miss the size or the reference point asked for when strokes did not scale and the objects' strokes added different margins, and when strokes scaled and the width and height were out of proportion, even for one path. A clip group, a Shaper Group, a compound path, type, and a group or instance with effects or an opacity mask of its own are each measured as one object, and so is an instance in perspective or one turned or slanted relative to the bounding box, other than by quarter turns. When the selection holds more than 4,096 objects to measure this way, each selected object is measured as one. Instances inside symbol art are measured by their own symbol's art. An instance is measured as the square when its symbol is missing, when its symbol or a symbol nested in its art holds an instance of itself, and when symbols nest 32 deep in its art. Align and Distribute, the Transform panel, the bounding box and the selection outline, clicks, the marquee, document.inspect and document.node, Fit to Artwork Bounds and Fit to Selected Art, canvas culling, thumbnails, the SVG filter region of an instance with a raster effect, raster effect images, Export Selection, the SVG of an artboard, printing, and the PDF, EPS, EMF/WMF and DXF writers use the new box. The renderer also culls an instance by the effects and brushed strokes in its art, and it culls a blend, envelope or repeat by the brush art of what it holds and the effects in the art of the instances in it. It culls an instance with geometry effects of its own by the effects in its art after those geometry effects reshape the art. It measures the effects in a symbol's art once for each symbol and linear part of the transform that places it. For symbols whose art holds instances, it measures at most 4,096 placements a frame, and at most 4,096 more for each pattern tile it rasterizes and each placed document it draws. Past that, it estimates the reach from the symbol's reach with no transform, which it measures once. When the drawn document's symbols change, the renderer drops the cached bounds of the instances and of the objects that hold them. The PDF and EPS writers, the SVG of an artboard and Skip Blank Artboards grow the box of an instance whose art holds brushed strokes by 16 times the widest stroke (at least 1 pt) of the objects in that art that have a brushed stroke, plus 8 pt, as the renderer grows the cull bounds of a brushed path. They keep an instance whose brush art reaches the page. The SVG of an artboard also keeps an object that holds an instance when what the canvas paints for it, the effects in the symbol's art and the instance's own included, reaches the artboard. Not yet: other commands that measure objects, such as Select › All on Active Artboard, Transform Each and Convert to Artboards, still measure an instance by the square. Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
1 parent
21a386a6d4
commit
d9bd9b134d
42 files changed
+2728
-205
No files matched your search
@@ -169,7 +169,7 @@ fn doc_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc = &s.doc()?.doc;
|
||||
let n = doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
opts.compound_member = doc.parent_of(id).and_then(|p| doc.node(p)).is_some_and(|p| matches!(p.kind, vectorcraft_doc::NodeKind::Compound { .. }));
|
||||
if summary { Ok(inspect::node_summary_opts(n, opts)) } else { Ok(serde_json::to_value(n).unwrap_or(Value::Null)) }
|
||||
if summary { Ok(inspect::node_summary_opts(n, opts, &doc.symbol_boxes())) } else { Ok(serde_json::to_value(n).unwrap_or(Value::Null)) }
|
||||
}
|
||||
|
||||
/// `depth` / `childLimit` for a summary read: absent (or null) means no limit.
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, SymbolBoxes};
|
||||
|
||||
use crate::DocState;
|
||||
|
||||
@@ -92,21 +92,29 @@ fn selected_part(n: &Node, keep: &HashSet<NodeId>) -> Option<Node> {
|
||||
|
||||
/// `doc` with only the art over `rect` (an artboard): objects whose visual bounds miss it are left
|
||||
/// out, at any depth of layers and sublayers, and objects that reach it stay whole (the file's
|
||||
/// bounds clip them), as DXF's crop leaves them. A clipping layer keeps every object, its clipping
|
||||
/// path among them. An artboard's file then holds its own art, not a whole document of artboards.
|
||||
/// bounds clip them), as DXF's crop leaves them. Symbol instances are measured by their art, and
|
||||
/// the box of one whose art holds brushed strokes grows by as far as their brush art can paint
|
||||
/// ([`SymbolBoxes::with_brush_art`]). An object that holds a symbol instance also stays when what
|
||||
/// the canvas paints for it reaches `rect` ([`vectorcraft_render::painted_bounds`]: the effects in
|
||||
/// the symbols' art and its own effects). A clipping layer keeps every object, its clipping path
|
||||
/// among them. An artboard's file then holds its own art, not a whole document of artboards.
|
||||
pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect) -> Document {
|
||||
fn kept(n: &Arc<Node>, rect: vectorcraft_geom::Rect) -> Option<Arc<Node>> {
|
||||
fn kept(n: &Arc<Node>, doc: &Document, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect) -> Option<Arc<Node>> {
|
||||
if matches!(n.kind, NodeKind::Layer { clip: false, .. }) {
|
||||
let mut layer = Node::clone(n);
|
||||
let children = layer.children_mut()?;
|
||||
*children = children.iter().filter_map(|c| kept(c, rect)).collect();
|
||||
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect)).collect();
|
||||
return Some(Arc::new(layer));
|
||||
}
|
||||
let over = |b: vectorcraft_geom::Rect| b.x0 <= rect.x1 && rect.x0 <= b.x1 && b.y0 <= rect.y1 && rect.y0 <= b.y1;
|
||||
n.visual_bounds().is_none_or(over).then(|| n.clone())
|
||||
let mut holds_instance = false;
|
||||
n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. }));
|
||||
let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over);
|
||||
(n.visual_bounds_with(symbols).is_none_or(over) || painted()).then(|| n.clone())
|
||||
}
|
||||
let symbols = doc.symbol_boxes().with_brush_art();
|
||||
let mut d = doc.clone();
|
||||
d.layers = doc.layers.iter().filter_map(|l| kept(l, rect)).collect();
|
||||
d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect)).collect();
|
||||
d
|
||||
}
|
||||
|
||||
@@ -152,10 +160,12 @@ fn selection(s: &mut Session, cmd: &str) -> Result<(Document, vectorcraft_geom::
|
||||
}
|
||||
|
||||
/// Objects `ids` of `doc` alone on one layer (in that order, back to front), with one artboard
|
||||
/// named `name`: their visual bounds (`None` when they have none).
|
||||
/// named `name`: their visual bounds, symbol instances measured by their art (`None` when they
|
||||
/// have none).
|
||||
pub(crate) fn isolated(doc: &Document, ids: &[NodeId], name: &str) -> Option<(Document, vectorcraft_geom::Rect)> {
|
||||
let nodes: Vec<Arc<Node>> = ids.iter().filter_map(|id| doc.node(*id).cloned().map(Arc::new)).collect();
|
||||
let bounds = nodes.iter().filter_map(|n| n.visual_bounds()).reduce(|a, b| a.union(b))?;
|
||||
let symbols = doc.symbol_boxes();
|
||||
let bounds = nodes.iter().filter_map(|n| n.visual_bounds_with(&symbols)).reduce(|a, b| a.union(b))?;
|
||||
let mut d = single_artboard(doc, bounds, name);
|
||||
let mut layer = Node::layer(d.alloc_id(), name, vectorcraft_doc::LayerColor::Preset(0));
|
||||
if let Some(ch) = layer.children_mut() {
|
||||
|
||||
+349
-10
@@ -1406,9 +1406,17 @@ fn set_bounds(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let frame = d.oriented_bounds(&ids, false).ok_or_else(|| EngineError::Other("no bounds".into()))?;
|
||||
let g = frame.rect;
|
||||
// With Use Preview Bounds the values measure the visual box, whose margins around the
|
||||
// geometric box (left, top, right, bottom) scale with the strokes or stay.
|
||||
let v = if s.prefs.use_preview_bounds { d.oriented_bounds(&ids, true).map_or(g, |b| b.rect) } else { g };
|
||||
let m = [g.x0 - v.x0, g.y0 - v.y0, v.x1 - g.x1, v.y1 - g.y1];
|
||||
// geometric box (left, top, right, bottom) scale with the strokes or stay. The margins of
|
||||
// `vs`, the visual box without the strokes in symbols' art, scale; those strokes keep their
|
||||
// weight when an instance scales, so the rest of the margins stay.
|
||||
let (v, vs) = if s.prefs.use_preview_bounds {
|
||||
(d.oriented_bounds(&ids, true).map_or(g, |b| b.rect), scaling_box(d, &ids, &frame).unwrap_or(g))
|
||||
} else {
|
||||
(g, g)
|
||||
};
|
||||
let margins = |b: Rect| [g.x0 - b.x0, g.y0 - b.y0, b.x1 - g.x1, b.y1 - g.y1];
|
||||
let (m, all) = (margins(vs), margins(v));
|
||||
let fixed = [all[0] - m[0], all[1] - m[1], all[2] - m[2], all[3] - m[3]];
|
||||
let refi = p.get("reference").and_then(Value::as_u64).unwrap_or(4) as usize;
|
||||
let rp = vectorcraft_geom::reference_point(v, refi);
|
||||
let mut w = f64_or(p, "width", v.width());
|
||||
@@ -1420,20 +1428,33 @@ fn set_bounds(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
w = v.width() * h / v.height();
|
||||
}
|
||||
}
|
||||
// The geometric scale that gives the visual size: margins grow by the strokes' scale `f`
|
||||
// (exact for proportional scales, which scale the visual box alike).
|
||||
// The geometric scale that gives the visual size: margins grow by the strokes' scale `f`. It is
|
||||
// exact for proportional scales of one path; [`Spans::refit`] checks it, and solves for the
|
||||
// scales where it misses.
|
||||
let strokes = bool_or(p, "strokes", s.prefs.scale_strokes);
|
||||
let ratio = |size: f64, geo: f64, margin: f64| if geo > 1e-9 { (size - margin) / geo } else { 1.0 };
|
||||
let f = |sx: f64, sy: f64| if strokes { (sx * sy).abs().sqrt() } else { 1.0 };
|
||||
let (lx, ly) = (ratio(w, v.width(), 0.0), ratio(h, v.height(), 0.0));
|
||||
// The strokes' scale `f0`: the size left after the margins in symbols' art, which stay, over
|
||||
// `vs`, whose margins scale.
|
||||
let (lx, ly) = (ratio(w - fixed[0] - fixed[2], vs.width(), 0.0), ratio(h - fixed[1] - fixed[3], vs.height(), 0.0));
|
||||
let f0 = f(if g.width() > 1e-9 { lx } else { 1.0 }, if g.height() > 1e-9 { ly } else { 1.0 });
|
||||
let sx = ratio(w, g.width(), (m[0] + m[2]) * f0);
|
||||
let sy = ratio(h, g.height(), (m[1] + m[3]) * f0);
|
||||
// When a size of 0 or more is smaller than the margins and some of them stay, the geometry
|
||||
// gets no width or height: the visual box is then as small as it can be. The margins in
|
||||
// symbols' art stay, and so does every margin when strokes do not scale.
|
||||
let fit = |size: f64, geo: f64, scaling: f64, kept: f64| {
|
||||
let s = ratio(size, geo, scaling * f0 + kept);
|
||||
let stays = if strokes { kept } else { scaling + kept };
|
||||
if s < 0.0 && size >= 0.0 && stays > 0.0 { 0.0 } else { s }
|
||||
};
|
||||
let sx = fit(w, g.width(), m[0] + m[2], fixed[0] + fixed[2]);
|
||||
let sy = fit(h, g.height(), m[1] + m[3], fixed[1] + fixed[3]);
|
||||
let scale = about(rp, Affine::scale_non_uniform(sx, sy));
|
||||
// Move the new visual box's reference point to x, y (default: where it was): the geometric
|
||||
// box's reference point moves with the art, the margin from it to the visual one by `f`.
|
||||
// box's reference point moves with the art, the margin from it to `vs`'s by `f`, and the
|
||||
// margin from that one to the visual box's stays.
|
||||
let gp = vectorcraft_geom::reference_point(g, refi);
|
||||
let new_rp = scale * gp + (rp - gp) * f(sx, sy);
|
||||
let sp = vectorcraft_geom::reference_point(vs, refi);
|
||||
let new_rp = scale * gp + (sp - gp) * f(sx, sy) + (rp - sp);
|
||||
// x, y place the reference point on the page.
|
||||
let page = frame.to_doc() * rp;
|
||||
// When every value given is the current one, the transform is the identity. Computing it can
|
||||
@@ -1443,9 +1464,327 @@ fn set_bounds(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return apply_transform(s, "Transform", ids, Affine::IDENTITY, p, false);
|
||||
}
|
||||
let to = frame.to_local(Point::new(f64_or(p, "x", page.x), f64_or(p, "y", page.y)));
|
||||
// The scales and the point above can miss the size or the reference point when the margins of
|
||||
// the objects differ, the members of groups and the objects in symbols' art included, and with
|
||||
// strokes that scale, when the sizes are out of proportion. The objects are then measured one
|
||||
// by one ([`Spans::measure`]), and the scales solved for.
|
||||
let solved = if s.prefs.use_preview_bounds && w >= 0.0 && h >= 0.0 {
|
||||
Spans::measure(d, &ids, &frame, strokes).refit(rp, refi, [w, h], (sx, sy, new_rp))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (scale, new_rp) = solved.map_or((scale, new_rp), |(sx, sy, at)| (about(rp, Affine::scale_non_uniform(sx, sy)), at));
|
||||
apply_transform(s, "Transform", ids, frame.conjugate(Affine::translate(to - new_rp) * scale), p, false)
|
||||
}
|
||||
|
||||
/// The visual box of `ids` square to `frame`, as [`Document::oriented_bounds`] measures it, with
|
||||
/// symbol instances measured without the strokes in their art
|
||||
/// ([`vectorcraft_doc::SymbolBoxes::without_art_strokes`]).
|
||||
fn scaling_box(d: &Document, ids: &[NodeId], frame: &OrientedBox) -> Option<Rect> {
|
||||
let symbols = d.symbol_boxes().without_art_strokes();
|
||||
let to_local = frame.to_doc().inverse();
|
||||
ids.iter().filter_map(|id| d.node(*id)).fold(None, |acc, n| {
|
||||
let b = if frame.angle == 0.0 { n.visual_bounds_with(&symbols) } else { n.bounds_in(&symbols, to_local, true) };
|
||||
vectorcraft_geom::union_opt(acc, b)
|
||||
})
|
||||
}
|
||||
|
||||
/// One axis of an object that [`set_bounds`] sizes, square to its frame: the geometric box runs
|
||||
/// from `lo` to `hi`, and the visual box reaches past each end (before, after) by a margin that
|
||||
/// scales with the strokes and one that stays.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Span {
|
||||
lo: f64,
|
||||
hi: f64,
|
||||
scaling: [f64; 2],
|
||||
kept: [f64; 2],
|
||||
}
|
||||
|
||||
impl Span {
|
||||
/// The ends of the visual box after a scale by `s` about `c`, with the margins that scale
|
||||
/// grown by `k`. A negative scale turns the box over, and its margins with it.
|
||||
fn scaled(self, c: f64, s: f64, k: f64) -> (f64, f64) {
|
||||
let ([sb, sa], [kb, ka]) = (self.scaling, self.kept);
|
||||
let (before, after) = (sb * k + kb, sa * k + ka);
|
||||
let (a, b) = (c + s * (self.lo - c), c + s * (self.hi - c));
|
||||
if s < 0.0 { (b - after, a + before) } else { (a - before, b + after) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects that [`set_bounds`] sizes, measured one by one square to its frame.
|
||||
struct Spans {
|
||||
x: Vec<Span>,
|
||||
y: Vec<Span>,
|
||||
/// Whether strokes scale. The margins that scale grow by the square root of the product of the
|
||||
/// two scales; with strokes that do not scale, every margin stays.
|
||||
strokes: bool,
|
||||
}
|
||||
|
||||
impl Spans {
|
||||
/// The objects of `ids` that have a box, measured one by one as [`Document::oriented_bounds`]
|
||||
/// measures them square to `frame`, each plain group member by member and each symbol instance
|
||||
/// that [`open`] opens object by object in its art. Past [`MAX_SPANS`] parts, each object of
|
||||
/// `ids` is measured as one. The margins of the visual box without the strokes in symbols' art
|
||||
/// ([`scaling_box`]) scale with the strokes, and the rest stay. With `strokes` false, every
|
||||
/// margin stays.
|
||||
fn measure(d: &Document, ids: &[NodeId], frame: &OrientedBox, strokes: bool) -> Self {
|
||||
let (symbols, without, art) = (d.symbol_boxes(), d.symbol_boxes().without_art_strokes(), d.symbol_boxes().quick());
|
||||
let to_local = frame.to_doc().inverse();
|
||||
let measure = |n: &Node, s: &vectorcraft_doc::SymbolBoxes, visual: bool| match (frame.angle == 0.0, visual) {
|
||||
(true, false) => n.geometric_bounds_with(s),
|
||||
(true, true) => n.visual_bounds_with(s),
|
||||
(false, _) => n.bounds_in(s, to_local, visual),
|
||||
};
|
||||
let roots: Vec<&Node> = ids.iter().filter_map(|id| d.node(*id)).collect();
|
||||
let mut parts = vec![];
|
||||
if !roots.iter().all(|n| open(n, 0.0, d, &symbols, to_local, &mut parts)) {
|
||||
parts = roots.iter().map(|n| Part::Object(n, 0.0)).collect();
|
||||
}
|
||||
let mut out = Self { x: vec![], y: vec![], strokes };
|
||||
for part in parts {
|
||||
let (g, v, vs) = match part {
|
||||
Part::Object(n, grow) => {
|
||||
let Some(g) = measure(n, &symbols, false) else { continue };
|
||||
let v = measure(n, &symbols, true).unwrap_or(g).inflate(grow, grow);
|
||||
let vs = if strokes { measure(n, &without, true).unwrap_or(g).inflate(grow, grow) } else { g };
|
||||
(g, v, vs)
|
||||
}
|
||||
// Measured as the instance's own box measures its art (`Node::visual_bounds_with`):
|
||||
// the strokes at their own weight, and the instances in it by their art boxes.
|
||||
Part::Art(n, xf, grow, kept) => {
|
||||
let mut placed = n.clone();
|
||||
placed.transform(xf, false);
|
||||
let Some(g) = placed.geometric_bounds_with(&art) else { continue };
|
||||
let v = placed.visual_bounds_with(&art).map_or(g, |v| v.union(g)).inflate(kept + grow, kept + grow);
|
||||
let vs = if strokes { g.inflate(grow, grow) } else { g };
|
||||
(g, v, vs)
|
||||
}
|
||||
};
|
||||
out.x.push(Span { lo: g.x0, hi: g.x1, scaling: [g.x0 - vs.x0, vs.x1 - g.x1], kept: [vs.x0 - v.x0, v.x1 - vs.x1] });
|
||||
out.y.push(Span { lo: g.y0, hi: g.y1, scaling: [g.y0 - vs.y0, vs.y1 - g.y1], kept: [vs.y0 - v.y0, v.y1 - vs.y1] });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The visual box after a scale by `sx`, `sy` about `c`.
|
||||
fn visual(&self, c: Point, sx: f64, sy: f64) -> Option<Rect> {
|
||||
let k = if self.strokes { (sx * sy).abs().sqrt() } else { 1.0 };
|
||||
let boxes = self.x.iter().zip(&self.y).map(|(x, y)| {
|
||||
let ((x0, x1), (y0, y1)) = (x.scaled(c.x, sx, k), y.scaled(c.y, sy, k));
|
||||
Rect::new(x0, y0, x1, y1)
|
||||
});
|
||||
boxes.reduce(|a, b| a.union(b))
|
||||
}
|
||||
|
||||
/// The scales along x and y that give the visual box the size `size` with a scale about `c`,
|
||||
/// or come as near to it as the margins that stay allow ([`Self::solve`]), and the point that
|
||||
/// goes to the reference point's place: point `refi` of the visual box they give. Returns
|
||||
/// `None`, which keeps `closed` (the scales and the point of [`set_bounds`]'s closed form), when
|
||||
/// the scales of `closed` put point `refi` at the point of `closed` and either give the size
|
||||
/// `size` or are the scales [`Self::solve`] finds, to within rounding (1e-12 of the largest
|
||||
/// value compared, or of 1).
|
||||
fn refit(&self, c: Point, refi: usize, size: [f64; 2], closed: (f64, f64, Point)) -> Option<(f64, f64, Point)> {
|
||||
let ([w, h], (sx, sy, at)) = (size, closed);
|
||||
let b = self.visual(c, sx, sy)?;
|
||||
let p = vectorcraft_geom::reference_point(b, refi);
|
||||
let tolerance = 1e-12 * [b.x0, b.y0, b.x1, b.y1, w, h, at.x, at.y].iter().fold(1.0, |m: f64, v| m.max(v.abs()));
|
||||
let near = |a: f64, b: f64| (a - b).abs() <= tolerance;
|
||||
let placed = near(p.x, at.x) && near(p.y, at.y);
|
||||
if placed && near(b.width(), w) && near(b.height(), h) {
|
||||
return None;
|
||||
}
|
||||
let (tx, ty) = self.solve(w, h);
|
||||
let same = |a: f64, b: f64| (a - b).abs() <= 1e-12 * a.abs().max(b.abs()).max(1.0);
|
||||
if placed && same(tx, sx) && same(ty, sy) {
|
||||
return None;
|
||||
}
|
||||
let b = self.visual(c, tx, ty)?;
|
||||
Some((tx, ty, vectorcraft_geom::reference_point(b, refi)))
|
||||
}
|
||||
|
||||
/// The scales of 0 or more along x and y that give the visual box the size `w` × `h`, each
|
||||
/// found by [`scale_across`]. With strokes that scale, the margins that scale grow by `k`,
|
||||
/// found where it is the square root of the product of the two scales.
|
||||
fn solve(&self, w: f64, h: f64) -> (f64, f64) {
|
||||
let at = |k: f64| (scale_across(&self.x, k, w), scale_across(&self.y, k, h));
|
||||
if !self.strokes {
|
||||
return at(1.0);
|
||||
}
|
||||
// The scales get smaller as `k` grows, so the square root of their product minus `k` is at
|
||||
// least 0 at `k` 0 and at most 0 at `k` equal to that root. Bisection finds the `k` between
|
||||
// the two where it is 0.
|
||||
let (sx, sy) = at(0.0);
|
||||
let (mut lo, mut hi) = (0.0, (sx * sy).sqrt());
|
||||
if hi.is_nan() || hi <= 0.0 {
|
||||
return (sx, sy);
|
||||
}
|
||||
for _ in 0..200 {
|
||||
let mid = lo + (hi - lo) / 2.0;
|
||||
if mid <= lo || mid >= hi {
|
||||
break;
|
||||
}
|
||||
let (sx, sy) = at(mid);
|
||||
if (sx * sy).sqrt() > mid {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
let miss = |k: f64| {
|
||||
let (sx, sy) = at(k);
|
||||
((sx * sy).sqrt() - k).abs()
|
||||
};
|
||||
at(if miss(lo) < miss(hi) { lo } else { hi })
|
||||
}
|
||||
}
|
||||
|
||||
/// Most parts [`Spans::measure`] opens the objects it sizes into: past it, each object is one part.
|
||||
const MAX_SPANS: usize = 4096;
|
||||
|
||||
/// What [`Spans::measure`] measures as one span.
|
||||
enum Part<'a> {
|
||||
/// An object of the selection, or a member of a plain group in it, and the outset of the
|
||||
/// strokes of the plain groups around it, which scale with its own.
|
||||
Object(&'a Node, f64),
|
||||
/// An object in the art of a symbol instance and the transform that places it square to the
|
||||
/// frame. The outset of the strokes of the instance and of the plain groups around the instance
|
||||
/// scales with the strokes; the outset of the strokes of the plain groups around the object in
|
||||
/// the art stays, as the strokes in the art do.
|
||||
Art(&'a Node, Affine, f64, f64),
|
||||
}
|
||||
|
||||
/// Adds the parts that [`Spans::measure`] measures `n` by to `parts`, `grow` being the outset of
|
||||
/// the strokes of the plain groups around it ([`Part::Object`]). A plain group ([`opens`]) adds the
|
||||
/// parts of each member. A symbol instance without effects or an opacity mask of its own adds the
|
||||
/// objects of its art, with plain groups there opened too ([`Part::Art`]), when its symbol's art
|
||||
/// measures it, it is not in perspective, and its transform keeps the art square to the frame (a
|
||||
/// turned or slanted instance is measured by the box around its turned art box). Anything else is
|
||||
/// one part. Returns false when the parts pass [`MAX_SPANS`].
|
||||
fn open<'a>(n: &'a Node, grow: f64, d: &'a Document, symbols: &vectorcraft_doc::SymbolBoxes, to_local: Affine, parts: &mut Vec<Part<'a>>) -> bool {
|
||||
if opens(n) {
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } => {
|
||||
let grow = grow + n.appearance.outset();
|
||||
return children.iter().all(|c| open(c, grow, d, symbols, to_local, parts));
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let xf = to_local * *xf;
|
||||
if n.projection().is_none()
|
||||
&& square(xf)
|
||||
&& symbols.art_bounds(symbol).is_some()
|
||||
&& let Some(art) = d.symbols.iter().find(|s| s.name == *symbol)
|
||||
{
|
||||
return open_art(&art.art, xf, grow + n.appearance.outset(), 0.0, parts);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
parts.push(Part::Object(n, grow));
|
||||
parts.len() <= MAX_SPANS
|
||||
}
|
||||
|
||||
/// [`open`] for `n` in symbol art that `xf` places square to the frame: a plain group adds the parts
|
||||
/// of each member, and anything else, a symbol instance included, is one part. `kept` is the outset
|
||||
/// of the strokes of the plain groups around `n` in the art, and `grow` that of the instance and the
|
||||
/// plain groups around it.
|
||||
fn open_art<'a>(n: &'a Node, xf: Affine, grow: f64, kept: f64, parts: &mut Vec<Part<'a>>) -> bool {
|
||||
if let NodeKind::Group { children, .. } = &n.kind
|
||||
&& opens(n)
|
||||
{
|
||||
let kept = kept + n.appearance.outset();
|
||||
return children.iter().all(|c| open_art(c, xf, grow, kept, parts));
|
||||
}
|
||||
parts.push(Part::Art(n, xf, grow, kept));
|
||||
parts.len() <= MAX_SPANS
|
||||
}
|
||||
|
||||
/// Whether [`open`] opens `n`: a group without a clip, a Shaper construction, effects or an opacity
|
||||
/// mask of its own, or a symbol instance without effects or an opacity mask of its own.
|
||||
fn opens(n: &Node) -> bool {
|
||||
let visible = |effects: &[vectorcraft_doc::Effect]| effects.iter().any(|e| e.visible);
|
||||
let effects = visible(&n.appearance.effects) || n.appearance.items.iter().any(|i| visible(i.effects()));
|
||||
let kind = match n.kind {
|
||||
NodeKind::Group { clip, .. } => !clip && n.extras().shaper.is_none(),
|
||||
NodeKind::SymbolInstance { .. } => true,
|
||||
_ => false,
|
||||
};
|
||||
kind && !effects && n.extras().mask.is_none()
|
||||
}
|
||||
|
||||
/// Whether `a` takes boxes square to the frame to boxes square to it: it scales, mirrors, turns by a
|
||||
/// quarter turn and moves, and nothing else, to within rounding.
|
||||
fn square(a: Affine) -> bool {
|
||||
let [m0, m1, m2, m3, ..] = a.as_coeffs();
|
||||
let tolerance = 1e-9 * [m0, m1, m2, m3].iter().fold(0.0, |m: f64, v| m.max(v.abs()));
|
||||
m1.abs() <= tolerance && m2.abs() <= tolerance || m0.abs() <= tolerance && m3.abs() <= tolerance
|
||||
}
|
||||
|
||||
/// The largest scale of 0 or more at which `spans`, with the margins that scale grown by `k`,
|
||||
/// reach across `size` together. Returns 1 when their geometric boxes reach 1e-9 or less across
|
||||
/// together, as the closed form in [`set_bounds`] does, and 0 when the spans reach farther than
|
||||
/// `size` at the scale 0.
|
||||
fn scale_across(spans: &[Span], k: f64, size: f64) -> f64 {
|
||||
let o = spans.iter().map(|s| s.lo).fold(f64::INFINITY, f64::min);
|
||||
let across = spans.iter().map(|s| s.hi).fold(f64::NEG_INFINITY, f64::max) - o;
|
||||
// How far the spans reach together after a scale by `s` about `o`, and how fast that changes
|
||||
// with `s`: the far geometric end minus the near one, of the objects that reach farthest at the
|
||||
// two ends.
|
||||
let reach = |s: f64| {
|
||||
let (mut start, mut end, mut slope_start, mut slope_end) = (f64::INFINITY, f64::NEG_INFINITY, 0.0, 0.0);
|
||||
for sp in spans {
|
||||
let (a, b) = sp.scaled(o, s, k);
|
||||
if a < start {
|
||||
(start, slope_start) = (a, sp.lo - o);
|
||||
}
|
||||
if b > end {
|
||||
(end, slope_end) = (b, sp.hi - o);
|
||||
}
|
||||
}
|
||||
(end - start, slope_end - slope_start)
|
||||
};
|
||||
if across.is_nan() || across <= 1e-9 {
|
||||
return 1.0;
|
||||
}
|
||||
let least = reach(0.0).0;
|
||||
if least.is_nan() || least > size {
|
||||
return 0.0;
|
||||
}
|
||||
// `reach` is convex in `s` and at most `size` at 0, so it equals `size` at one largest scale.
|
||||
// Newton's method, started at a larger scale, reaches it one linear piece of `reach` at a
|
||||
// time; bisection finishes the search when a step makes no progress.
|
||||
let (mut lo, mut hi) = (0.0, size / across);
|
||||
for _ in 0..64 {
|
||||
if reach(hi).0 >= size {
|
||||
break;
|
||||
}
|
||||
hi = 2.0 * hi + 1.0;
|
||||
}
|
||||
for _ in 0..64 {
|
||||
let (r, slope) = reach(hi);
|
||||
if r <= size {
|
||||
return hi;
|
||||
}
|
||||
let next = hi - (r - size) / slope;
|
||||
if next.is_nan() || next <= lo || next >= hi {
|
||||
break;
|
||||
}
|
||||
hi = next;
|
||||
}
|
||||
for _ in 0..64 {
|
||||
let mid = lo + (hi - lo) / 2.0;
|
||||
if mid <= lo || mid >= hi {
|
||||
break;
|
||||
}
|
||||
if reach(mid).0 <= size {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
if size - reach(lo).0 <= reach(hi).0 - size { lo } else { hi }
|
||||
}
|
||||
|
||||
fn expand_shape(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let ids = selected_roots(s)?;
|
||||
// With no live shape selected, the document and its undo history stay as they are.
|
||||
|
||||
@@ -173,7 +173,7 @@ pub(crate) fn effects_scale(doc: &Document) -> f64 {
|
||||
pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option<Node> {
|
||||
// What it paints (its members' effects included), and how far its fills' and strokes' raster
|
||||
// effects reach beyond that.
|
||||
let b = vectorcraft_render::painted_bounds(whole)?;
|
||||
let b = vectorcraft_render::painted_bounds(out, whole)?;
|
||||
let look = out.raster_effects.clone();
|
||||
let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + look.add_around;
|
||||
let b = b.inflate(reach, reach);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_doc::{ArrowAlign, Document, LineCap, LineJoin, Node, NodeKind, StrokeAlign, StrokeLayer, WidthProfile};
|
||||
use vectorcraft_doc::{ArrowAlign, Document, LineCap, LineJoin, Node, NodeKind, StrokeAlign, StrokeLayer, SymbolBoxes, WidthProfile};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
@@ -26,20 +26,21 @@ pub struct SummaryOpts {
|
||||
pub compound_member: bool,
|
||||
}
|
||||
|
||||
/// Compact tree summary of a node (for `document.inspect`): the whole subtree.
|
||||
pub fn node_summary(n: &Node) -> Value {
|
||||
node_summary_opts(n, SummaryOpts::default())
|
||||
/// Compact tree summary of a node (for `document.inspect`): the whole subtree, symbol instances
|
||||
/// measured by their art from `symbols`.
|
||||
pub fn node_summary(n: &Node, symbols: &SymbolBoxes) -> Value {
|
||||
node_summary_opts(n, SummaryOpts::default(), symbols)
|
||||
}
|
||||
|
||||
/// The same summary with [`SummaryOpts`] applied.
|
||||
pub fn node_summary_opts(n: &Node, opts: SummaryOpts) -> Value {
|
||||
pub fn node_summary_opts(n: &Node, opts: SummaryOpts, symbols: &SymbolBoxes) -> Value {
|
||||
let mut v = json!({
|
||||
"id": n.id.0,
|
||||
"name": n.display_name(),
|
||||
"kind": n.kind_label(),
|
||||
"visible": n.visible,
|
||||
"locked": n.locked,
|
||||
"bounds": rect_json(n.geometric_bounds()),
|
||||
"bounds": rect_json(n.geometric_bounds_with(symbols)),
|
||||
});
|
||||
if n.opacity < 1.0 {
|
||||
v["opacity"] = json!(n.opacity);
|
||||
@@ -114,7 +115,7 @@ pub fn node_summary_opts(n: &Node, opts: SummaryOpts) -> Value {
|
||||
child_limit: opts.child_limit,
|
||||
compound_member: matches!(n.kind, NodeKind::Compound { .. }),
|
||||
};
|
||||
v["children"] = Value::Array(ch.iter().rev().take(take_n).map(|c| node_summary_opts(c, next)).collect());
|
||||
v["children"] = Value::Array(ch.iter().rev().take(take_n).map(|c| node_summary_opts(c, next, symbols)).collect());
|
||||
}
|
||||
if take_n < total || v.get("children").is_none() {
|
||||
v["childCount"] = json!(total);
|
||||
@@ -132,6 +133,7 @@ pub fn document(s: &Session) -> Value {
|
||||
pub fn document_opts(s: &Session, opts: SummaryOpts) -> Value {
|
||||
let Some(st) = s.active() else { return Value::Null };
|
||||
let d = &st.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
json!({
|
||||
"title": st.title(),
|
||||
"path": st.path,
|
||||
@@ -141,7 +143,7 @@ pub fn document_opts(s: &Session, opts: SummaryOpts) -> Value {
|
||||
"colorMode": format!("{:?}", d.color_mode),
|
||||
"artboards": d.artboards.iter().map(|a| json!({"name": a.name, "x": a.rect.x0, "y": a.rect.y0, "width": a.rect.width(), "height": a.rect.height()})).collect::<Vec<_>>(),
|
||||
// Top of the stack first, like the Layers panel.
|
||||
"layers": d.layers.iter().rev().map(|l| node_summary_opts(l, opts)).collect::<Vec<_>>(),
|
||||
"layers": d.layers.iter().rev().map(|l| node_summary_opts(l, opts, &symbols)).collect::<Vec<_>>(),
|
||||
"currentLayer": st.active_layer.map(|l| l.0),
|
||||
// The rows highlighted in the Layers panel (`layer.setCurrent`, `layer.highlight`).
|
||||
"layerRows": st.highlighted_rows().iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
|
||||
@@ -1949,6 +1949,8 @@ mod tests_swatches;
|
||||
#[cfg(test)]
|
||||
mod tests_swatchlib;
|
||||
#[cfg(test)]
|
||||
mod tests_symbolbounds;
|
||||
#[cfg(test)]
|
||||
mod tests_targeting;
|
||||
#[cfg(test)]
|
||||
mod tests_textcombos;
|
||||
|
||||
@@ -98,6 +98,248 @@ fn the_w_field_sets_the_visual_width() {
|
||||
assert!((geometric(&s, id).x0 - 5.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_size_below_what_a_kept_stroke_adds_gives_the_path_no_width_or_height() {
|
||||
// The 10 pt stroke adds 10 pt to the width and the height. With strokes kept, a width or height
|
||||
// of 0 or more below 10 pt gives the path no width or height, and the visual box is the
|
||||
// stroke's 10 pt: the path does not turn over. A size of 10 pt or more scales the path to it,
|
||||
// and a negative size turns the path over.
|
||||
let mut wrong = vec![];
|
||||
for (key, size, path, visual) in [
|
||||
("width", 5.0, 0.0, 10.0),
|
||||
("width", 0.0, 0.0, 10.0),
|
||||
("width", 10.0, 0.0, 10.0),
|
||||
("width", 30.0, 20.0, 30.0),
|
||||
("width", -10.0, 20.0, 30.0),
|
||||
("height", 5.0, 0.0, 10.0),
|
||||
("height", 0.0, 0.0, 10.0),
|
||||
("height", 10.0, 0.0, 10.0),
|
||||
("height", 30.0, 20.0, 30.0),
|
||||
("height", -10.0, 20.0, 30.0),
|
||||
] {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 100.0, 10.0);
|
||||
preview(&mut s, true);
|
||||
run(&mut s, "object.setBounds", json!({key: size, "reference": 0, "strokes": false}));
|
||||
let (g, v) = (geometric(&s, id), s.transform_bounds(&[id]).unwrap());
|
||||
let (g, v) = if key == "width" { (g.width(), v.width()) } else { (g.height(), v.height()) };
|
||||
if (g - path).abs() > 1e-9 || (v - visual).abs() > 1e-9 {
|
||||
wrong.push(format!("{key} {size}: path {g}, visual box {v}"));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_gives_one_path_sizes_out_of_proportion_when_strokes_scale() {
|
||||
// The 100 × 50 rectangle with a 10 pt stroke: its visual box runs from (95, 95) to (205, 155).
|
||||
// The stroke scales by the square root of the product of the two scales, so the width it adds
|
||||
// depends on the height too. Set from the top-left corner, the visual box is 220 × 60, and
|
||||
// 5 × 1000 with the path the same way round.
|
||||
let mut wrong = vec![];
|
||||
for (width, height) in [(220.0, 60.0), (5.0, 1000.0)] {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 100.0, 10.0);
|
||||
preview(&mut s, true);
|
||||
run(&mut s, "object.setBounds", json!({"width": width, "height": height, "reference": 0, "strokes": true}));
|
||||
let v = s.transform_bounds(&[id]).unwrap();
|
||||
let Some(vectorcraft_doc::LiveShape::Rectangle { xf, .. }) = s.doc().unwrap().doc.node(id).unwrap().live_shape() else {
|
||||
panic!("the rectangle")
|
||||
};
|
||||
if !close(v, Rect::new(95.0, 95.0, 95.0 + width, 95.0 + height)) || xf.as_coeffs()[0] <= 0.0 {
|
||||
wrong.push(format!("{width} × {height}: {v:?}, {xf:?}"));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:?}");
|
||||
}
|
||||
|
||||
fn close(a: Rect, b: Rect) -> bool {
|
||||
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-9)
|
||||
}
|
||||
|
||||
/// Two rectangles 50 pt high at y 100, both selected with Use Preview Bounds on: one from x 0 to
|
||||
/// 10 with a 2 pt stroke, which sets the left edge of the paths, and one from x 3 to 10 with a
|
||||
/// 10 pt stroke, which sets every edge of the visual box, (-2, 95) to (15, 155).
|
||||
fn thin_and_thick() -> (Session, [NodeId; 2]) {
|
||||
let mut s = session();
|
||||
let ids = [rect(&mut s, 0.0, 10.0, 2.0), rect(&mut s, 3.0, 7.0, 10.0)];
|
||||
preview(&mut s, true);
|
||||
run(&mut s, "select.set", json!({"ids": [ids[0].0, ids[1].0]}));
|
||||
assert!(close(s.transform_bounds(&ids).unwrap(), Rect::new(-2.0, 95.0, 15.0, 155.0)));
|
||||
(s, ids)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_measures_the_margins_on_each_side_object_by_object() {
|
||||
// Set to 37 wide from the left edge with strokes kept, the paths scale by 3.1, and the left edge
|
||||
// of the visual box stays at -2.
|
||||
let (mut s, ids) = thin_and_thick();
|
||||
run(&mut s, "object.setBounds", json!({"width": 37, "reference": 0, "strokes": false}));
|
||||
let v = s.transform_bounds(&ids).unwrap();
|
||||
assert!(close(v, Rect::new(-2.0, 95.0, 35.0, 155.0)), "{v:?}");
|
||||
assert!(close(geometric(&s, ids[0]), Rect::new(-1.0, 100.0, 30.0, 150.0)), "{:?}", geometric(&s, ids[0]));
|
||||
assert!(close(geometric(&s, ids[1]), Rect::new(8.3, 100.0, 30.0, 150.0)), "{:?}", geometric(&s, ids[1]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_scales_both_ways_at_once_when_strokes_scale_and_the_sizes_are_out_of_proportion() {
|
||||
// Each stroke scales by the square root of the product of the two scales, so the width it
|
||||
// adds depends on the height too. The visual box is 40 × 100.
|
||||
let (mut s, ids) = thin_and_thick();
|
||||
run(&mut s, "object.setBounds", json!({"width": 40, "height": 100, "reference": 0, "strokes": true}));
|
||||
let v = s.transform_bounds(&ids).unwrap();
|
||||
assert!(close(v, Rect::new(-2.0, 95.0, 38.0, 195.0)), "{v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_measures_paths_turned_together_square_to_their_box() {
|
||||
// Turned 30° together, the paths are measured square to their turned box: it is 37 wide, and
|
||||
// its top-left corner stays where it was.
|
||||
let (mut s, ids) = thin_and_thick();
|
||||
run(&mut s, "object.rotate", json!({"angle": 30}));
|
||||
let before = s.transform_box(&ids).unwrap();
|
||||
run(&mut s, "object.setBounds", json!({"width": 37, "reference": 0, "strokes": false}));
|
||||
let after = s.transform_box(&ids).unwrap();
|
||||
assert!((after.angle - 30.0).abs() < 1e-9 && (after.rect.width() - 37.0).abs() < 1e-9, "{after:?}");
|
||||
assert!((after.rect.height() - 60.0).abs() < 1e-9, "{after:?}");
|
||||
assert!(after.reference_point(0).distance(before.reference_point(0)) < 1e-9, "{before:?} {after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_size_below_what_the_kept_strokes_of_several_paths_add_gives_them_no_width() {
|
||||
// With no width, the paths have a visual box 10 pt wide, the width of the thick stroke. A width
|
||||
// of 0 or more below 10 gives both paths no width, and the left edge of the visual box stays at
|
||||
// -2. A negative width turns the paths over, as it does one path.
|
||||
let mut wrong = vec![];
|
||||
for (width, paths, visual) in [
|
||||
(8.0, [Rect::new(3.0, 100.0, 3.0, 150.0); 2], Rect::new(-2.0, 95.0, 8.0, 155.0)),
|
||||
(0.0, [Rect::new(3.0, 100.0, 3.0, 150.0); 2], Rect::new(-2.0, 95.0, 8.0, 155.0)),
|
||||
(-37.0, [Rect::new(-44.0, 100.0, 0.0, 150.0), Rect::new(-44.0, 100.0, -13.2, 150.0)], Rect::new(-49.0, 95.0, 1.0, 155.0)),
|
||||
] {
|
||||
let (mut s, ids) = thin_and_thick();
|
||||
run(&mut s, "object.setBounds", json!({"width": width, "reference": 0, "strokes": false}));
|
||||
let (g, v) = (ids.map(|id| geometric(&s, id)), s.transform_bounds(&ids).unwrap());
|
||||
if !close(g[0], paths[0]) || !close(g[1], paths[1]) || !close(v, visual) {
|
||||
wrong.push(format!("width {width}: paths {g:?}, visual box {v:?}"));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_leaves_the_height_of_lines_with_no_height() {
|
||||
// Horizontal lines at y 100 with square caps, from x 0 to 10 with a 2 pt stroke and from x 3 to
|
||||
// 10 with a 10 pt stroke: the visual box is (-2, 95) to (15, 105). They have no height to
|
||||
// scale, so the height stays 10; the width becomes 37 from the left edge.
|
||||
let mut s = session();
|
||||
let mut ids = vec![];
|
||||
for (x, weight) in [(0.0, 2.0), (3.0, 10.0)] {
|
||||
ids.push(NodeId(run(&mut s, "shape.line", json!({"x1": x, "y1": 100, "x2": 10, "y2": 100}))["id"].as_u64().unwrap()));
|
||||
run(&mut s, "stroke.set", json!({"weight": weight, "cap": "square"}));
|
||||
}
|
||||
preview(&mut s, true);
|
||||
run(&mut s, "select.set", json!({"ids": [ids[0].0, ids[1].0]}));
|
||||
assert!(close(s.transform_bounds(&ids).unwrap(), Rect::new(-2.0, 95.0, 15.0, 105.0)), "{:?}", s.transform_bounds(&ids));
|
||||
run(&mut s, "object.setBounds", json!({"width": 37, "height": 30, "reference": 0, "strokes": false}));
|
||||
let v = s.transform_bounds(&ids).unwrap();
|
||||
assert!(close(v, Rect::new(-2.0, 95.0, 35.0, 105.0)), "{v:?}");
|
||||
assert!(close(geometric(&s, ids[1]), Rect::new(8.3, 100.0, 30.0, 100.0)), "{:?}", geometric(&s, ids[1]));
|
||||
}
|
||||
|
||||
/// The rectangles of [`thin_and_thick`] in a group, the thick one in a group of its own inside it
|
||||
/// when `nested`, selected with an unstroked rectangle from x 100 to 110 when `plain`. Returns the
|
||||
/// selected objects.
|
||||
fn grouped(nested: bool, plain: bool) -> (Session, Vec<NodeId>) {
|
||||
let (mut s, [thin, thick]) = thin_and_thick();
|
||||
let mut members = vec![thin.0, thick.0];
|
||||
if nested {
|
||||
run(&mut s, "select.set", json!({"ids": [thick.0]}));
|
||||
members[1] = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap();
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": members}));
|
||||
let mut ids = vec![NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap())];
|
||||
if plain {
|
||||
ids.push(rect(&mut s, 100.0, 10.0, 0.0));
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}));
|
||||
(s, ids)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_measures_the_members_of_groups_one_by_one() {
|
||||
// With the unstroked rectangle, the visual box runs from (-2, 95) to (110, 155). Set to 224 wide
|
||||
// from its left edge, it is 224 wide and its left edge stays at -2, with strokes kept or
|
||||
// scaling, and with the thick rectangle in a group of its own. The group alone, (-2, 95) to
|
||||
// (15, 155), set to 37 wide is 37 wide.
|
||||
let mut wrong = vec![];
|
||||
for (nested, plain, width, strokes) in
|
||||
[(false, true, 224.0, false), (false, true, 224.0, true), (true, true, 224.0, false), (false, false, 37.0, false)]
|
||||
{
|
||||
let (mut s, ids) = grouped(nested, plain);
|
||||
run(&mut s, "object.setBounds", json!({"width": width, "reference": 0, "strokes": strokes}));
|
||||
let v = s.transform_bounds(&ids).unwrap();
|
||||
if !close(v, Rect::new(-2.0, 95.0, width - 2.0, 155.0)) {
|
||||
wrong.push(format!("nested {nested}, plain {plain}, strokes {strokes}: {v:?}"));
|
||||
}
|
||||
}
|
||||
// The group with a 1 pt stroke of its own, which reaches 5 pt at its miter limit of 10, around
|
||||
// each member: the visual box runs from (-7, 90) to (110, 160). Set to 224 wide from its left
|
||||
// edge, it is 224 wide and its left edge stays at -7, with strokes kept or scaling.
|
||||
for strokes in [false, true] {
|
||||
let (mut s, _) = thin_and_thick();
|
||||
let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "appearance.addStroke", json!({"ids": [group.0]}));
|
||||
let ids = [group, rect(&mut s, 100.0, 10.0, 0.0)];
|
||||
run(&mut s, "select.set", json!({"ids": [ids[0].0, ids[1].0]}));
|
||||
assert!(close(s.transform_bounds(&ids).unwrap(), Rect::new(-7.0, 90.0, 110.0, 160.0)), "{:?}", s.transform_bounds(&ids));
|
||||
run(&mut s, "object.setBounds", json!({"width": 224, "reference": 0, "strokes": strokes}));
|
||||
let v = s.transform_bounds(&ids).unwrap();
|
||||
if !close(v, Rect::new(-7.0, 90.0, 217.0, 160.0)) {
|
||||
wrong.push(format!("the group with a stroke, strokes {strokes}: {v:?}"));
|
||||
}
|
||||
}
|
||||
// A group of a rectangle from x 0 to 100 with a 2 pt stroke and one from x 40 to 60 with a 10 pt
|
||||
// stroke: its visual box, (-1, 95) to (101, 155), set to 11 wide is 11 wide.
|
||||
let mut s = session();
|
||||
let ids = [rect(&mut s, 0.0, 100.0, 2.0), rect(&mut s, 40.0, 20.0, 10.0)];
|
||||
preview(&mut s, true);
|
||||
run(&mut s, "select.set", json!({"ids": [ids[0].0, ids[1].0]}));
|
||||
let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "object.setBounds", json!({"width": 11, "reference": 0, "strokes": false}));
|
||||
let v = s.transform_bounds(&[group]).unwrap();
|
||||
if !close(v, Rect::new(-1.0, 95.0, 10.0, 155.0)) {
|
||||
wrong.push(format!("the 0 to 100 and 40 to 60 group: {v:?}"));
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_measures_clip_groups_and_groups_with_effects_as_one_object() {
|
||||
// A clip group is measured by its clipping path, a rectangle from x 0 to 10, though its content
|
||||
// with a 10 pt stroke reaches past it: with the unstroked rectangle from x 100 to 110, set to
|
||||
// 224 wide from the left edge, the visual box runs from x 0 to 224.
|
||||
let mut s = session();
|
||||
let content = rect(&mut s, 3.0, 17.0, 10.0);
|
||||
let path = rect(&mut s, 0.0, 10.0, 0.0);
|
||||
run(&mut s, "select.set", json!({"ids": [content.0, path.0]}));
|
||||
let clip = NodeId(run(&mut s, "object.clippingMask.make", json!({}))["id"].as_u64().unwrap());
|
||||
let plain = rect(&mut s, 100.0, 10.0, 0.0);
|
||||
preview(&mut s, true);
|
||||
run(&mut s, "select.set", json!({"ids": [clip.0, plain.0]}));
|
||||
run(&mut s, "object.setBounds", json!({"width": 224, "reference": 0, "strokes": false}));
|
||||
let v = s.transform_bounds(&[clip, plain]).unwrap();
|
||||
assert!(close(v, Rect::new(0.0, 100.0, 224.0, 150.0)), "the clip group: {v:?}");
|
||||
// A group with a drop shadow of its own is measured as one object, as before. Its 2 pt margin on
|
||||
// the left is measured from the group's left edge, though the stroke of the thick rectangle at
|
||||
// x 3 paints it, so the visual box is 223 wide and its left edge moves to -1.
|
||||
let (mut s, ids) = grouped(false, true);
|
||||
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": [ids[0].0]}));
|
||||
run(&mut s, "select.set", json!({"ids": [ids[0].0, ids[1].0]}));
|
||||
run(&mut s, "object.setBounds", json!({"width": 224, "reference": 0, "strokes": false}));
|
||||
let v = s.transform_bounds(&ids).unwrap();
|
||||
assert!(close(v, Rect::new(-1.0, 95.0, 222.0, 155.0)), "the group with a shadow: {v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bounding_box_handles_sit_on_the_preview_bounds() {
|
||||
// Drag from the visual right edge (10 pt outside the path) 100 pt to the right.
|
||||
|
||||
@@ -0,0 +1,415 @@
|
||||
//! Symbol instances measured by their symbol's art: Align, the Transform panel and the bounding
|
||||
//! box, Use Preview Bounds, Fit to Artwork Bounds, EPS export of the art, an artboard's SVG, Export
|
||||
//! Selection and the raster effect images of exports.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId, NodeKind, Symbol};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The symbol of the SVG import tests: a circle of radius 4 around (5, 5) with a 2 pt stroke, and
|
||||
/// an instance of it at x 80.
|
||||
const DOT: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="120"><defs><symbol id="Dot"><circle cx="5" cy="5" r="4" stroke="#000" stroke-width="2"/></symbol></defs><use href="#Dot" x="80" fill="red"/></svg>"##;
|
||||
|
||||
/// A symbol whose art, a red rectangle from (100, 60) to (140, 80), lies outside the 20 × 20
|
||||
/// square around the origin, and an instance of it.
|
||||
const FAR: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="120"><defs><symbol id="Far"><rect x="100" y="60" width="40" height="20" fill="#f00"/></symbol></defs><use href="#Far"/></svg>"##;
|
||||
|
||||
/// The same symbol with its instance moved by (-50, -50): the art, (50, 10) to (90, 30), lies on
|
||||
/// the artboard, and the 20 × 20 square, (-60, -60) to (-40, -40), lies off it.
|
||||
const FAR_MOVED: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="120"><defs><symbol id="Far"><rect x="100" y="60" width="40" height="20" fill="#f00"/></symbol></defs><use href="#Far" x="-50" y="-50"/></svg>"##;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
/// `svg` opened, and its symbol instance.
|
||||
fn open(svg: &str) -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "document.open", json!({"name": "symbols.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())}));
|
||||
let mut found = None;
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::SymbolInstance { .. }) {
|
||||
found = Some(n.id);
|
||||
}
|
||||
});
|
||||
(s, found.expect("a symbol instance"))
|
||||
}
|
||||
|
||||
fn close(a: Option<Rect>, b: Rect) -> bool {
|
||||
a.is_some_and(|a| [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-9))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn align_left_puts_the_dot_instances_circle_on_the_rectangles_edge() {
|
||||
let (mut s, dot) = open(DOT);
|
||||
// The Transform panel and the bounding box measure the circle, (81, 1) to (89, 9), not the
|
||||
// 20 × 20 square, (70, -10) to (90, 10).
|
||||
assert!(close(s.transform_bounds(&[dot]), Rect::new(81.0, 1.0, 89.0, 9.0)), "{:?}", s.transform_bounds(&[dot]));
|
||||
assert!(close(s.transform_box(&[dot]).map(|b| b.rect), Rect::new(81.0, 1.0, 89.0, 9.0)));
|
||||
run(&mut s, "shape.rectangle", json!({"x": 0, "y": 40, "width": 20, "height": 10}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "object.align", json!({"horizontal": "left"}));
|
||||
let NodeKind::SymbolInstance { xf, .. } = &s.doc().unwrap().doc.node(dot).unwrap().kind else { panic!("the instance") };
|
||||
// The circle's left edge, 1 pt right of where the instance draws the art's (0, 0), is at x 0.
|
||||
assert!(((*xf * Point::ZERO).x + 1.0).abs() < 1e-9, "{xf:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_inspect_reports_the_instances_art_bounds() {
|
||||
let (mut s, dot) = open(DOT);
|
||||
let rect = |v: &Value| {
|
||||
Some(Rect::new(v["x"].as_f64()?, v["y"].as_f64()?, v["x"].as_f64()? + v["width"].as_f64()?, v["y"].as_f64()? + v["height"].as_f64()?))
|
||||
};
|
||||
let node = run(&mut s, "document.node", json!({"id": dot.0, "summary": true}));
|
||||
assert!(close(rect(&node["bounds"]), Rect::new(81.0, 1.0, 89.0, 9.0)), "{node}");
|
||||
run(&mut s, "select.all", json!({}));
|
||||
let doc = run(&mut s, "document.inspect", json!({}));
|
||||
assert!(close(rect(&doc["selectionBounds"]), Rect::new(81.0, 1.0, 89.0, 9.0)), "{doc}");
|
||||
let layer = &doc["layers"][0];
|
||||
assert!(close(rect(&layer["children"][0]["bounds"]), Rect::new(81.0, 1.0, 89.0, 9.0)), "{layer}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn use_preview_bounds_takes_in_the_strokes_inside_the_symbol() {
|
||||
let (mut s, dot) = open(DOT);
|
||||
run(&mut s, "prefs.set", json!({"key": "usePreviewBounds", "value": true}));
|
||||
// The 2 pt stroke paints 1 pt around the circle.
|
||||
assert!(close(s.transform_bounds(&[dot]), Rect::new(80.0, 0.0, 90.0, 10.0)), "{:?}", s.transform_bounds(&[dot]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_with_use_preview_bounds_keeps_the_strokes_in_the_symbol_at_their_weight() {
|
||||
// The circle's visual box, (80, 0) to (90, 10), set to 20 × 20 around its center and from its
|
||||
// top-left corner: the stroke still paints 1 pt around the circle, whether strokes scale or not.
|
||||
for strokes in [true, false] {
|
||||
for (reference, want) in [(4, Rect::new(75.0, -5.0, 95.0, 15.0)), (0, Rect::new(80.0, 0.0, 100.0, 20.0))] {
|
||||
let (mut s, dot) = open(DOT);
|
||||
run(&mut s, "prefs.set", json!({"key": "usePreviewBounds", "value": true}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot.0]}));
|
||||
run(&mut s, "object.setBounds", json!({"width": 20, "height": 20, "strokes": strokes, "reference": reference}));
|
||||
let b = s.transform_bounds(&[dot]);
|
||||
assert!(close(b, want), "strokes {strokes}, reference {reference}: {b:?}");
|
||||
}
|
||||
}
|
||||
// A width of 2 pt, what the stroke adds, or less, with strokes that scale: the circle gets no
|
||||
// width, and the visual box is the stroke's 2 pt. The instance does not turn over.
|
||||
for width in [2.0, 1.0, 0.0] {
|
||||
let (mut s, dot) = open(DOT);
|
||||
run(&mut s, "prefs.set", json!({"key": "usePreviewBounds", "value": true}));
|
||||
run(&mut s, "select.set", json!({"ids": [dot.0]}));
|
||||
run(&mut s, "object.setBounds", json!({"width": width, "strokes": true}));
|
||||
let NodeKind::SymbolInstance { xf, .. } = &s.doc().unwrap().doc.node(dot).unwrap().kind else { panic!("the instance") };
|
||||
assert_eq!(xf.as_coeffs()[0], 0.0, "width {width}: {xf:?}");
|
||||
let b = s.transform_bounds(&[dot]).unwrap();
|
||||
assert!((b.width() - 2.0).abs() < 1e-9, "width {width}: {b:?}");
|
||||
}
|
||||
// An instance with a 2 pt stroke of its own, which scales, around art with a 2 pt stroke, which
|
||||
// keeps its weight: doubled, the visual box is twice as wide and high.
|
||||
let mut d = Document::new(200.0, 120.0);
|
||||
let stroked = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0);
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 8.0, 8.0)), stroked);
|
||||
d.symbols.push(Symbol { name: "Box".into(), art: Arc::new(art) });
|
||||
let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Box".into(), xf: Affine::translate((50.0, 50.0)) });
|
||||
*instance.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
|
||||
let (layer, id) = (d.layers[0].id, instance.id);
|
||||
d.insert(Some(layer), 0, instance).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
run(&mut s, "prefs.set", json!({"key": "usePreviewBounds", "value": true}));
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
let before = s.transform_bounds(&[id]).unwrap();
|
||||
run(&mut s, "object.setBounds", json!({"width": 2.0 * before.width(), "height": 2.0 * before.height(), "strokes": true}));
|
||||
let after = s.transform_bounds(&[id]).unwrap();
|
||||
assert!((after.width() - 2.0 * before.width()).abs() < 1e-9 && (after.height() - 2.0 * before.height()).abs() < 1e-9, "{before:?} {after:?}");
|
||||
// A symbol of an 8 × 8 square with a 2 pt round-joined stroke, and an instance of it at
|
||||
// (50, 50) as the one copy of a one-by-one grid repeat. With strokes that scale,
|
||||
// `object.setBounds` sets the repeat's visual box, (49, 49) to (59, 59), to 20 × 20 around its
|
||||
// center, (44, 44) to (64, 64), and the stroke in the symbol keeps its weight.
|
||||
let mut d = Document::new(200.0, 120.0);
|
||||
let mut round = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
|
||||
round.stroke_mut().unwrap().join = vectorcraft_doc::LineJoin::Round;
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 8.0, 8.0)), round);
|
||||
d.symbols.push(Symbol { name: "Ring".into(), art: Arc::new(art) });
|
||||
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Ring".into(), xf: Affine::translate((50.0, 50.0)) });
|
||||
let (layer, id) = (d.layers[0].id, instance.id);
|
||||
d.insert(Some(layer), 0, instance).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
run(&mut s, "prefs.set", json!({"key": "usePreviewBounds", "value": true}));
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
let repeat = NodeId(run(&mut s, "object.repeat.grid", json!({"rows": 1, "cols": 1}))["id"].as_u64().expect("the repeat"));
|
||||
run(&mut s, "select.set", json!({"ids": [repeat.0]}));
|
||||
assert!(close(s.transform_bounds(&[repeat]), Rect::new(49.0, 49.0, 59.0, 59.0)), "{:?}", s.transform_bounds(&[repeat]));
|
||||
run(&mut s, "object.setBounds", json!({"width": 20, "height": 20, "strokes": true}));
|
||||
let b = s.transform_bounds(&[repeat]);
|
||||
assert!(close(b, Rect::new(44.0, 44.0, 64.0, 64.0)), "the repeat: {b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_sizes_an_instance_and_a_path_whose_strokes_differ() {
|
||||
// An instance at (50, 50) of a 10 × 10 square with a 10 pt stroke, which keeps its weight, and a
|
||||
// path of the same square there with a 2 pt stroke, which scales. Setting their visual box,
|
||||
// (45, 45) to (65, 65), to 40 × 40 around its center gives (35, 35) to (75, 75): the instance's
|
||||
// stroke still sets every edge.
|
||||
let mut d = Document::new(200.0, 120.0);
|
||||
let square = |d: &mut Document, at: f64, weight: f64| {
|
||||
let stroked = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), weight);
|
||||
Node::path(d.alloc_id(), shapes::rectangle(Rect::new(at, at, at + 10.0, at + 10.0)), stroked)
|
||||
};
|
||||
let art = square(&mut d, 0.0, 10.0);
|
||||
d.symbols.push(Symbol { name: "Thick".into(), art: Arc::new(art) });
|
||||
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Thick".into(), xf: Affine::translate((50.0, 50.0)) });
|
||||
let path = square(&mut d, 50.0, 2.0);
|
||||
let (layer, ids) = (d.layers[0].id, [instance.id, path.id]);
|
||||
d.insert(Some(layer), 0, instance).unwrap();
|
||||
d.insert(Some(layer), 1, path).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
run(&mut s, "prefs.set", json!({"key": "usePreviewBounds", "value": true}));
|
||||
run(&mut s, "select.set", json!({"ids": [ids[0].0, ids[1].0]}));
|
||||
assert!(close(s.transform_bounds(&ids), Rect::new(45.0, 45.0, 65.0, 65.0)), "{:?}", s.transform_bounds(&ids));
|
||||
run(&mut s, "object.setBounds", json!({"width": 40, "height": 40, "strokes": true}));
|
||||
let b = s.transform_bounds(&ids);
|
||||
assert!(close(b, Rect::new(35.0, 35.0, 75.0, 75.0)), "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_measures_the_objects_in_an_instances_art_one_by_one() {
|
||||
// A symbol whose art is a group of a rectangle from x 0 to 10 with a 2 pt stroke and one from
|
||||
// x 3 to 10 with a 10 pt stroke, both 50 pt high, and an instance of it 100 pt down, in a group
|
||||
// when `grouped`, selected with an unstroked rectangle from x 100 to 110 when `plain`. The
|
||||
// instance's visual box runs from (-2, 95) to (15, 155). With `own`, the art's group and the
|
||||
// instance each have a 1 pt stroke of their own, which reaches 5 pt at its miter limit of 10.
|
||||
let selection = |grouped: bool, plain: bool, own: bool| {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let stroked = |d: &mut Document, x0: f64, weight: f64| {
|
||||
Node::path(
|
||||
d.alloc_id(),
|
||||
shapes::rectangle(Rect::new(x0, 0.0, 10.0, 50.0)),
|
||||
Appearance::basic(Paint::None, Paint::solid(Color::BLACK), weight),
|
||||
)
|
||||
};
|
||||
let mut art = Node::group(d.alloc_id(), vec![Arc::new(stroked(&mut d, 0.0, 2.0)), Arc::new(stroked(&mut d, 3.0, 10.0))]);
|
||||
let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mixed".into(), xf: Affine::translate((0.0, 100.0)) });
|
||||
if own {
|
||||
*art.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
*instance.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
}
|
||||
d.symbols.push(Symbol { name: "Mixed".into(), art: Arc::new(art) });
|
||||
let mut roots = vec![if grouped { Node::group(d.alloc_id(), vec![Arc::new(instance)]) } else { instance }];
|
||||
if plain {
|
||||
let filled = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0);
|
||||
roots.push(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 100.0, 110.0, 150.0)), filled));
|
||||
}
|
||||
let (layer, ids): (NodeId, Vec<NodeId>) = (d.layers[0].id, roots.iter().map(|n| n.id).collect());
|
||||
for (i, n) in roots.into_iter().enumerate() {
|
||||
d.insert(Some(layer), i, n).unwrap();
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
run(&mut s, "prefs.set", json!({"key": "usePreviewBounds", "value": true}));
|
||||
run(&mut s, "select.set", json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}));
|
||||
(s, ids)
|
||||
};
|
||||
// With the unstroked rectangle, the visual box runs from (-2, 95) to (110, 155). Set to 224 wide
|
||||
// from its left edge, it is 224 wide and its left edge stays at -2, with strokes kept or
|
||||
// scaling, and with the instance in a group. The instance alone set to 37 wide is 37 wide. With
|
||||
// the strokes of their own, which paint around each rectangle, the visual box runs from
|
||||
// (-12, 85) to (110, 165): set to 224 wide, it is 224 wide and its left edge stays at -12.
|
||||
let mut wrong = vec![];
|
||||
for (grouped, plain, own, width, strokes) in [
|
||||
(false, true, false, 224.0, false),
|
||||
(false, true, false, 224.0, true),
|
||||
(true, true, false, 224.0, false),
|
||||
(false, false, false, 37.0, false),
|
||||
(false, true, true, 224.0, false),
|
||||
(false, true, true, 224.0, true),
|
||||
] {
|
||||
let (mut s, ids) = selection(grouped, plain, own);
|
||||
let (left, top, bottom) = if own { (-12.0, 85.0, 165.0) } else { (-2.0, 95.0, 155.0) };
|
||||
let before = s.transform_bounds(&ids);
|
||||
if !close(before, Rect::new(left, top, if plain { 110.0 } else { 15.0 }, bottom)) {
|
||||
wrong.push(format!("grouped {grouped}, plain {plain}, own {own}, before: {before:?}"));
|
||||
}
|
||||
run(&mut s, "object.setBounds", json!({"width": width, "reference": 0, "strokes": strokes}));
|
||||
let b = s.transform_bounds(&ids);
|
||||
if !close(b, Rect::new(left, top, left + width, bottom)) {
|
||||
wrong.push(format!("grouped {grouped}, plain {plain}, own {own}, strokes {strokes}: {b:?}"));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_measures_an_instance_as_one_object_past_4096_objects_in_its_art() {
|
||||
// An instance 100 pt down of a symbol whose art is a rectangle from x 0 to 10 with a 2 pt
|
||||
// stroke, one from x 3 to 10 with a 10 pt stroke, both 50 pt high, and unstroked 1 × 1 squares
|
||||
// inside them: 4,096 objects, then 4,097. Its visual box runs from (-2, 95) to (15, 155). Set to
|
||||
// 37 wide from the left edge, it is 37 wide with 4,096 objects. With 4,097 it is measured as one
|
||||
// object: its 2 pt margin on the left is measured from its left edge, though the stroke of the
|
||||
// thick rectangle at x 3 paints it, so it is 36 wide and its left edge moves to -1.
|
||||
for (objects, want) in [(4096, Rect::new(-2.0, 95.0, 35.0, 155.0)), (4097, Rect::new(-1.0, 95.0, 35.0, 155.0))] {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let stroked = |d: &mut Document, x0: f64, weight: f64| {
|
||||
Arc::new(Node::path(
|
||||
d.alloc_id(),
|
||||
shapes::rectangle(Rect::new(x0, 0.0, 10.0, 50.0)),
|
||||
Appearance::basic(Paint::None, Paint::solid(Color::BLACK), weight),
|
||||
))
|
||||
};
|
||||
let mut art = vec![stroked(&mut d, 0.0, 2.0), stroked(&mut d, 3.0, 10.0)];
|
||||
for i in 2..objects {
|
||||
let (x, y) = (f64::from(4 + i % 5), f64::from(1 + i % 47));
|
||||
let square = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0);
|
||||
art.push(Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 1.0, y + 1.0)), square)));
|
||||
}
|
||||
let art = Node::group(d.alloc_id(), art);
|
||||
d.symbols.push(Symbol { name: "Many".into(), art: Arc::new(art) });
|
||||
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Many".into(), xf: Affine::translate((0.0, 100.0)) });
|
||||
let (layer, id) = (d.layers[0].id, instance.id);
|
||||
d.insert(Some(layer), 0, instance).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
run(&mut s, "prefs.set", json!({"key": "usePreviewBounds", "value": true}));
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
run(&mut s, "object.setBounds", json!({"width": 37, "reference": 0, "strokes": false}));
|
||||
let b = s.transform_bounds(&[id]);
|
||||
assert!(close(b, want), "{objects} objects: {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_measures_a_turned_instance_by_the_box_around_its_turned_art_box() {
|
||||
// A symbol whose art is a filled circle of radius 10 around the origin, and an instance of it
|
||||
// turned 30° at (100, 100) whose bounding box stands square to the page: the box around the
|
||||
// art's 20 × 20 box turned 30°, 27.32 wide. Set to 40 wide from its left edge, it is 40 wide.
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let filled = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0);
|
||||
let circle = Node::path(d.alloc_id(), shapes::ellipse(Rect::new(-10.0, -10.0, 10.0, 10.0)), filled);
|
||||
d.symbols.push(Symbol { name: "Disc".into(), art: Arc::new(circle) });
|
||||
let xf = Affine::translate((100.0, 100.0)) * Affine::rotate(30f64.to_radians());
|
||||
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Disc".into(), xf });
|
||||
let (layer, id) = (d.layers[0].id, instance.id);
|
||||
d.insert(Some(layer), 0, instance).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
run(&mut s, "prefs.set", json!({"key": "usePreviewBounds", "value": true}));
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
let before = s.transform_bounds(&[id]).unwrap();
|
||||
let turned = 20.0 * (30f64.to_radians().cos() + 30f64.to_radians().sin());
|
||||
assert!((before.width() - turned).abs() < 1e-9, "{before:?}");
|
||||
run(&mut s, "object.setBounds", json!({"width": 40, "reference": 0}));
|
||||
let after = s.transform_bounds(&[id]).unwrap();
|
||||
assert!((after.width() - 40.0).abs() < 1e-9 && (after.x0 - before.x0).abs() < 1e-9, "{before:?} {after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fit_to_artwork_bounds_fits_the_instances_art() {
|
||||
let (mut s, _) = open(DOT);
|
||||
run(&mut s, "artboard.fitToArt", json!({}));
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
assert!(close(Some(board), Rect::new(80.0, 0.0, 90.0, 10.0)), "{board:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eps_of_the_art_bounds_and_writes_an_instances_art() {
|
||||
let (mut s, _) = open(FAR);
|
||||
let r = run(&mut s, "document.export", json!({"format": "eps", "previewFormat": "none", "cmykPostScript": false}));
|
||||
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let ps = String::from_utf8(vectorcraft_eps::sections(&bytes).unwrap().0.to_vec()).unwrap();
|
||||
let bbox = ps.lines().find_map(|l| l.strip_prefix("%%BoundingBox:")).map(str::trim);
|
||||
// The art, 60 to 80 down from the artboard's top, is 40 to 60 up from its bottom (120 high).
|
||||
assert_eq!(bbox, Some("100 40 140 60"), "{ps}");
|
||||
assert!(ps.contains("1 0 0 rg"), "the art is written: {ps}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_artboards_svg_keeps_an_instance_whose_art_is_on_it() {
|
||||
let (mut s, _) = open(FAR_MOVED);
|
||||
let svg = run(&mut s, "document.serialize", json!({"format": "svg", "artboard": 0}));
|
||||
let text = svg["text"].as_str().unwrap();
|
||||
assert!(text.contains("<use"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_artboards_svg_keeps_an_instance_whose_brush_art_is_on_it() {
|
||||
// The symbol's art: a line from (0, 40) to (0, 60) with a 1 pt stroke painted by a 20 pt round
|
||||
// nib. Drawn from (-5, 0), the line lies left of the artboard, and the nib paints 10 pt either
|
||||
// side of it, onto the artboard.
|
||||
let mut d = Document::new(200.0, 120.0);
|
||||
let mut lib = vectorcraft_brush::library(&d);
|
||||
let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else {
|
||||
panic!("the 3 pt. Round brush")
|
||||
};
|
||||
c.size = 20.0;
|
||||
vectorcraft_brush::store(&mut d, &lib);
|
||||
let mut stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
stroke.stroke_mut().unwrap().brush = Some("3 pt. Round".into());
|
||||
let line = Node::path(d.alloc_id(), shapes::line((0.0, 40.0).into(), (0.0, 60.0).into()), stroke);
|
||||
d.symbols.push(Symbol { name: "Nib".into(), art: Arc::new(line) });
|
||||
let (layer, id) = (d.layers[0].id, d.alloc_id());
|
||||
d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Nib".into(), xf: Affine::translate((-5.0, 0.0)) })).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
let svg = run(&mut s, "document.serialize", json!({"format": "svg", "artboard": 0}));
|
||||
let text = svg["text"].as_str().unwrap();
|
||||
assert!(text.contains("<use"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_artboards_svg_keeps_an_instance_whose_shadow_is_on_it() {
|
||||
// The symbol's art, a black square from (-1, -1) to (1, 1), drawn from (-5, 20): left of the
|
||||
// artboard. A drop shadow 8 pt to the right, on the art or on the instance, reaches onto it.
|
||||
for in_art in [true, false] {
|
||||
let mut d = Document::new(200.0, 120.0);
|
||||
let shadow = Effect { id: "stylize.dropShadow".into(), params: json!({"x": 8, "y": 0, "blur": 0}), visible: true };
|
||||
let square = shapes::rectangle(Rect::new(-1.0, -1.0, 1.0, 1.0));
|
||||
let mut art = Node::path(d.alloc_id(), square, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((-5.0, 20.0)) });
|
||||
if in_art {
|
||||
art.appearance.effects.push(shadow);
|
||||
} else {
|
||||
instance.appearance.effects.push(shadow);
|
||||
}
|
||||
d.symbols.push(Symbol { name: "Dot".into(), art: Arc::new(art) });
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, instance).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
let svg = run(&mut s, "document.serialize", json!({"format": "svg", "artboard": 0}));
|
||||
let text = svg["text"].as_str().unwrap();
|
||||
assert!(text.contains("<use"), "the shadow on the art: {in_art}; {text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_selection_crops_to_the_instances_art() {
|
||||
let (mut s, _) = open(FAR);
|
||||
run(&mut s, "select.all", json!({}));
|
||||
let v = run(&mut s, "document.exportSelection", json!({"format": "svg"}));
|
||||
let bounds: Vec<f64> = v["bounds"].as_array().unwrap().iter().filter_map(Value::as_f64).collect();
|
||||
// x, y, width and height: the art, not the 20 × 20 square from (-10, -10).
|
||||
assert_eq!(bounds, [100.0, 60.0, 40.0, 20.0], "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_groups_shadow_image_covers_the_art_of_the_instance_in_it() {
|
||||
let (mut s, far) = open(FAR);
|
||||
run(&mut s, "select.set", json!({"ids": [far.0]}));
|
||||
let group = run(&mut s, "object.group", json!({}))["id"].as_u64().expect("the group");
|
||||
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": [group]}));
|
||||
let flat = crate::flatten_raster_effects(&s.doc().unwrap().doc).unwrap();
|
||||
let mut frame = None;
|
||||
flat.walk(|n| {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
frame = Some(im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height))));
|
||||
}
|
||||
});
|
||||
let frame = frame.expect("the shadow's image");
|
||||
assert!(frame.x0 <= 100.0 && frame.y0 <= 60.0 && frame.x1 >= 140.0 && frame.y1 >= 80.0, "{frame:?}");
|
||||
}
|
||||
Reference in new issue
Block a user