Merge main into fix/speed-i13929-menu-model

This commit is contained in:
dotCooCoo committed 2026-11-28 18:16:42 -08:00
commit cfc45aeef7
111 files changed
+6414 -474

No files matched your search

+1
View File
@@ -174,6 +174,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and, with Measurement Labels on, its radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged.
- 2026-11-28: The Three-Point Arc tool joins an arc to the open paths whose ends its ends are placed on, with Join to Open Path Ends (Tool Options, or J while drawing; `shape.threePointArc` `join`), and in direction mode snaps the third point to where the arc carries an open path on, the same way or turned back (Snap Where the Arc Continues a Path, on by default). Headline numbers unchanged.
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged.
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
+77
View File
@@ -2626,6 +2626,83 @@ fn pattern_brush_scale_from_the_pen_fits_start_and_end_tiles_where_the_scale_fal
}
}
/// How far from y = 0 the outlines under `nodes` reach where they cross the vertical line at `x`.
fn reach_at(nodes: &[Node], x: f64) -> f64 {
let mut reach = 0.0f64;
for n in nodes {
n.walk(&mut |c| {
for sp in c.path_data().into_iter().flat_map(|p| &p.subpaths) {
for i in 0..sp.segment_count() {
let s = sp.segment(i);
let (a, b, c, d) = (s.p0.x, s.p1.x, s.p2.x, s.p3.x);
let roots = kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (c - 2.0 * b + a), d - 3.0 * c + 3.0 * b - a);
for t in roots.into_iter().filter(|t| (-1e-9..=1.0 + 1e-9).contains(t)) {
reach = reach.max(kurbo::ParamCurve::eval(&s, t.clamp(0.0, 1.0)).y.abs());
}
}
}
});
}
reach
}
/// A pattern tile whose scale follows the pen is as tall as the scale at a short peak of the
/// pressure, even where the peak falls between the positions the bent outline is checked at.
#[test]
fn pattern_brush_scale_from_the_pen_keeps_a_short_peak() {
let doc = Document::new(1.0, 1.0);
let b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(300.0));
// One 10 × 4 pt tile on a 10 pt path: 100 % (2 pt either side) but for a peak at 2.2 pt, where
// the scale reaches 300 % (6 pt either side).
let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]);
let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 10.0, 0.0), &peak);
// At the peak 300 %, half way up it 200 %, and 100 % on either side of it.
for (x, want) in [(2.2, 6.0), (2.15, 4.0), (2.25, 4.0), (1.0, 2.0), (2.05, 2.0), (2.4, 2.0), (8.0, 2.0)] {
assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x));
}
}
/// An art brush whose width follows the pen is as wide as the pen gives at a short peak of the
/// pressure, even where the peak falls between the positions the bent outline is checked at.
#[test]
fn art_brush_width_from_the_pen_keeps_a_short_peak() {
let mut b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
if let BrushKind::Art(a) = &mut b.kind {
(a.width, a.width_mode, a.width_max) = (100.0, Some(Variation::Pressure), Some(300.0));
}
// 4 pt art on a 100 pt path: 2 pt either side but for a peak at 22 pt, where it is 6 pt.
let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]);
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 100.0, 0.0), &peak);
for (x, want) in [(22.0, 6.0), (21.5, 4.0), (22.5, 4.0), (10.0, 2.0), (20.5, 2.0), (24.0, 2.0), (80.0, 2.0)] {
assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x));
}
}
/// A pen recording sampled many times along a straight ramp draws as many anchors as the ramp's
/// two ends do: samples that leave the scale on the same straight course are not split at.
#[test]
fn pen_samples_on_a_straight_ramp_add_no_anchors() {
let doc = Document::new(1.0, 1.0);
let bp = line(0.0, 0.0, 1000.0, 0.0);
let ramp = |n: usize| pressed((0..=n).map(|i| (i as f64 / n as f64, i as f64 / n as f64)).collect());
let anchors = |out: &[Node]| {
let mut count = 0;
for n in out {
n.walk(&mut |c| count += c.path_data().map_or(0, |p| p.subpaths.iter().map(|s| s.anchors.len()).sum::<usize>()));
}
count
};
let pattern = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0));
let mut art = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
if let BrushKind::Art(a) = &mut art.kind {
(a.width, a.width_mode, a.width_max) = (50.0, Some(Variation::Pressure), Some(300.0));
}
for b in [&pattern, &art] {
let (few, many) = (stroke_pieces(&doc, b, &bp, &ramp(1)), stroke_pieces(&doc, b, &bp, &ramp(2000)));
assert_eq!(anchors(&many), anchors(&few), "{}", b.name);
}
}
/// On a closed path, a tile that Approximate Path starts before the path's start takes the scale
/// recorded at the end of the stroke there, where the tile is drawn.
#[test]
+152 -30
View File
@@ -40,23 +40,32 @@ const MASK_STEPS: usize = 32;
/// through the bend to within [`fit_tol`] of `doc_tol`, the flattening tolerance in document
/// space, so the art keeps its curves (#3926). Where that cannot be done in no more anchors than
/// chords would take, the path is flattened with `flat_tol` (art space) and subdivided so no chord
/// is longer than `max_du` along x, as it always was. Stroke widths scale by `width_scale`.
/// Text, images and symbol instances can't bend and are dropped. The art of a linked opacity mask
/// bends with the object it masks.
pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, doc_tol: f64, width_scale: f64) -> Option<Node> {
/// is longer than `max_du` along x, as it always was. Both routes also split the art where it
/// crosses each of `breaks` (art x, in order), so a turn of the map there is not stepped over.
/// Stroke widths scale by `width_scale`. Text, images and symbol instances can't bend and are
/// dropped. The art of a linked opacity mask bends with the object it masks.
pub(crate) fn warp_node(
n: &Node,
f: &dyn Fn(Point) -> Point,
flat_tol: f64,
max_du: f64,
doc_tol: f64,
width_scale: f64,
breaks: &[f64],
) -> Option<Node> {
let mut out = n.clone();
out.appearance.scale_strokes(width_scale);
match &mut out.kind {
NodeKind::Path { path, live, .. } => {
*live = None;
*path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol));
*path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol), breaks);
if path.is_empty() {
return None;
}
}
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } => {
let kids: Vec<Arc<Node>> =
children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale)).map(Arc::new).collect();
children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale, breaks)).map(Arc::new).collect();
if kids.is_empty() {
return None;
}
@@ -64,7 +73,7 @@ pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max
}
_ => return None,
}
map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale));
map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale, breaks));
Some(out)
}
@@ -80,12 +89,13 @@ fn map_mask(n: &mut Node, map: impl FnOnce(&Node) -> Option<Node>) {
}
/// Each subpath of `p` through `f`: fitted cubics when they take no more anchors than the chords
/// would, else the chords. Points `f` cannot place (not finite) are left out of the chords.
fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64) -> PathData {
/// would, else the chords, both split at `breaks` ([`warp_node`]). Points `f` cannot place (not
/// finite) are left out of the chords.
fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64, breaks: &[f64]) -> PathData {
let mut subs = vec![];
for sp in &p.subpaths {
let Some(dense) = densified(sp, flat_tol, max_du) else { continue };
if let Some(fit) = fitted(sp, f, fit_tol, dense.len()) {
let Some(dense) = densified(sp, flat_tol, max_du, breaks) else { continue };
if let Some(fit) = fitted(sp, f, fit_tol, dense.len(), breaks) {
subs.push(fit);
continue;
}
@@ -98,8 +108,9 @@ fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f6
}
/// `sp` flattened with `flat_tol` and its chords subdivided so none is longer than `max_du` along
/// x, in art space: the points the chord route maps. `None` below two points.
fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
/// x, in art space, with a point where a chord crosses each of `breaks` (art x, in order): the
/// points the chord route maps. `None` below two points.
fn densified(sp: &SubPath, flat_tol: f64, max_du: f64, breaks: &[f64]) -> Option<Vec<Point>> {
let mut bp = BezPath::new();
sp.to_bezpath_into(&mut bp);
let mut pts = vec![];
@@ -118,16 +129,57 @@ fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
let mut dense = vec![*pts.first()?];
for (i, (&a, &b)) in pts.iter().zip(pts.iter().cycle().skip(1)).take(segs).enumerate() {
let k = (((b.x - a.x).abs() / max_du).ceil() as usize).clamp(1, MAX_SUB);
// The breaks the chord crosses, as parameters along it in order, go in among the even ones.
let mut cuts: Vec<f64> = crossed(breaks, a.x, b.x).iter().map(|&x| (x - a.x) / (b.x - a.x)).collect();
cuts.sort_by(f64::total_cmp);
let mut cuts = cuts.into_iter().peekable();
for j in 1..=k {
let even = j as f64 / k as f64;
while let Some(t) = cuts.next_if(|&t| t < even) {
dense.push(a.lerp(b, t));
}
if sp.closed && i == segs - 1 && j == k {
break;
}
dense.push(a.lerp(b, j as f64 / k as f64));
dense.push(a.lerp(b, even));
}
}
Some(dense)
}
/// The values of `breaks` (in order) strictly between `a` and `b`, either way round.
fn crossed(breaks: &[f64], a: f64, b: f64) -> &[f64] {
let (lo, hi) = (a.min(b), a.max(b));
let from = breaks.partition_point(|&x| x <= lo);
let to = from + breaks[from..].partition_point(|&x| x < hi);
&breaks[from..to]
}
/// The parameters of `c` (in order, strictly between its ends) where its x is one of `breaks`;
/// `line` when `c` is a line with its handles at thirds, whose x runs evenly.
fn crossings(c: &CubicBez, line: bool, breaks: &[f64]) -> Vec<f64> {
let xs = [c.p0.x, c.p1.x, c.p2.x, c.p3.x];
let (lo, hi) = xs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &x| (lo.min(x), hi.max(x)));
let inside = crossed(breaks, lo, hi);
if inside.is_empty() {
return vec![];
}
let [a, b, cc, d] = xs;
let mut ts: Vec<f64> = vec![];
for &x in inside {
if line {
ts.push((x - a) / (d - a));
} else {
ts.extend(kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (cc - 2.0 * b + a), d - 3.0 * cc + 3.0 * b - a));
}
}
// Pieces are no shorter than the step the fit reads their ends' directions over.
ts.retain(|t| t.is_finite() && *t > FIT_DT && *t < 1.0 - FIT_DT);
ts.sort_by(f64::total_cmp);
ts.dedup_by(|t, prev| *t - *prev <= FIT_DT);
ts
}
/// Times an art segment is halved at most while looking for cubics that fit it.
const FIT_DEPTH: u32 = 12;
/// Parameter step of the finite differences that stand in for the bend's derivative.
@@ -156,7 +208,10 @@ fn fit_tol(doc_tol: f64) -> f64 {
/// bend at the same parameters, so the distance measured is never less than the true one. The
/// halving is our own rather than kurbo's `fit_to_bezpath`, which halves until the floats run out
/// on a map that never fits; the depth and the anchor count bound this one.
fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Option<SubPath> {
///
/// A segment is first split where its x crosses one of `breaks` (art x, in order), so a turn of
/// the map there lands on an anchor rather than between the checked positions.
fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize, breaks: &[f64]) -> Option<SubPath> {
if !(tol.is_finite() && tol > 0.0) {
return None;
}
@@ -174,7 +229,11 @@ fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Op
// A line's handles sit on its ends, which stalls its parameter there; thirds keep it even.
let c = if line { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c };
let at = |t: f64| Some(f(c.eval(t))).filter(|q| q.is_finite());
fit_into(&at, (0.0, 1.0), line, tol, FIT_DEPTH, &mut bp, &mut room)?;
let mut t0 = 0.0;
for t1 in crossings(&c, line, breaks).into_iter().chain([1.0]) {
fit_into(&at, (t0, t1), line, tol, FIT_DEPTH, &mut bp, &mut room)?;
t0 = t1;
}
}
if sp.closed {
bp.close_path();
@@ -316,6 +375,16 @@ impl AlongMap {
fn max_scale(&self) -> f64 {
(0..3).map(|i| self.slope(i).abs()).fold(1e-6, f64::max)
}
/// The art x (offset from the art's left edge) that [`AlongMap::at`] takes to arc length `s`,
/// when a piece with width spans it.
fn x_at(&self, s: f64) -> Option<f64> {
(0..3).find_map(|i| {
let ((x0, x1), (s0, s1)) = ((self.xs[i], self.xs[i + 1]), (self.ss[i], self.ss[i + 1]));
let spans = x1 - x0 > 1e-12 && (s1 - s0).abs() > 1e-12 && s0.min(s1) <= s && s <= s0.max(s1);
spans.then(|| x0 + (s - s0) / (s1 - s0) * (x1 - x0))
})
}
}
/// The affine that reproduces `f` over `b` to within `tol`, if one does.
@@ -414,12 +483,14 @@ fn bend(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64) -> Option<N
{
return affine_node(art, a, cross.abs());
}
warp_node(art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs())
warp_node(art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs(), &[])
}
/// [`bend`], with the cross scale at arc length `s` multiplied by `widen(s)` (0..=1). The strokes
/// of each object in the art take the factor at the middle of the object.
fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, widen: &dyn Fn(f64) -> f64) -> Option<Node> {
/// of each object in the art take the factor at the middle of the object. `marks` are the arc
/// lengths (in order) of the recorded pen samples `widen` runs in a straight line between; the art
/// is split where `widen` turns at one by more than the bent outline's tolerance ([`pen_breaks`]).
fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, widen: &dyn Fn(f64) -> f64, marks: &[f64]) -> Option<Node> {
let cy = b.center().y;
let x0 = b.x0;
let f = move |p: Point| {
@@ -430,7 +501,45 @@ fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, wid
let art = widen_strokes(art, &factor);
let scale = along.max_scale().max(cross.abs()).max(1e-6);
let flat_tol = tolerance(b.height().max(b.width()) * scale) / scale;
warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs())
// A change of `dw` in `widen` moves the art's top and bottom edges `dw × reach` across.
let reach = b.height() / 2.0 * cross.abs();
let mut breaks: Vec<f64> =
pen_breaks(marks, along.span(), widen, fit_tol(flat_tol * scale) / reach).into_iter().filter_map(|s| along.x_at(s)).map(|x| x + x0).collect();
breaks.sort_by(f64::total_cmp);
breaks.dedup();
warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs(), &breaks)
}
/// The arc lengths among `marks` (in order) strictly within `(s0, s1)` at which the art is split:
/// those where `widen` is more than `tol` from the straight line between the ones kept on either
/// side (the span's ends to begin with), chosen by splitting at the farthest one until every
/// sample left out is within `tol` of that line. `widen` runs straight between samples, so it
/// is then within `tol` of the line between kept samples all along, and samples on a straight
/// course add no splits.
fn pen_breaks(marks: &[f64], (s0, s1): (f64, f64), widen: &dyn Fn(f64) -> f64, tol: f64) -> Vec<f64> {
if !(s1 > s0 && tol > 0.0) {
return vec![];
}
let inside = {
let from = marks.partition_point(|&s| s <= s0);
&marks[from..from + marks[from..].partition_point(|&s| s < s1)]
};
if inside.is_empty() {
return vec![];
}
let pts: Vec<(f64, f64)> = std::iter::once(s0).chain(inside.iter().copied()).chain([s1]).map(|s| (s, widen(s))).collect();
let mut keep = vec![false; pts.len()];
let mut spans = vec![(0, pts.len() - 1)];
while let Some((i, j)) = spans.pop() {
let ((sa, wa), (sb, wb)) = (pts[i], pts[j]);
let off = |&(s, w): &(f64, f64)| (w - if sb > sa { wa + (wb - wa) * (s - sa) / (sb - sa) } else { wa }).abs();
let far = (i + 1..j).map(|k| (k, off(&pts[k]))).filter(|&(_, d)| d > tol).max_by(|a, b| a.1.total_cmp(&b.1));
if let Some((k, _)) = far {
keep[k] = true;
spans.extend([(i, k), (k, j)]);
}
}
pts.iter().zip(keep).filter(|&(_, k)| k).map(|(p, _)| p.0).collect()
}
/// `n` with the strokes of it and of everything inside it scaled by `factor` of the object they
@@ -465,8 +574,17 @@ fn art_runs(t: &Track) -> Vec<(f64, f64)> {
bounds.windows(2).map(|w| (w[0], w[1])).collect()
}
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1.
fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, Rect), cross: f64, widen: &dyn Fn(f64) -> f64) -> Option<Node> {
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1 (`marks`
/// as [`bend_widened`] takes them).
fn art_on_run(
t: &Track,
(s0, s1): (f64, f64),
a: &ArtBrush,
(art, b): (&Node, Rect),
cross: f64,
widen: &dyn Fn(f64) -> f64,
marks: &[f64],
) -> Option<Node> {
let l = s1 - s0;
if l <= 1e-9 {
return None;
@@ -489,7 +607,7 @@ fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, R
}
}
};
bend_widened(t, art, b, along, cross, widen)
bend_widened(t, art, b, along, cross, widen, marks)
}
/// An art brush's art along `bp`. With a width that follows the pen (its pressure, tilt, bearing
@@ -515,9 +633,13 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer)
let p = a.width_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5);
(light + (heavy - light) * p) / width
};
let marks = match a.width_mode {
Some(m) if light != heavy && width > 0.0 => pen_marks(stroke, m, l),
_ => vec![],
};
let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] };
for run in runs {
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen) {
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen, &marks) {
out.push(n);
}
}
@@ -671,7 +793,7 @@ fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64)
if mid <= 0.0 || marks.is_none_or(even) {
return tile_on(t, tile, s0, s1, mid);
}
bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid)
bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid, marks.unwrap_or_default())
}
/// The most side tiles a run of a pattern brush places.
@@ -966,7 +1088,7 @@ fn auto_corner(t: &Track, i: usize, source: CornerSource, side: &(Node, Rect), k
}
let s = if tw > 1e-9 { len / tw } else { 1.0 };
let max_du = MAX_SEG / (2.0 * k * s.max(1.0));
let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k);
let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k, &[]);
// Art point → (distance along from the left edge, stretched to `len`, and offset across).
let along = move |q: Point| {
let (x, y) = local(q);
@@ -1393,7 +1515,7 @@ mod tests {
let f = |p: Point| t.map(along.at(p.x - x0), p.y - cy);
let tol = tolerance(b.height().max(b.width()));
let exact = traced(art, &f, 1000);
let chords: Vec<Point> = densified(art, tol, MAX_SEG).expect("the tile flattens").into_iter().map(f).collect();
let chords: Vec<Point> = densified(art, tol, MAX_SEG, &[]).expect("the tile flattens").into_iter().map(f).collect();
let curves = traced(sp, &|p| p, 200);
let (e_curves, e_chords) = (apart(&curves, &exact), apart(&chords, &exact));
// Checked at eight points a piece, so a little room between them.
@@ -1419,7 +1541,7 @@ mod tests {
let allowed: usize = path
.subpaths
.iter()
.filter_map(|sp| densified(sp, 0.25, 1.5))
.filter_map(|sp| densified(sp, 0.25, 1.5, &[]))
.map(|dense| 1 + (FIT_CHECKS + 3) * (2 * dense.len() + FIT_DEPTH as usize + 1) + dense.len())
.sum();
let finite = |n: &Node| match &n.kind {
@@ -1441,7 +1563,7 @@ mod tests {
calls.set(calls.get() + 1);
if calls.get() > allowed { Point::new(f64::NAN, f64::NAN) } else { f(p) }
};
let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0);
let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0, &[]);
assert!(calls.get() <= allowed, "map {i} was called {} times, {allowed} allowed", calls.get());
match (i, &out) {
(3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"),
@@ -1491,7 +1613,7 @@ mod tests {
let mask = out.extras().mask.as_ref().expect("the mask is kept");
assert_eq!(*mask.art, stroked(1), "{name} run: an unlinked mask stays where it was");
let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5).expect("the art is drawn");
let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5, &[]).expect("the art is drawn");
let mask = out.extras().mask.as_ref().expect("the mask is kept");
assert_eq!(mask.art.kind, out.kind, "{name} run, widened: the mask's art bends with the art");
assert_eq!(mask.art.appearance, out.appearance, "{name} run, widened: the mask's strokes narrow with the art's");
+7 -1
View File
@@ -314,8 +314,14 @@ impl Document {
self.renumber_stored_duplicates();
}
/// Find a node anywhere in the tree.
/// Find a node anywhere in the tree. With the lookup cache built, the node comes from the place the cache has for
/// it, read once and without copying its index path; otherwise, and when that place no longer holds it, as
/// [`Document::index_path`] finds it.
pub fn node(&self, id: NodeId) -> Option<&Node> {
if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id)) {
crate::id_index::note_path_lookup();
return Some(n);
}
self.index_path(id).and_then(|p| self.node_at(&p))
}
+43
View File
@@ -82,6 +82,7 @@ impl Paths {
/// isn't in the table or it, or a node it is in, was removed.
pub(crate) fn get(&self, id: &NodeId) -> Option<Option<Vec<usize>>> {
let e = (*self.table.ids.get(id)?)?;
note_path_copy();
let mut path = Vec::new();
let mut cur = e;
// Each step goes to a parent entry, made before its children: at most `at.len()` steps.
@@ -96,6 +97,29 @@ impl Paths {
}
Some(None)
}
/// The node with `id` in `layers` at the place the table has for it, found without copying its index path: `None`
/// when the table does not have one place for `id`, its path is deeper than [`NODE_IN_DEPTH`], or the node there
/// does not have the id (the tree changed). The caller then looks it up as [`crate::Document::index_path`] does.
pub(crate) fn node_in<'a>(&self, layers: &'a [Arc<Node>], id: NodeId) -> Option<&'a Node> {
let mut cur = (*self.table.ids.get(&id)?)?;
let mut steps = [0u32; NODE_IN_DEPTH];
let mut depth = 0;
loop {
let &(parent, i) = self.table.at.get(cur as usize)?;
*steps.get_mut(depth)? = self.shifted(parent, i)?;
depth += 1;
if parent == u32::MAX {
break;
}
cur = parent;
}
let mut path = steps[..depth].iter().rev();
let mut node: &Node = layers.get(*path.next()? as usize)?;
for &i in path {
node = node.children()?.get(i as usize)?;
}
(node.id == id).then_some(node)
}
/// Where the table has `id` as it was built: its parent's entry and its index among its
/// siblings then; `None` when the id isn't in the table or appears more than once.
pub(crate) fn table_place(&self, id: &NodeId) -> Option<(u32, u32)> {
@@ -170,6 +194,25 @@ pub(crate) fn note_path_lookup() {
PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1));
}
/// The deepest index path [`Paths::node_in`] follows without copying it.
const NODE_IN_DEPTH: usize = 32;
thread_local! {
/// [`path_copies`] of this thread.
static PATH_COPIES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// How many index paths the lookup cache has copied out on this thread, one for each [`crate::Document::index_path`]
/// that it answered. [`crate::Document::node`] reads the node from the cache without one.
pub fn path_copies() -> u64 {
PATH_COPIES.get()
}
/// Adds one to [`path_copies`].
fn note_path_copy() {
PATH_COPIES.set(PATH_COPIES.get().saturating_add(1));
}
/// The cache, shared by clones of a document (each checks every path it uses against its own tree),
/// the lookups that missed it, and the nodes removed from the tree since it was built.
#[derive(Default)]
+1 -1
View File
@@ -24,7 +24,7 @@ mod halftone_radii;
pub mod hit;
mod id_index;
pub mod image_quad;
pub use id_index::{path_lookups, tree_walks};
pub use id_index::{path_copies, path_lookups, tree_walks};
pub mod inks;
mod inline;
pub mod intertwine;
+29
View File
@@ -579,3 +579,32 @@ fn nearest_finder_reads_one_path_per_object() {
assert_eq!(path_lookups() - lookups, 0, "lookups by id");
assert_eq!(tree_walks() - walks, 0, "walks of the tree");
}
/// `Document::node` reads a node from the lookup cache without copying its index path, in nested groups and after
/// objects were removed, and finds what a walk finds: 10,000 objects looked up one at a time copy no path.
#[test]
fn node_lookups_copy_no_index_path() {
let (mut d, ids) = squares(10_000);
let layer = d.layers[0].id;
let mut nested = vec![];
for g in 0..50 {
let kids: Vec<Arc<Node>> = (0..4)
.map(|_| {
let id = d.alloc_id();
nested.push(id);
Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()))
})
.collect();
let (gid, inner) = (d.alloc_id(), d.alloc_id());
d.insert(Some(layer), g, Node::group(gid, vec![Arc::new(Node::group(inner, kids))])).unwrap();
}
d.remove_many(&ids[..100]).unwrap();
d.node(layer);
let copies = path_copies();
let found = ids[100..].iter().chain(&nested).filter(|id| d.node(**id).is_some_and(|n| n.id == **id)).count();
assert_eq!(found, ids.len() - 100 + nested.len());
assert_eq!(path_copies() - copies, 0, "index paths copied");
assert!(ids[..100].iter().all(|id| d.node(*id).is_none()), "removed objects are not found");
agree(&d, &ids[..200], "after remove_many");
agree(&d, &nested, "nested");
}
+1 -1
View File
@@ -855,7 +855,7 @@ pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, s
/// write a resolution and a number of bytes.
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
pub use docmenu::guide_indexes;
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
pub(crate) use edit::{Unrecorded, artboard_tool_picks, settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
+27 -2
View File
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Three-Point Arc",
[],
None,
"{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`)} → {id, cx, cy, radius, sweep}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn",
"{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`), join?: bool (default false)} → {id, cx, cy, radius, sweep, joined?}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. With `join`, an end of the arc on an end of an editable open path (inside the isolated group in isolation mode) joins the arc to that path, which keeps its look and, when one end joins, its direction (a path in the selection comes first); with both ends on open path ends the second path joins too, or the path closes when both are its own ends. The result then has `joined: true` and `id` is the joined path (or its compound path). A `join` that is not true or false is an error. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn",
has_doc,
three_point_arc
),
@@ -747,7 +747,8 @@ fn arc(s: &mut Session, p: &Value) -> Result<Value> {
}
/// An open circular arc from `start` to `end` ([`shapes::CircularArc`]): through `through`, or
/// leaving the end `at` names toward `toward`. One undo step, named as an Arc tool drag is.
/// leaving the end `at` names toward `toward`. With `join`, joined to the open paths whose ends
/// its ends lie on ([`super::path::join_arc`]). One undo step, named as an Arc tool drag is.
fn three_point_arc(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "shape.threePointArc";
let point = |key: &str| finite_numbers::<2>(&p[key]).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, format!("`{key}` must be [x, y]")));
@@ -774,8 +775,32 @@ fn three_point_arc(s: &mut Session, p: &Value) -> Result<Value> {
}
_ => return Err(bad(C, "give exactly one of `through` and `toward`")),
};
let join = match p.get("join") {
None => false,
Some(Value::Bool(on)) => *on,
Some(_) => return Err(bad(C, "`join` must be true or false")),
};
let arc = arc.ok_or_else(|| bad(C, "no arc fits these points: two are the same or all three lie on one line"))?;
let path = via.map_or_else(|| arc.to_path(), |v| arc.to_path_via(v));
let ends = if join {
let st = s.doc()?;
let selected = st.selection.objects.clone();
let find = |at| super::path::open_end_at(&st.doc, st.isolation, &selected, at);
(find(start), find(end))
} else {
(None, None)
};
if ends.0.is_some() || ends.1.is_some() {
let sub = path.subpaths.first().cloned().ok_or_else(|| bad(C, "no arc fits these points"))?;
let id = s.edit("Arc", |d, sel| {
let id = super::path::join_arc(d, &sub, ends.0, ends.1)?;
sel.set([id]);
Ok(id)
})?;
return Ok(
json!({ "id": id.0, "joined": true, "cx": arc.center.x, "cy": arc.center.y, "radius": arc.radius, "sweep": arc.sweep.to_degrees() }),
);
}
let look = s.new_art_look(
vectorcraft_color::Paint::None,
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
+18 -8
View File
@@ -268,16 +268,22 @@ fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions)
if !every_page(opened.page_count(), opts) || !opts.layers || !opts.editing_data {
return None;
}
Some(editing_copy_alone(&decoded_copy(opened)?, opts))
// A placeholder page's fonts aren't the art's.
Some(editing_copy_alone(&decoded_copy(opened)?, opts, Default::default()))
}
/// [`from_editing_data_alone`] of `decoded`, the editor's copy already read and decoded, or why it
/// can't be decoded.
fn editing_copy_alone(decoded: &std::result::Result<Vec<u8>, String>, opts: &LoadOptions) -> Result<(Document, Vec<String>)> {
/// can't be decoded, with `widths`, the widths the file's PDF part gives the characters of its
/// fonts, which tell installed copies of a font apart ([`vectorcraft_eps::AiLayers::with_page_widths`]).
fn editing_copy_alone(
decoded: &std::result::Result<Vec<u8>, String>,
opts: &LoadOptions,
widths: vectorcraft_pdf::PageWidths,
) -> Result<(Document, Vec<String>)> {
decoded
.as_ref()
.map_err(Clone::clone)
.and_then(|data| vectorcraft_eps::ai_alone_decoded(data, opts.legacy_names))
.and_then(|data| vectorcraft_eps::ai_alone_decoded(data, opts.legacy_names, widths))
.map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})")))
}
@@ -473,6 +479,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
Err(e) => Err(err(e)),
};
let mut read = restore_or_import(editing, || {
// The widths the PDF part gives the characters of its fonts, which tell installed
// copies of a font apart: read once, when the editing copy is.
let page_widths = std::cell::OnceCell::new();
let widths = || page_widths.get_or_init(|| opened.as_ref().map(vectorcraft_pdf::Opened::page_widths).unwrap_or_default()).clone();
// Type all from the text document and nothing that needs the PDF part: the layers
// alone, the PDF part not imported. Else what was read of the layers is kept for
// reading them with the PDF part.
@@ -480,7 +490,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?)))
{
let pages = o.trim_pages();
match vectorcraft_eps::ai_layers_alone_decoded(private, &pages.sizes, pages.user_unit, opts.legacy_names) {
match vectorcraft_eps::ai_layers_alone_decoded(private, &pages.sizes, pages.user_unit, opts.legacy_names, widths()) {
Ok((mut doc, warnings)) => {
doc.setup.bleed = pages.bleed;
editing_data = true;
@@ -502,9 +512,9 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
// decoded draws nothing either): its notes are at most the page's own.
let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w));
let copy_alone = || match &private {
Some(private) => Some(editing_copy_alone(private, opts)),
Some(private) => Some(editing_copy_alone(private, opts, widths())),
None if layers.is_some() => {
opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts))
opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts, widths()))
}
None => None,
};
@@ -516,7 +526,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
let (doc, warnings, read) = match alone {
Some((doc, warnings)) => (doc, warnings, true),
None => {
let layers = layers.or_else(|| private.map(vectorcraft_eps::AiLayers::decoded));
let layers = layers.or_else(|| private.map(|p| vectorcraft_eps::AiLayers::decoded(p).with_page_widths(widths())));
through_editing_data(layers, opts, r.document, r.warnings, r.user_unit)
}
};
@@ -2234,3 +2234,110 @@ fn an_illustrator_ai_file_opens_with_its_layers_closed() {
assert_eq!(r["restored"], json!(true), "{r}");
assert_eq!(open_rows(&s).1, ["Art", "Hidden"]);
}
/// A `.ai` whose layer `Art` holds one line of type, `Hamburg`, that its text document sets in the
/// font of PostScript name `name` (a font record without a version), and whose PDF part sets it in
/// a subset of that font that gives each character the width `width` gives it, in thousandths of an
/// em. With `square`, the layer and the page have a gray square too. The editing copy's artboard is
/// 200 × 100 pt, and the page `page_width` × 100.
fn type_in_copy_ai(name: &str, square: bool, page_width: f64, width: impl Fn(char) -> f64) -> Vec<u8> {
let story = "Hamburg";
let n = story.chars().count() + 1;
let document = format!(
"/0 << /1 << /0 [ << /0 << /0 << /0 ({name}) >> >> >> ] >> /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\
/1 << /1 [ << /0 << /0 ({story}\r) /5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 {n} >> ] >> \
/6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /0 0 /1 10.0 >> >> >> /1 {n} >> ] >> >> \
/1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8105.5 8176.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \
<< /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 {n} >> >> ] >> ] >> ] >> ] >> ] >> ] >> >> ] /2 << /1 12.0 >> >>\n"
);
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n";
let (art, drawn) =
if square { (format!("0.5 g\n{}f\n{text}", ai::rect(120.0, 20.0, 160.0, 60.0)), "0.5 g 120 20 40 40 re f ") } else { (text.to_string(), "") };
let body = format!(
"%AI3_TemplateBox: 100 50 100 50\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n",
ai::layer("Art", &art),
lines.join("\n")
);
let data = ai::editing_data(200.0, 100.0, &body);
let widths: Vec<String> = (32u8..=126).map(char::from).map(|c| if story.contains(c) { width(c).to_string() } else { "0".into() }).collect();
let page = PdfPage {
resources: format!(
"/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>",
widths.join(" ")
),
entries: format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(1)),
// A page that is only type, with its art box, isn't a placeholder.
art: Some([0.0, 0.0, page_width, 100.0]),
..PdfPage::new(page_width, 100.0, &format!("{drawn}BT /F1 10 Tf 14 65 Td ({story}) Tj ET"))
};
pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len())], None)
}
/// Type from the text document of a `.ai` whose font record keeps no version, where two installed
/// copies of the font share its PostScript name, family and style and differ in their widths, is
/// set in the copy that sets its characters at the widths the file's PDF part gives them: whether
/// its layers open alone, with the PDF part imported, or from the editing copy alone because the PDF
/// part is only type (read after the layers alone, on a page of another size, were not used).
#[test]
fn type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in() {
let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewtest Ink", "PagewtestInk-Regular"));
let trim = LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() };
// (a square beside the type, the page's width, the options, whether the PDF part is imported)
let cases = [
(true, 200.0, &LoadOptions::default(), false),
(true, 200.0, &trim, true),
(false, 200.0, &LoadOptions::default(), false),
(false, 200.0, &trim, true),
(false, 260.0, &LoadOptions::default(), true),
];
for (square, page_width, opts, imported) in cases {
let file = type_in_copy_ai("PagewtestInk-Regular", square, page_width, &width);
let before = vectorcraft_pdf::imports_of(&file);
let loaded = load_with("copies.ai", &file, opts).unwrap();
let case = format!("square {square}, page {page_width}, {:?}: {:?}", opts.crop, loaded.warnings);
assert!(loaded.editing_data, "{case}");
assert_eq!(vectorcraft_pdf::imports_of(&file) > before, imported, "{case}");
let art = loaded.doc.layers[0].children().unwrap();
assert_eq!(art.len(), 1 + usize::from(square), "{case}");
let Some(NodeKind::Text(t)) = art.iter().map(|n| &n.kind).find(|k| matches!(k, NodeKind::Text(_))) else { panic!("type: {case}") };
assert_eq!(t.plain_text(), "Hamburg");
assert_eq!(db.style_face(&t.runs[0].style).unwrap().version, "1.1", "{case}");
}
}
/// Installs two copies of family `family` and PostScript name `name`: Inter as version 1.0, loaded
/// first, and Source Sans 3 as 1.1, whose advances (thousandths of an em) the returned function gives.
fn install_width_copies(family: &str, name: &str) -> impl Fn(char) -> f64 + use<> {
let db = vectorcraft_text::FontDb::global();
for (inter, version) in [(true, "1.0"), (false, "1.1")] {
let font = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", version, name)).unwrap();
assert_eq!(db.add_font(font), 1);
}
let newer = db.postscript_faces(name).into_iter().find(|f| f.version == "1.1").unwrap();
move |c: char| newer.advance(newer.glyph_for(c)) * 1000.0 / newer.units_per_em()
}
/// Type the PDF part's widths set in the second copy of its font is saved as `.ai` with that
/// copy's version in its font record, so it opens in the same copy again, from the editing copy
/// alone as from the whole file.
#[test]
fn type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save() {
let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewrt Ink", "PagewrtInk-Regular"));
let mut s = Session::new();
let r = open(&mut s, "copies.ai", &type_in_copy_ai("PagewrtInk-Regular", true, 200.0, &width), json!({})).unwrap();
let saved = s.execute("file.saveCopy", &json!({"format": "ai"})).unwrap();
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let versions = |doc: &vectorcraft_doc::Document| -> Vec<String> {
let art = doc.layers[0].children().unwrap();
art.iter()
.filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(db.style_face(&t.runs[0].style).unwrap().version.clone()) } else { None })
.collect()
};
assert_eq!(versions(&s.doc().unwrap().doc), ["1.1"], "{r}");
let loaded = load_with("saved.ai", &bytes, &LoadOptions { native: false, ..Default::default() }).unwrap();
assert!(loaded.editing_data, "{:?}", loaded.warnings);
assert_eq!(versions(&loaded.doc), ["1.1"], "{:?}", loaded.warnings);
let private = vectorcraft_pdf::illustrator_data(&bytes, None).unwrap();
assert_eq!(versions(&vectorcraft_eps::ai_alone(&private).unwrap().0), ["1.1"]);
}
@@ -602,6 +602,53 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() {
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again");
}
/// Place with Replace of an image changed by Perspective Distort or Free Distort by a clipped PSD
/// file with many more pixels keeps its corners when the image is tiny: the new image's transform
/// is the old one scaled down to the new pixel size, which is invertible however small it is.
#[test]
fn replacing_a_tiny_distorted_image_by_a_large_clipped_psd_keeps_its_corners() {
let dir = vectorcraft_testkit::TempDir::new("psd-replace-tiny-distorted");
let plane = vec![255u8; 2000 * 2000];
let zero = vec![0u8; 2000 * 2000];
let big = psd(1, 3, (2000, 2000), 8, 3, &[], &triangle_resources(), &[], &raw(&[&plane, &zero, &zero]));
let cut = write_file(&dir, "big.psd", &big);
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let png = crate::tests_links::png(4, 4, [0, 0, 255]);
let r = s
.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": [100, 100, 0.001, 0.001]}))
.unwrap();
let old = NodeId(r["ids"][0].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [old.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[100, 100], [100.001, 100.0001], [100.0009, 100.001], [99.9998, 100.0008]]})).unwrap();
assert!(s.doc().unwrap().doc.node(old).unwrap().is_distorted_image(), "the old image is distorted");
let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap();
let r = s.execute("file.place", &json!({"path": cut, "replace": true})).unwrap();
let image = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone();
assert!(image.is_distorted_image());
assert_eq!(image.image_corners().unwrap(), corners);
}
/// Place with Replace of a clipped PSD file's image changed by Perspective Distort or Free Distort
/// by a DCS file keeps the image's corners: the DCS file's image fills them.
#[test]
fn replacing_a_distorted_clipped_psd_by_a_dcs_file_keeps_its_corners() {
let dir = vectorcraft_testkit::TempDir::new("psd-replace-distorted-dcs");
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
let dcs = write_file(&dir, "pic.eps", &crate::tests::dcs::two_plates());
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap();
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
let corners = s.doc().unwrap().doc.node(image).unwrap().image_corners().unwrap();
let r = s.execute("file.place", &json!({"path": dcs, "replace": true})).unwrap();
let new = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone();
assert!(new.is_distorted_image(), "the DCS file's image takes the corners");
assert_eq!(new.image_corners().unwrap(), corners);
}
/// links.relink follows the clipping path of a linked PSD file for an image changed by Perspective
/// Distort or Free Distort too: the new file's clipping path is mapped through the image's corners,
/// a clip group of the old file's clipping path loses it when the new file names none, and a later
@@ -456,6 +456,30 @@ fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() {
}
}
/// A file placed with Replace over an image changed by Perspective Distort or Free Distort takes
/// its corners, and its slices cover what the corners put their part of the pixels on.
#[test]
fn slices_placed_over_a_distorted_image_follow_its_corners() {
let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 10, 10])], &[]));
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let png = crate::tests_links::png(4, 4, [0, 0, 255]);
s.execute("file.place", &json!({"name": "a.png", "dataBase64": b64(&png), "at": [100, 100]})).unwrap();
s.execute("object.distort", &json!({"corners": [[100, 100], [160, 104], [150, 140], [96, 136]]})).unwrap();
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "replace": true})).unwrap();
assert_eq!(r["slices"].as_array().map(Vec::len), Some(1), "{r}");
let d = &s.doc().unwrap().doc;
let image = d.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
assert!(image.is_distorted_image());
let vectorcraft_doc::NodeKind::Image(im) = &image.kind else { panic!("an image") };
// The top left quarter of the 20 × 20 px canvas.
let (w, h) = (f64::from(im.width) / 2.0, f64::from(im.height) / 2.0);
let want = image.image_map().unwrap().map_rect_bbox(Rect::new(0.0, 0.0, w, h)).unwrap();
let got = slices(&s)[0].0;
let near = |a: f64, b: f64| (a - b).abs() < 1e-6;
assert!(near(got.x0, want.x0) && near(got.y0, want.y0) && near(got.x1, want.x1) && near(got.y1, want.y1), "{got:?} vs {want:?}");
}
#[test]
fn linked_files_are_placed_without_their_slices() {
let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id()));
+1 -1
View File
@@ -1314,7 +1314,7 @@ fn refill_distorted(
/// `path` with its anchors and handles mapped through `map` as a distort maps a path's points
/// (`xform::Projective::apply`): a point on the map's horizon is mapped as if a billionth in front
/// of it, and one past it to the far side. `None` when a point maps to no finite page point.
fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
pub(super) fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
let [[a, b, c], [d, e, f], [g, h, i]] = map.0;
let apply = |p: vectorcraft_geom::Point| {
let w = g * p.x + h * p.y + i;
+3 -1
View File
@@ -2000,6 +2000,8 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
Some(ids) => ids,
None => super::edit::selected_roots(s)?,
};
// Read before the default is recolored, so that a bad `target` or `aligned` is refused with nothing selected too.
let item = item_target(s, p, cmd)?;
if ids.is_empty() {
let def = if stroke { &mut s.paint.stroke } else { &mut s.paint.fill };
let changed = super::colorcmds::map_paint(def, f);
@@ -2007,7 +2009,7 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
s.remember_paint(&shown);
return Ok(json!({ "changed": changed as usize }));
}
let item = item_target(s, p, cmd)?.of_kind(s, !stroke);
let item = item.of_kind(s, !stroke);
// Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has
// no row for) is still an error.
let targets = super::appearance::drop_design_art_rows(s, item.targets_for(s, p, !stroke)?, item, !stroke, cmd)?;
+89 -3
View File
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Direction Handles",
[],
None,
"{handles: [{id, subpath?, anchor, which: \"in\"|\"out\"}, ...], dx, dy, independent?: bool} move several direction handles by (dx, dy) as one undo step; an anchor with one handle listed moves it as path.setHandle does (a smooth anchor turns its other handle in line at its own length), and an anchor with both handles listed moves both and becomes a corner; independent (default false) makes every listed handle's anchor a corner and leaves its other handle; a handle listed twice moves once; an empty list, a missing or unknown path, subpath or anchor, or a which other than \"in\" or \"out\" is refused",
"{handles: [{id, subpath?, anchor, which: \"in\"|\"out\"}, ...], dx, dy, independent?: bool} move several direction handles by (dx, dy) as one undo step; an anchor with one handle listed moves it as path.setHandle does (a smooth anchor turns its other handle in line at its own length), and an anchor with both handles listed moves both and becomes a corner; independent (default false) makes every listed handle's anchor a corner and leaves its other handle; a handle listed twice moves once; a move by 0, 0 changes only the anchors it makes corners, so a live shape with no such anchor stays live and one with such an anchor becomes a plain path, and with none it changes nothing and records no undo step; an empty list, a missing or unknown path, subpath or anchor, or a which other than \"in\" or \"out\" is refused",
has_doc,
move_handles
),
@@ -643,8 +643,9 @@ fn move_handles(s: &mut Session, p: &Value) -> Result<Value> {
}
// A move by nothing changes only the kind of anchors that become corners: those with both
// handles listed, or every listed one with `independent`.
// The other anchors are left out, so a live shape that only they lie on is not expanded.
if d == Vec2::ZERO {
let corners = anchors.iter().any(|(&(id, si, ai), &(inn, out))| {
anchors.retain(|&(id, si, ai), &mut (inn, out)| {
(independent || (inn && out))
&& doc
.node(id)
@@ -652,7 +653,7 @@ fn move_handles(s: &mut Session, p: &Value) -> Result<Value> {
.and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai))
.is_some_and(|a| a.kind != AnchorKind::Corner)
});
if !corners {
if anchors.is_empty() {
return ok();
}
}
@@ -1593,6 +1594,91 @@ fn join_pair(d: &mut Document, (a, sa): (NodeId, usize), (b, sb): (NodeId, usize
Ok(compound_or_self(d, a))
}
/// An end of an open subpath of an editable path (not a guide) at `at`: the path, the subpath and
/// whether the end is the subpath's first anchor. In isolation mode (`scope`), only a path inside
/// the isolated node counts. Among several, one in or inside the selection `selected` comes first,
/// then the last in paint order.
pub(super) fn open_end_at(d: &Document, scope: Option<NodeId>, selected: &[NodeId], at: Point) -> Option<(NodeId, usize, bool)> {
let editable = d.editable();
let mut found: Option<((NodeId, usize, bool), bool)> = None;
d.walk(|n| {
let NodeKind::Path { path, guide: false, .. } = &n.kind else { return };
if !editable(n.id) {
return;
}
let chain = d.ancestry(n.id).unwrap_or_default();
if scope.is_some_and(|s| !chain.contains(&s)) {
return;
}
let chosen = chain.iter().any(|id| selected.contains(id));
for (si, sp) in path.subpaths.iter().enumerate().filter(|(_, sp)| !sp.closed) {
let Some((first, last)) = end_points(sp) else { continue };
let end = if last.distance(at) < 1e-6 {
false
} else if first.distance(at) < 1e-6 {
true
} else {
continue;
};
if found.is_none_or(|(_, was)| chosen || !was) {
found = Some(((n.id, si, end), chosen));
}
}
});
found.map(|(end, _)| end)
}
/// `sp`, an open subpath whose end (its first anchor when `at_first`) lies on an end of `arc`
/// (its first anchor when `arc_at_start`), with `arc` added there: one subpath running the way
/// `sp` runs. The anchor where they meet is `sp`'s, with its handle on the arc's side taken from
/// the arc.
fn splice(sp: &SubPath, at_first: bool, arc: &SubPath, arc_at_start: bool) -> SubPath {
let mut arc = arc.clone();
if arc_at_start == at_first {
arc.reverse();
}
let mut out = sp.clone();
if at_first {
let meet = arc.anchors.pop();
if let (Some(meet), Some(first)) = (meet, out.anchors.first_mut()) {
first.h_in = meet.h_in;
}
arc.anchors.extend(out.anchors);
out.anchors = arc.anchors;
} else {
if !arc.anchors.is_empty() {
let meet = arc.anchors.remove(0);
if let Some(last) = out.anchors.last_mut() {
last.h_out = meet.h_out;
}
}
out.anchors.extend(arc.anchors);
}
out
}
/// The arc `arc` joined to the open path ends `start` (at its first anchor) and `end` (at its
/// last), as [`open_end_at`] gives them, at least one of them. The arc joins the path at `start`
/// first, keeping that path's direction and look, and then, when `end` is an end of another open
/// subpath, that subpath joins it as Join joins two paths; when `end` is the other end of the same
/// subpath, the subpath closes. Returns what to select: the joined path, or its compound path.
pub(super) fn join_arc(d: &mut Document, arc: &SubPath, start: Option<(NodeId, usize, bool)>, end: Option<(NodeId, usize, bool)>) -> Result<NodeId> {
let err = || EngineError::Other("join needs open paths".into());
let ((id, si, at_first), arc_at_start, rest) = match (start, end) {
(Some(s), e) => (s, true, e),
(None, Some(e)) => (e, false, None),
(None, None) => return Err(err()),
};
let path = path_mut(d, id)?;
let sp = path.subpaths.get_mut(si).filter(|sp| !sp.closed && !sp.anchors.is_empty()).ok_or_else(err)?;
*sp = splice(sp, at_first, arc, arc_at_start);
match rest {
// The arc's far end is the first anchor of the joined subpath when it was added before it.
Some((other, osi, other_first)) => join_pair(d, (id, si), (other, osi), (at_first, !other_first), None),
None => Ok(compound_or_self(d, id)),
}
}
pub(super) type AnchorTargets = Vec<(NodeId, Vec<(usize, usize)>)>;
pub(super) fn anchor_targets(s: &Session) -> Result<AnchorTargets> {
+84 -16
View File
@@ -57,7 +57,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SliceOptions, SymbolBoxes};
use vectorcraft_geom::{Affine, Point, Rect, shapes};
use vectorcraft_geom::{Affine, Homography, Point, Rect, shapes};
use vectorcraft_pdf::CropTo;
use super::fileio::{self, Format, RasterImage};
@@ -88,7 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Place…",
["File"],
Some("Cmd+Shift+P"),
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed Line truncated
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; an image changed by Perspective Distort or Free Distort keeps its corners, which a raster image or a DCS file's image fills, with its file's clipping path drawn through them, and other files but text are refused; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 12 Line truncated
has_doc,
place
),
@@ -655,7 +655,7 @@ fn at_param(p: &Value) -> Result<Option<Point>> {
/// The transform that puts new art with the natural box `natural` where `old` is: an image's scale
/// and rotation relative to its 100% size (its resolution's) and its centre are kept (with
/// `image_xf`), also for an image alone in a clip group when the new art is an image, clipped by
/// `image_xf`), also for an image alone in a clip group when the new art is a raster or DCS image, clipped by
/// its file's clipping path or not (`new_image`); other objects keep their centre.
fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image: bool) -> Affine {
let image = replace_measured(d, old, new_image);
@@ -663,7 +663,7 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
let (sx, sy) = pt_per_px(d.images.get(&im.key).and_then(|b| fileio::ppi::resolution(&b.bytes)));
let full = Affine::scale_non_uniform(sx, sy);
let centre = full * Point::new(im.width as f64 / 2.0, im.height as f64 / 2.0);
if im.xf.determinant().abs() > 1e-12 {
if Homography::affine_is_invertible(im.xf) {
return im.xf * full.inverse() * Affine::translate(centre - natural.center());
}
}
@@ -672,8 +672,8 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
}
/// The object [`replace_xf`] measures when Replace swaps `old`: an image alone in a clip group (as
/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is an
/// image (`new_image`), except a DCS file's plates; else `old` itself.
/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is a
/// raster or DCS image (`new_image`), except a DCS file's plates; else `old` itself.
fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Node {
match &old.kind {
NodeKind::Group { children, clip: true } if new_image => match &children[..] {
@@ -687,6 +687,60 @@ fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Nod
}
}
/// What Replace does when the image it measures, `old`, is distorted and the art placed is a
/// raster image or a DCS file's image (`art`): the transform that puts the new pixels on `old`'s
/// transform scaled to their size, as Update Links scales it, the corners the new image takes, and
/// the map from the art's natural box to the page through those corners, which a PSD file's slices
/// follow. `None` for other art, for an image with no pixels, and for corners the new pixels can't
/// fill ([`Node::set_image_corners`]).
fn distorted_replace(old: &Node, art: &Art) -> Option<(Affine, [Point; 4], Homography)> {
let NodeKind::Image(im) = &old.kind else { return None };
let q = old.image_quad()?;
let (pixels, width, height) = match art {
Art::Image(img, _) => {
let (sx, sy) = pt_per_px(img.ppi);
(Affine::scale_non_uniform(sx, sy), img.width, img.height)
}
Art::Dcs(a) => (a.xf, a.img.width, a.img.height),
_ => return None,
};
if width == 0 || height == 0 || !Homography::affine_is_invertible(pixels) {
return None;
}
let xf = im.xf * Affine::scale_non_uniform(f64::from(im.width) / f64::from(width), f64::from(im.height) / f64::from(height));
let new = ImageObject { key: String::new(), width, height, xf, link: None, placement: Default::default(), pixels: None };
let mut probe = Node::new(old.id, NodeKind::Image(Box::new(new)));
probe.set_image_corners(q).ok()?;
let page = probe.image_map()?.checked_then_after(&Homography::from_affine(pixels.inverse()))?;
Some((xf * pixels.inverse(), q, page))
}
/// Placed raster `node` (an image, or an image in a clip group of its file's clipping path, as
/// [`build`] makes them) with the image's corners at `q`: the pixels fill them, and the clipping
/// path is drawn through them as the pixels are. `None` when the corners can't hold the image.
fn with_corners(mut node: Node, q: [Point; 4]) -> Option<Node> {
match &mut node.kind {
NodeKind::Image(_) => node.set_image_corners(q).ok()?,
NodeKind::Group { children, clip: true } => {
let [path, image] = &mut children[..] else { return None };
let image = Arc::make_mut(image);
let NodeKind::Image(im) = &image.kind else { return None };
if !Homography::affine_is_invertible(im.xf) {
return None;
}
// The clipping path in the image's pixels, which its transform placed on the page.
let to_pixels = im.xf.inverse();
image.set_image_corners(q).ok()?;
let map = image.image_map()?;
let NodeKind::Path { path: p, .. } = &mut Arc::make_mut(path).kind else { return None };
p.transform(to_pixels);
*p = super::links::warped(p, &map)?;
}
_ => return None,
}
Some(node)
}
/// `rect` fitted with `natural`'s aspect, centred.
fn fit(natural: Rect, r: Rect) -> Affine {
let ratio = |a: f64, b: f64| (b > 1e-9).then(|| a / b);
@@ -846,19 +900,24 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
loaded.natural = Rect::from_origin_size(Point::ORIGIN, size);
}
let natural = loaded.natural;
// Replace keeps the transform of the image it measures (`replace_measured`), which a
// distortion's corners do not follow. Type, and any other object it measures, is placed by the
// bounds of what it replaces, so a distorted image there is not refused.
// Replace keeps the transform of the image it measures (`replace_measured`). When that image
// is distorted, a raster placed in its place takes its corners ([`distorted_replace`]); other
// art is refused. Type, and any other object it measures, is placed by the bounds of what it
// replaces, so a distorted image there is not refused.
let mut distorted = None;
let new_image = matches!(loaded.art, Art::Image(..) | Art::Dcs(..));
if let Some(o) = old_node
&& !is_text
{
let image = replace_measured(&st.doc, o, matches!(loaded.art, Art::Image(..)));
let image = replace_measured(&st.doc, o, new_image);
if image.is_distorted_image() {
return Err(super::xform::distorted_image_error(PLACE, image.id));
let fit = distorted_replace(image, &loaded.art).ok_or_else(|| super::xform::distorted_image_error(PLACE, image.id))?;
distorted = Some((image.id, fit));
}
}
let m = match (old_node, rect) {
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(..))),
(Some(_), _) if let Some((_, (m, ..))) = distorted => m,
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, new_image),
(None, Some(r)) => fit(natural, r),
// Its artboard's bottom-left corner on the target's.
(None, None) if let (Some(src), Some(to)) = (loaded.board, target) => Affine::translate((to.x0 - src.x0, to.y1 - src.y1)),
@@ -908,13 +967,19 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
if let Art::Dcs(a) = &loaded.art {
warnings.extend(dcs::swatch_notes(&st.doc, &a.spots));
}
// A PSD file's slices move and scale with its art; one that would leave the canvas is left out.
// A PSD file's slices move and scale with its art, through a distorted image's corners when
// it takes them; one that would leave the canvas is left out.
let read_count = read_slices.len();
let slices: Slices = read_slices
.into_iter()
.filter_map(|(r, o)| {
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c);
let placed = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c));
let placed = match distorted {
Some((_, (_, _, page))) => page.map_rect_bbox(r)?,
None => {
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c);
corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c))
}
};
super::slices::slice_rect_ok(placed).then_some((placed, o))
})
.collect();
@@ -924,7 +989,10 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")),
}
let (id, size, slice_ids) = s.edit("Place", |d, sel| {
let node = transformed(build(d, loaded, link), m);
let mut node = transformed(build(d, loaded, link), m);
if let Some((old_image, (_, q, _))) = distorted {
node = with_corners(node, q).ok_or_else(|| super::xform::distorted_image_error(PLACE, old_image))?;
}
let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default();
let (into, index) = match old {
Some(old) => {
@@ -682,6 +682,7 @@ pub(super) const ALLOWED: &[&str] = &[
"text.thread.info",
"text.thread.releaseSelection",
"text.thread.remove",
"text.thread.setNeighbor",
"text.touchType",
"threeD.addGraphic",
"threeD.mapArt",
+4 -1
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Script",
[],
None,
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s resul Line truncated
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event Line truncated
always,
run
),
@@ -195,6 +195,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
if s.script_frames && !answers.is_empty() {
return Err(param("`answers` is only for a run with nobody to ask: in the app, the person answers each dialog"));
}
let actions = script::actions::parse(p.get("actions")).map_err(param)?;
let fuel = max_fuel(p)?;
let installed = switch_or(p, "installed", false, "script.run")?;
let mut checked_real = None;
@@ -241,6 +242,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
fuel,
locale,
answers,
actions,
})
}
@@ -442,6 +444,7 @@ impl Session {
fuel,
locale,
answers: vec![],
actions: vec![],
};
let runs = self.script_runs;
self.script_start(request).map_err(|e| {
+115
View File
@@ -59,6 +59,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
break_thread
),
cmd!(
"text.thread.setNeighbor",
"Thread Text",
[],
None,
"{id, side: \"next\"|\"previous\", neighbor: id|null} link area type or type on a path `id` to the frame that follows it (`next`) or comes before it (`previous`) in its story, or with null break that one link, as a script's `nextFrame` and `previousFrame` assignments do. Linking joins two stories: `id` must be the last frame of its story for `next` (the first for `previous`) and `neighbor` the first (the last) of another one, and the second story's text flows on after the first's. Breaking a link makes each side of it a story of its own: no text moves across the break, and the frames after it flow their own text again from their first frame, which now starts a paragraph. An error, with nothing changed, for point type or other art, a frame linked to itself, a link that would make a loop or go to a frame inside a story, and a frame of either story that is hidden or locked; a link that is already there, or a break where there is no link, changes nothing and records no undo step; the selection is kept → {changed: bool, threads: [[id…]] (the stories of the frames involved, after the change, a one-frame story as [id])}",
has_doc,
set_neighbor
),
cmd!(query "text.thread.info", "Threads", [], None, "{} → [[id…]] every thread in order", has_doc, |s, _| {
Ok(json!(s.doc()?.doc.text_threads.iter().map(|t| t.iter().map(|i| i.0).collect::<Vec<_>>()).collect::<Vec<_>>()))
}),
@@ -986,5 +995,111 @@ fn break_thread(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// The frames of the story `id` is a frame of, in thread order: its thread's area type and type on
/// a path, each once, or `id` alone when it is in no thread.
fn chain_of(d: &Document, id: NodeId) -> Vec<NodeId> {
let mut frames = story_of(d, id);
let mut seen = Ids::default();
frames.retain(|f| seen.insert(*f));
if frames.len() < 2 { vec![id] } else { frames }
}
fn chain_ids(chains: &[&[NodeId]]) -> Value {
json!(chains.iter().filter(|c| !c.is_empty()).map(|c| c.iter().map(|i| i.0).collect::<Vec<_>>()).collect::<Vec<_>>())
}
/// `text.thread.setNeighbor`: link a frame to the frame after or before it, or break that link.
fn set_neighbor(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.thread.setNeighbor";
let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?;
let next = match p.get("side").and_then(Value::as_str) {
Some("next") => true,
Some("previous") => false,
_ => return Err(bad(C, "`side` must be \"next\" or \"previous\"")),
};
let neighbor = match p.get("neighbor") {
None => return Err(bad(C, "missing `neighbor` (an id, or null to break the link)")),
Some(Value::Null) => None,
Some(v) => Some(checked_id(s, v, C)?),
};
let d = &s.doc()?.doc;
if text_of(d, id).is_none() {
return Err(bad(C, "`id` must be area type or type on a path"));
}
let locked = |frames: &[NodeId]| {
let editable = d.editable();
frames.iter().any(|f| !editable(*f))
};
let chain = chain_of(d, id);
let Some(n) = neighbor else {
// Break the link on that side: the frames before it and the frames after it.
let i = chain.iter().position(|f| *f == id).unwrap_or(0);
let at = if next { i + 1 } else { i };
if at == 0 || at >= chain.len() {
return Ok(json!({"changed": false, "threads": chain_ids(&[&chain])}));
}
if locked(&chain) {
return Err(bad(C, "a frame of the story is hidden or locked"));
}
let (head, tail) = (chain[..at].to_vec(), chain[at..].to_vec());
let cut: Ids = chain.iter().copied().collect();
s.edit("Break Thread", |d, _| {
d.text_threads.retain(|t| !t.iter().any(|f| cut.contains(f)));
for part in [&head, &tail] {
if part.len() >= 2 {
d.text_threads.push(part.clone());
}
}
// The first frame after the break starts its story, which flows again on this edit so
// that its numbered paragraphs count from 1.
if let Some(f) = tail.first() {
touch(d, *f);
}
if let Some(NodeKind::Text(t)) = tail.first().and_then(|f| d.node_mut(*f)).map(|n| &mut n.kind)
&& t.first_para_continues
{
t.first_para_continues = false;
refresh_bounds(t);
}
Ok(())
})?;
return Ok(json!({"changed": true, "threads": chain_ids(&[&head, &tail])}));
};
if n == id {
return Err(bad(C, "a frame cannot be linked to itself"));
}
if text_of(d, n).is_none() {
return Err(bad(C, "`neighbor` must be area type or type on a path"));
}
// `first` is to flow into `second`.
let (first, second) = if next { (id, n) } else { (n, id) };
let (a, b) = if next { (chain, chain_of(d, n)) } else { (chain_of(d, n), chain) };
if a.contains(&second) {
if a.windows(2).any(|w| w == [first, second]) {
return Ok(json!({"changed": false, "threads": chain_ids(&[&a])}));
}
return Err(bad(C, "the two frames are already in one story: the link would make a loop or reorder it"));
}
if a.last() != Some(&first) {
return Err(bad(C, format!("frame {} already has a next frame: break that link first", first.0)));
}
if b.first() != Some(&second) {
return Err(bad(C, format!("frame {} already has a previous frame: break that link first", second.0)));
}
if locked(&a) || locked(&b) {
return Err(bad(C, "a frame of either story is hidden or locked"));
}
let joined: Vec<NodeId> = a.iter().chain(&b).copied().collect();
let affected: Ids = joined.iter().copied().collect();
s.edit("Thread Text", |d, _| {
d.text_threads.retain(|t| !t.iter().any(|f| affected.contains(f)));
d.text_threads.push(joined.clone());
// Force a re-flow of the joined story on this edit.
touch(d, first);
Ok(())
})?;
Ok(json!({"changed": true, "threads": chain_ids(&[&joined])}))
}
#[cfg(test)]
mod tests;
+354
View File
@@ -0,0 +1,354 @@
//! `app.doScript(action, set, dialogs?)`: plays an action of the Actions panel inside the script's
//! run, as the VBScript reference's `DoScript` method of the Application object describes it
//! (<https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf>).
//!
//! The actions a run can play come with its request (`script.run`'s `actions`), each with the steps
//! that playback runs: the included steps, those of a recorded `command.batch` one by one. In the app
//! they are the Actions panel's.
//!
//! VectorCraft's own rules, which the reference does not state:
//! - The action and its set are matched by their exact names; a name that matches no action, or
//! more than one, throws before any step runs.
//! - The call returns when every step has run, or when the run is asked to stop. Each step runs as `vc.run` runs a command: it joins
//! the run's transaction and its one undo step for each changed document, it is counted as a host
//! call, it reads and writes files only where the script may, and a step that fails is put back
//! and throws an error that names the step and the action, while the steps before it stay done.
//! - A step a script may not run ([`super::refused_to_scripts`]), a step whose command the engine
//! does not have (a View menu step, or one that plays an action), and a stop throw before any step
//! runs, as does such a command among those an `action.batch` step plays. An action cannot play
//! another action, so it cannot play itself.
//! - `dialogs` is `true` or `false` (default `false`); VectorCraft's steps open no dialogs, so it
//! changes nothing.
use std::rc::Rc;
use serde_json::{Map, Value, json};
use vectorcraft_js::{Data, HostError, HostMember};
use super::{Host, Link, command, current, refused_to_scripts};
/// The most actions a run's request may carry.
pub const MAX_ACTIONS: usize = 4096;
/// The most steps one action may have, after a `command.batch` step gives its own steps.
pub const MAX_ACTION_STEPS: usize = 10_000;
/// The most steps the actions of one request may have in all.
pub const MAX_ALL_STEPS: usize = 100_000;
/// The most bytes of the request's actions, as JSON.
pub const MAX_ACTIONS_BYTES: usize = 16 << 20;
/// The longest name of an action or a set, in bytes.
pub const MAX_NAME_BYTES: usize = 1024;
/// The longest command id of a step, in bytes.
const MAX_ID_BYTES: usize = 256;
/// The command id of a stop, which waits for the person in the Actions panel.
pub const STOP_STEP: &str = "action.stop";
/// An action a run can play: its set's name, its name and the steps playback runs.
#[derive(Clone, Debug)]
pub struct Playable {
set: String,
name: String,
steps: Vec<Step>,
}
/// A step of a [`Playable`]: its place in the action as errors give it (1 for the first; a step of a
/// `command.batch` step has the batch's place and its own, as in `3.2`), its command, its params and
/// their size as JSON, and for a step of a `command.batch` step the `artboard` that batch names.
#[derive(Clone, Debug)]
struct Step {
place: String,
id: String,
params: Value,
bytes: u64,
artboard: Option<u64>,
}
/// `script.run`'s `actions`: `[{set, name, steps: [{command, params?, step?}]}]`, where `step` is the
/// step's place in the action (1 for the first; default its place in the list), within the limits
/// above. A `command.batch` step gives its own steps, each at the batch's place and its own.
pub fn parse(v: Option<&Value>) -> Result<Vec<Playable>, String> {
let Some(v) = v else { return Ok(Vec::new()) };
let Value::Array(list) = v else { return Err("`actions` must be a list".into()) };
if list.len() > MAX_ACTIONS {
return Err(format!("`actions` holds more than {MAX_ACTIONS} actions"));
}
if let Some(place) = super::too_deep(v) {
return Err(format!("`actions{place}` is nested more than 64 levels deep"));
}
if serde_json::to_vec(v).map_or(true, |b| b.len() > MAX_ACTIONS_BYTES) {
return Err("`actions` is larger than 16 MiB".into());
}
let mut all = 0usize;
let mut out = Vec::with_capacity(list.len());
for (i, a) in list.iter().enumerate() {
let at = format!("`actions[{i}]`");
let Value::Object(a) = a else { return Err(format!("{at} must be an object")) };
only_keys(a, &["set", "name", "steps"], &at)?;
let set = name_of(a, "set", &at)?;
let name = name_of(a, "name", &at)?;
let Some(Value::Array(given)) = a.get("steps") else { return Err(format!("{at}.steps must be a list")) };
let mut steps = Vec::new();
for (j, s) in given.iter().enumerate() {
let at = format!("{at}.steps[{j}]");
let Value::Object(s) = s else { return Err(format!("{at} must be an object")) };
only_keys(s, &["command", "params", "step"], &at)?;
let place = match s.get("step") {
None => (j + 1).to_string(),
Some(n) => match n.as_u64().filter(|n| (1..=1_000_000).contains(n)) {
Some(n) => n.to_string(),
None => return Err(format!("{at}.step must be a whole number from 1 to 1000000")),
},
};
let (id, params) = command_of(s, &at)?;
match params.get("commands") {
Some(Value::Array(inner)) if id == "command.batch" => {
// The batch's `artboard`, for its steps that act on the active artboard, as
// `command.batch` reads it.
let artboard = params.get("artboard").and_then(Value::as_u64);
for (k, c) in inner.iter().enumerate() {
let at = format!("{at}.params.commands[{k}]");
let Value::Object(c) = c else { return Err(format!("{at} must be an object")) };
let (id, params) = command_of(c, &at)?;
if id == "command.batch" {
return Err(format!("{at} is a command.batch inside a command.batch"));
}
steps.push(step(format!("{place}.{}", k + 1), id, params, artboard));
}
}
_ if id == "command.batch" => return Err(format!("{at}.params.commands must be a list")),
_ => steps.push(step(place, id, params, None)),
}
if steps.len() > MAX_ACTION_STEPS {
return Err(format!("{at}: the action has more than {MAX_ACTION_STEPS} steps"));
}
}
all += steps.len();
if all > MAX_ALL_STEPS {
return Err(format!("`actions` has more than {MAX_ALL_STEPS} steps in all"));
}
out.push(Playable { set, name, steps });
}
Ok(out)
}
impl Playable {
/// The steps the action runs.
pub fn len(&self) -> usize {
self.steps.len()
}
/// Whether the action runs no step.
pub fn is_empty(&self) -> bool {
self.steps.is_empty()
}
}
fn only_keys(o: &Map<String, Value>, keys: &[&str], at: &str) -> Result<(), String> {
match o.keys().find(|k| !keys.contains(&k.as_str())) {
Some(k) => Err(format!("{at} has the unknown key `{}`", shown(k))),
None => Ok(()),
}
}
fn name_of(o: &Map<String, Value>, key: &str, at: &str) -> Result<String, String> {
match o.get(key) {
Some(Value::String(s)) if s.len() <= MAX_NAME_BYTES => Ok(s.clone()),
Some(Value::String(_)) => Err(format!("{at}.{key} is longer than {MAX_NAME_BYTES} bytes")),
_ => Err(format!("{at}.{key} must be a string")),
}
}
/// A step's `command` and `params` (default `{}`).
fn command_of(o: &Map<String, Value>, at: &str) -> Result<(String, Value), String> {
let id = match o.get("command") {
Some(Value::String(id)) if !id.is_empty() && id.len() <= MAX_ID_BYTES => id.clone(),
_ => return Err(format!("{at}.command must be a command id")),
};
let params = match o.get("params") {
None => json!({}),
Some(p @ Value::Object(_)) => p.clone(),
Some(_) => return Err(format!("{at}.params must be an object")),
};
Ok((id, params))
}
fn step(place: String, id: String, params: Value, artboard: Option<u64>) -> Step {
let bytes = serde_json::to_vec(&params).map_or(0, |b| b.len() as u64);
Step { place, id, params, bytes, artboard }
}
/// `text` as an error shows it: at most 80 characters, with … after a cut, and control characters
/// as U+FFFD.
fn shown(text: &str) -> String {
const MAX: usize = 80;
let mut out: String = text.chars().take(MAX).map(|c| if c.is_control() { '\u{fffd}' } else { c }).collect();
if text.chars().nth(MAX).is_some() {
out.push('…');
}
out
}
/// The members of `app` this module adds.
pub(super) fn app_members(link: &Link) -> Vec<super::dom::Described> {
let l = link.clone();
let play = Rc::new(move |a: Vec<Data>| {
let h = current(&l)?;
h.charge_call(16 + a.iter().map(super::data_size).sum::<u64>())?;
do_script(&h, &a)
});
let info = super::dom::returns("undefined", &[("action", "string"), ("set", "string"), ("dialogs", "boolean")]);
let mut members = vec![("doScript".to_string(), HostMember::Method(play), info)];
members.extend(["loadAction", "unloadAction"].map(|name| super::dom::later(link, "Application", name)));
members
}
fn arg(a: &[Data], i: usize) -> &Data {
a.get(i).unwrap_or(&Data::Undefined)
}
/// `app.doScript(action, set, dialogs?)`, its arguments after `this`.
fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
if a.len() > 4 {
return Err(HostError::Type("doScript takes an action's name, its set's name and dialogs".into()));
}
let (Data::String(action), Data::String(set)) = (arg(a, 1), arg(a, 2)) else {
return Err(HostError::Type("doScript needs the action's name and its set's name, as strings".into()));
};
if action.is_empty() || set.is_empty() {
return Err(HostError::Error("doScript needs the action's name and its set's name".into()));
}
if action.len() > MAX_NAME_BYTES || set.len() > MAX_NAME_BYTES {
return Err(HostError::Range(format!("an action's or a set's name is at most {MAX_NAME_BYTES} bytes")));
}
if !matches!(arg(a, 3), Data::Undefined | Data::Bool(_)) {
return Err(HostError::Type("doScript's dialogs must be true or false".into()));
}
let found: Vec<&Playable> = h.actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect();
let p = match found.as_slice() {
[p] => *p,
[] if !h.actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))),
[] => return Err(HostError::Error(format!("the set “{}” has no action “{}”", shown(set), shown(action)))),
_ => return Err(HostError::Error(format!("the set “{}” has more than one action “{}”", shown(set), shown(action)))),
};
if p.steps.is_empty() {
return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name))));
}
// Every step is checked before the first runs, so a step that cannot run leaves the documents as
// they were.
for s in &p.steps {
if let Some((place, id)) = refused_step(s) {
let name = shown(&p.name);
return Err(HostError::Error(if id == STOP_STEP {
format!("step {place} of “{name}” is a stop, which a script cannot wait at")
} else {
format!("step {place} of “{name}” runs `{}`, which a script cannot run", shown(&id))
}));
}
}
for s in &p.steps {
// A run asked to stop runs no further step; the realm ends it at its next instruction and
// puts the documents back.
if h.session.borrow().script_stop.is_set() {
break;
}
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
// passed over.
let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard };
let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params);
let outer = h.session.borrow_mut().set_replaying(true);
let r = command(h, &s.id, &params);
h.session.borrow_mut().set_replaying(outer);
if let Err(e) = r {
let named = |m: String| format!("action step {} of “{}” (`{}`) failed: {m}", s.place, shown(&p.name), shown(&s.id));
return Err(match e {
HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) => HostError::Error(named(m)),
other => other,
});
}
}
Ok(Data::Undefined)
}
/// The place and command of the first command step `s` would run that a script may not run: the
/// step itself, or one of the `commands` an `action.batch` step plays on each file (placed as the
/// batch's place and its own, as in `3.2`). A stop, a command a script may not run and a command the
/// engine does not have are refused.
fn refused_step(s: &Step) -> Option<(String, String)> {
let refused = |id: &str| id == STOP_STEP || refused_to_scripts(id) || crate::find_command(id).is_none();
if refused(&s.id) {
return Some((s.place.clone(), s.id.clone()));
}
if s.id != "action.batch" {
return None;
}
let commands = s.params.get("commands").and_then(Value::as_array)?;
commands.iter().enumerate().find_map(|(k, c)| {
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
refused(id).then(|| (format!("{}.{}", s.place, k + 1), id.to_owned()))
})
}
/// `params` of step `id`, with the active artboard of the active document added as a
/// `command.batch` given that artboard adds it when the Actions panel plays the step: `artboard` for
/// the commands that act on the active artboard, `index` for Fit to Artwork Bounds and Fit to
/// Selected Art. The active artboard is the index `start` gives for the document (its index as the
/// run started, which the view keeps), past the last artboard the last one, as the view shows it
/// after a step deletes artboards; a document the run opened has its own ([`super::dom`]'s). While
/// the Artboard tool has several artboards selected, a Fit to Artwork Bounds step gets those as its
/// `indices` instead, and a paste step gets none (it pastes on them). The run gives the tool fresh
/// state, which drops its selection, so while the tool is still the Artboard tool and has none, the
/// selection [`Start::picks`] holds for the document as the run started applies: a Fit to Artwork
/// Bounds step gets those as its `indices` and a paste step as its `artboards`, the ones past the
/// last artboard left out, and only while two or more remain. A step of a recorded `command.batch`
/// that names its `artboard` ([`Start::batch`]) gets that artboard instead of the active one, past
/// the last artboard the last one, and none in a document without artboards, as `command.batch`
/// gives it. A paste step in a document without artboards, or one that names `artboards`, and a Fit
/// to Artwork Bounds step that names `indices`, get none. A key the step gives is kept.
pub(crate) fn on_active_artboard(s: &crate::Session, start: &Start<'_>, id: &str, params: &Value) -> Value {
let mut params = params.clone();
let Some(st) = s.active() else { return params };
let n = st.doc.artboards.len();
let active = match (start.batch, start.active.iter().find(|(uid, _)| *uid == st.uid)) {
(Some(_), _) if n == 0 => return params,
(Some(a), _) => usize::try_from(a).map_or(n - 1, |a| a.min(n - 1)),
(None, Some((_, i))) => (*i).min(n.saturating_sub(1)),
(None, None) => super::dom::active_artboard(st),
};
let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack");
let fit_art = id == "artboard.fitToArt";
let key = if crate::ON_ACTIVE_ARTBOARD.contains(&id) {
"artboard"
} else if crate::FIT_ACTIVE_ARTBOARD.contains(&id) {
"index"
} else {
return params;
};
let Some(p) = params.as_object_mut() else { return params };
if p.contains_key(key) || (fit_art && p.contains_key("indices")) || (paste && (n == 0 || p.contains_key("artboards"))) {
return params;
}
let picks = if paste || fit_art { crate::cmd::artboard_tool_picks(s) } else { Vec::new() };
let kept: Vec<usize> = match start.picks {
Some((uid, list)) if picks.is_empty() && (paste || fit_art) && *uid == st.uid && s.tool_id() == "artboard" => {
list.iter().copied().filter(|i| *i < n).collect()
}
_ => Vec::new(),
};
if kept.len() >= 2 {
p.insert((if fit_art { "indices" } else { "artboards" }).into(), json!(kept));
} else if picks.is_empty() {
p.insert(key.into(), json!(active));
} else if fit_art {
p.insert("indices".into(), json!(picks));
}
params
}
/// What [`on_active_artboard`] reads besides the session: the index of each open document's active
/// artboard as the run started, by document uid; the Artboard tool's selection as the run started,
/// with its document's uid; and the `artboard` a step's recorded `command.batch` names.
pub(crate) struct Start<'a> {
pub active: &'a [(u64, usize)],
pub picks: Option<&'a (u64, Vec<usize>)>,
pub batch: Option<u64>,
}
+58 -22
View File
@@ -293,7 +293,7 @@ fn method(link: &Link, f: Member) -> HostMember {
}
/// A member of a class with what `reflect` tells of it.
type Described = (String, HostMember, MemberInfo);
pub(super) type Described = (String, HostMember, MemberInfo);
/// A property's or a method's result's type for `reflect`.
fn typed(data_type: &str) -> MemberInfo {
@@ -301,7 +301,7 @@ fn typed(data_type: &str) -> MemberInfo {
}
/// A method's result's type and its arguments' names and types, for `reflect`.
fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect();
MemberInfo { arguments, ..typed(data_type) }
}
@@ -309,7 +309,7 @@ fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
/// A member the help pages list that is not available yet: reading or assigning it throws, after
/// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is
/// false for it, so a script that checks for the member first skips it, and `reflect` leaves it out.
fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
let message = format!("{class}.{name} is not available yet");
let l = link.clone();
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
@@ -571,7 +571,7 @@ struct Frame {
}
/// The index of the active artboard of `st`, as the view keeps it.
fn active_artboard(st: &DocState) -> usize {
pub(super) fn active_artboard(st: &DocState) -> usize {
let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id);
st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0)
}
@@ -951,11 +951,19 @@ fn front_docs(s: &Session) -> impl Iterator<Item = &DocState> {
s.front_order().into_iter().map(|i| &s.documents()[i])
}
/// `documents[i]`, and `documents["name"]` as `getByName` reads it.
/// `documents[i]`, and `documents["name"]` as `getByName` reads it. A key that is the text of a
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
/// looked up as that name, giving `undefined` when no document has it.
fn docs_at(h: &Host, a: &[Data]) -> Answer {
let s = h.session.borrow();
let at = match arg(a, 1) {
Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| front_docs(&s).nth(i)),
Data::Number(n) => match position(*n) {
Some(i) => front_docs(&s).nth(i),
None => {
let name = vectorcraft_js::number_to_string(*n);
front_docs(&s).find(|d| d.title() == name)
}
},
Data::String(name) => match front_docs(&s).find(|d| d.title() == *name) {
None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())),
found => found,
@@ -975,10 +983,11 @@ fn docs_by_name(h: &Host, a: &[Data]) -> Answer {
fn docs_index(h: &Host, a: &[Data]) -> Answer {
match arg(a, 1) {
Data::String(_) => docs_by_name(h, a),
Data::Number(_) => match docs_at(h, a)? {
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
d => Ok(d),
},
Data::Number(n) => {
let s = h.session.borrow();
let st = position(*n).and_then(|i| front_docs(&s).nth(i)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?;
Ok(doc_ref(h, st.uid))
}
_ => Err(HostError::Type("give a name or an index".into())),
}
}
@@ -1820,27 +1829,49 @@ fn probing(a: &[Data]) -> bool {
matches!(arg(a, 2), Data::Bool(true))
}
/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it.
/// The position an indexer key names when it is an array index, 0 to 2^32 - 2.
fn position(n: f64) -> Option<usize> {
whole(n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok())
}
/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. A key that is the text of a
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
/// looked up as that name, giving `undefined` when no object has it.
fn items_at(h: &Host, a: &[Data]) -> Answer {
let doc = items_doc(h, a)?;
if let Data::String(_) = arg(a, 1) {
return match items_by_name(h, a) {
match arg(a, 1) {
Data::String(_) => match items_by_name(h, a) {
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
r => r,
};
},
Data::Number(n) => match position(*n) {
Some(i) => Ok(item_at(h, doc, i)),
None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) {
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
r => r,
},
},
_ => Ok(Data::Undefined),
}
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
Ok(with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
}
/// The object at position `i` of `pageItems`, or `undefined` past the end.
fn item_at(h: &Host, doc: Doc, i: usize) -> Data {
with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))
}
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
let doc = items_doc(h, a)?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
items_named(h, doc, name)
}
/// The first object of `pageItems` named `name`, or `Not found`.
fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
with_doc(h, doc, |_, st| {
let ids = page_items(h, st);
h.charge_call(ids.len() as u64)?;
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name));
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
})
}
@@ -1848,10 +1879,13 @@ fn items_by_name(h: &Host, a: &[Data]) -> Answer {
fn items_index(h: &Host, a: &[Data]) -> Answer {
match arg(a, 1) {
Data::String(_) => items_by_name(h, a),
Data::Number(_) => match items_at(h, a)? {
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
d => Ok(d),
},
Data::Number(n) => {
let doc = items_doc(h, a)?;
match position(*n).map(|i| item_at(h, doc, i)) {
None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())),
Some(d) => Ok(d),
}
}
_ => Err(HostError::Type("give a name or an index".into())),
}
}
@@ -2638,6 +2672,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
]);
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
application.push(later(l, "Application", "beep"));
application.extend(super::actions::app_members(l));
let preset = {
let l = link.clone();
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
@@ -2706,6 +2741,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
),
("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }),
("textFrames", text::doc_text_frames(l), MemberInfo { collection: true, ..typed("TextFrames") }),
("stories", text::threads::doc_stories(l), MemberInfo { collection: true, ..typed("Stories") }),
("selection", property(l, doc_selection, doc_set_selection), typed("*")),
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
("toString", method(l, doc_to_string), returns("string", &[])),
+86 -35
View File
@@ -50,6 +50,8 @@ use super::{
};
use crate::{DocState, Document, NodeId, NodeKind};
pub(super) mod threads;
/// The error of a text range, or of a collection of one, whose frame's text changed other than
/// through the object model.
pub const STALE_RANGE: &str = "Stale text range";
@@ -194,6 +196,7 @@ pub(in crate::script) struct TextState {
/// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character
/// names that is not installed is added at the end.
fonts: RefCell<Option<Vec<(String, String)>>>,
stories: threads::StoryState,
/// The number of text range objects made, which numbers the next one.
made: Cell<u64>,
/// The span of each range object, by its number, whose `length` the script set.
@@ -609,7 +612,10 @@ fn range_set_length(h: &Host, a: &[Data]) -> Answer {
let Some(n) = usize_of(n).filter(|n| *n <= left) else {
return Err(HostError::Range(format!("length must be a whole number from 0 to {left}")));
};
h.dom.text.resized.borrow_mut().insert(number, (s, s + n, stamp));
// An end inside a surrogate pair moves out to the end of its character.
let end = s + n;
let end = index.chars.get(index.chars.partition_point(|&c| c < end)).copied().unwrap_or(end);
h.dom.text.resized.borrow_mut().insert(number, (s, end, stamp));
Ok(Data::Undefined)
}
@@ -1322,39 +1328,54 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer {
return Err(HostError::Error(super::CROSS_DOCUMENT.into()));
}
if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) {
return Err(HostError::Error("TextFrames: threading and path positions are not available yet".into()));
return Err(HostError::Error("TextFrames: path positions are not available yet".into()));
}
let orientation = if on_path { 4 } else { 2 };
let (orientation, base) = if on_path { (4, 5) } else { (2, 3) };
let vertical = vertical_of(arg(a, orientation))?;
let base = threads::base_frame(h, doc, arg(a, base), arg(a, base + 1))?;
if base.is_some() {
threads::check_base_path(h, path)?;
}
let mode = if on_path { "onPath" } else { "area" };
let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical});
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", &params))?;
new_ref(h, doc, result_id(&r))
let id = result_id(&r);
if let (Some((base, postfix)), Some(id)) = (base, id) {
threads::thread_new(h, base, id, postfix)?;
}
new_ref(h, doc, id)
}
/// `areaText(textPath, orientation?, baseFrame?, postFix?)`.
fn frames_area_text(h: &Host, a: &[Data]) -> Answer {
in_path(h, a, false, &[3, 4])
in_path(h, a, false, &[])
}
/// `pathText(textPath, startTValue?, endTValue?, orientation?, baseFrame?, postFix?)`.
fn frames_path_text(h: &Host, a: &[Data]) -> Answer {
in_path(h, a, true, &[2, 3, 5, 6])
in_path(h, a, true, &[2, 3])
}
/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first.
/// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a
/// locked artboard, stops it first, as `PageItems.removeAll()` does.
fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let (ids, refused) = with_doc(h, doc, |_, st| {
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let ids = frame_ids(h, st);
let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
let refused: Vec<u64> = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect();
(ids, refused)
let locks = st.doc.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
(ids, refused, on_locked)
});
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}")));
}
if !on_locked.is_empty() {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD)));
}
if !ids.is_empty() {
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
}
@@ -1525,6 +1546,23 @@ fn read_only(link: &Link, g: super::Member, class: &'static str, name: &'static
}
}
/// The type `reflect` gives for character attribute `attr`.
fn attr_type(attr: Attr) -> &'static str {
match attr {
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
Attr::TextFont => "TextFont",
_ => "number",
}
}
/// The type `reflect` gives for paragraph attribute `attr`.
fn para_type(attr: ParaAttr) -> &'static str {
match attr {
ParaAttr::Justification => "Justification",
_ => "number",
}
}
fn attr_members(link: &Link) -> Vec<Described> {
let mut out = Vec::new();
for (name, attr) in ATTRS {
@@ -1540,12 +1578,7 @@ fn attr_members(link: &Link) -> Vec<Described> {
h.charge_call(16 + a.iter().map(super::data_size).sum::<u64>())?;
write_attr(&h, &a, attr, name)
});
let data_type = match attr {
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
Attr::TextFont => "TextFont",
_ => "number",
};
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(data_type)));
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(attr_type(attr))));
}
out
}
@@ -1565,8 +1598,7 @@ fn para_members(link: &Link) -> Vec<Described> {
h.charge_call(16 + a.iter().map(super::data_size).sum::<u64>())?;
write_para(&h, &a, attr, name)
});
let data_type = if matches!(attr, ParaAttr::Justification) { "Justification" } else { "number" };
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(data_type)));
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(para_type(attr))));
}
out
}
@@ -1592,27 +1624,26 @@ pub(super) fn install_enums(realm: &mut Realm) -> std::result::Result<(), RunErr
/// The classes of type, `TextFrame` among them, which inherits from `PageItem`.
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
let collection = |t: &str| MemberInfo { collection: true, ..typed(t) };
let mut frame = named(vec![
("kind", get(l, frame_kind), typed("TextType")),
("contents", property(l, frame_contents, frame_set_contents), typed("string")),
("textRange", get(l, frame_range), typed("TextRange")),
("characters", get(l, characters), MemberInfo { collection: true, ..typed("Characters") }),
("words", get(l, words), MemberInfo { collection: true, ..typed("Words") }),
("paragraphs", get(l, paragraphs), MemberInfo { collection: true, ..typed("Paragraphs") }),
("characters", get(l, characters), collection("Characters")),
("words", get(l, words), collection("Words")),
("paragraphs", get(l, paragraphs), collection("Paragraphs")),
("orientation", read_only(l, frame_orientation, "TextFrame", "orientation"), typed("TextOrientation")),
("createOutline", method(l, frame_outline), returns("GroupItem", &[])),
("convertAreaObjectToPointObject", method(l, frame_to_point), returns("TextFrame", &[])),
("convertPointObjectToAreaObject", method(l, frame_to_area), returns("TextFrame", &[])),
]);
frame.extend(super::variables::item_members(l, "TextFrame"));
frame.extend(threads::frame_members(l));
frame.extend(
[
"lines",
"insertionPoints",
"textRanges",
"story",
"nextFrame",
"previousFrame",
"textPath",
"anchor",
"antialias",
@@ -1637,9 +1668,9 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("end", read_only(l, range_end, "TextRange", "end"), typed("number")),
("characterOffset", read_only(l, range_start, "TextRange", "characterOffset"), typed("number")),
("length", property(l, range_length, range_set_length), typed("number")),
("characters", get(l, characters), MemberInfo { collection: true, ..typed("Characters") }),
("words", get(l, words), MemberInfo { collection: true, ..typed("Words") }),
("paragraphs", get(l, paragraphs), MemberInfo { collection: true, ..typed("Paragraphs") }),
("characters", get(l, characters), collection("Characters")),
("words", get(l, words), collection("Words")),
("paragraphs", get(l, paragraphs), collection("Paragraphs")),
("characterAttributes", get(l, character_attributes), typed("CharacterAttributes")),
("paragraphAttributes", get(l, paragraph_attributes), typed("ParagraphAttributes")),
("getParagraphLength", method(l, range_paragraph_length), returns("number", &[("charIndex", "number")])),
@@ -1647,13 +1678,13 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("remove", method(l, range_remove), returns("undefined", &[])),
]);
range.extend(attr_members(l));
range.push(threads::range_member(l));
range.extend(para_members(l));
range.extend(
[
"lines",
"insertionPoints",
"textRanges",
"story",
"kerning",
"characterStyles",
"paragraphStyles",
@@ -1676,8 +1707,8 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
named(vec![
("typename", get(l, part_typename), typed("string")),
("length", get(l, part_length), typed("number")),
("parent", get(l, part_parent), typed("*")),
("add", method(l, part_add_after), returns("TextRange", &[("contents", "string")])),
("parent", get(l, part_parent), typed("TextRange")),
("add", method(l, part_add_after), returns("TextRange", &[("contents", "string"), ("relativeObject", "TextRange")])),
("addBefore", method(l, part_add_before), returns("TextRange", &[("contents", "string")])),
]),
Some(function(l, part_at)),
@@ -1687,7 +1718,8 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
chars.extend(attr_members(l));
let mut paras = named(vec![("typename", get(l, para_attrs_typename), typed("string"))]);
paras.extend(para_members(l));
vec![
let stories = threads::classes(l);
let mut out = vec![
class("TextFrame", Some("PageItem"), frame, None),
class("TextRange", None, range, None),
part("Characters"),
@@ -1702,12 +1734,29 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("typename", get(l, frames_typename), typed("string")),
("length", get(l, frames_length), typed("number")),
("parent", get(l, frames_parent), typed("Document")),
("index", method(l, frames_index), returns("number", &[("itemKey", "TextFrame")])),
("index", method(l, frames_index), returns("number", &[("itemKey", "*")])),
("getByName", method(l, frames_by_name), returns("TextFrame", &[("name", "string")])),
("add", method(l, frames_add), returns("TextFrame", &[])),
("pointText", method(l, frames_point_text), returns("TextFrame", &[("anchor", "Array"), ("orientation", "TextOrientation")])),
("areaText", method(l, frames_area_text), returns("TextFrame", &[("textPath", "PathItem"), ("orientation", "TextOrientation")])),
("pathText", method(l, frames_path_text), returns("TextFrame", &[("textPath", "PathItem"), ("startTValue", "number")])),
(
"areaText",
method(l, frames_area_text),
returns("TextFrame", &[("textPath", "PathItem"), ("orientation", "TextOrientation"), ("baseFrame", "TextFrame")]),
),
(
"pathText",
method(l, frames_path_text),
returns(
"TextFrame",
&[
("textPath", "PathItem"),
("startTValue", "number"),
("endTValue", "number"),
("orientation", "TextOrientation"),
("baseFrame", "TextFrame"),
],
),
),
("removeAll", method(l, frames_remove_all), returns("undefined", &[])),
]),
Some(function(l, frames_at)),
@@ -1719,7 +1768,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("typename", typename_of("TextFonts"), typed("string")),
("length", get(l, fonts_length), typed("number")),
("parent", get(l, app_ref), typed("Application")),
("index", method(l, fonts_index), returns("number", &[("itemKey", "TextFont")])),
("index", method(l, fonts_index), returns("number", &[("itemKey", "*")])),
("getByName", method(l, fonts_by_name), returns("TextFont", &[("name", "string")])),
]),
Some(function(l, fonts_at)),
@@ -1736,7 +1785,9 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
]),
None,
),
]
];
out.extend(stories);
out
}
#[cfg(test)]
@@ -0,0 +1,829 @@
//! Threaded type in the script object model: a text frame's `nextFrame`, `previousFrame` and
//! `story`, `document.stories`, and each `Story` with its frames and its text, as the help pages
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Story/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Stories/> describe them.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - Assigning `nextFrame` links the last frame of a story to the first frame of another story,
//! whose text then flows on after it; `previousFrame` links the other way. Assigning `null`
//! breaks that link, and no text moves across it. Point type, a frame of another
//! document, the frame itself, a frame inside a story, a link that would make a loop and a hidden
//! or locked frame in either story are refused with nothing changed. Assigning the frame that is
//! already linked, or `null` where there is no link, changes nothing.
//! - A `Story` is the story of the frame it was read from as that frame is threaded now; when the
//! frame is deleted, it throws `Stale story`.
//! - `document.stories` lists one story for each type object in no thread and one for each thread,
//! in the order of their first frames in `document.textFrames`, topmost first. `index` with a string finds the first story whose
//! first frame has that name.
//! - The text of a story of two or more frames is its frames' text in thread order. Its ranges keep
//! their place through edits made through them, as a frame's ranges do, and are stale after any
//! other change to the story's text and after File › Revert. A story of one frame gives that
//! frame's own ranges.
//! - `areaText` and `pathText` with a `baseFrame` thread the new frame after it, or before it when
//! `postFix` is false; `postFix` is true when it is left out.
use std::cell::RefCell;
use std::collections::{HashMap, HashSet, VecDeque};
use std::rc::Rc;
use std::sync::{Arc, Weak};
use serde_json::json;
use vectorcraft_doc::TextKind;
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref};
use super::super::{
Answer, Described, Doc, Host, Item, Link, NOT_FOUND, arg, boolean, class, current, doc_of, doc_ref, edit_item, find_doc, float, function, get,
handle_of, id_of, id_parts, in_compound, item_of, item_ref, method, named, num, property, returns, text, typed, whole, with_doc,
};
use super::{
ATTRS, Index, Log, Part, STALE_RANGE, frame_ids, from_script, part_spans, range_ref, read_only, text_of, this_frame, to_script, touched,
usize_of, whole_span,
};
use crate::cmd::threads::story_of;
use crate::{DocState, Document, NodeId};
/// The error of a `Story` whose frame was deleted, or that came from an earlier run.
pub const STALE_STORY: &str = "Stale story";
/// A document's uid, the document, and the first frame of each of its stories then.
type StoryList = (u64, Weak<Document>, Rc<Vec<NodeId>>);
/// The story state of one run: the text of each story of two or more frames that a range was made
/// of, by document and the frame the `Story` was read from, and the last list of stories.
#[derive(Default)]
pub(in crate::script) struct StoryState {
logs: RefCell<HashMap<(u64, u64), Log>>,
list: RefCell<Option<StoryList>>,
}
/// The frames of the story `id` is a frame of, in thread order, each once, or `id` alone.
fn frames_of(st: &DocState, id: NodeId) -> Vec<NodeId> {
let mut frames = story_of(&st.doc, id);
let mut seen = HashSet::new();
frames.retain(|f| seen.insert(*f));
if frames.len() < 2 { vec![id] } else { frames }
}
/// The frames of the story `id` is a frame of, charged to the run.
fn charged_frames(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<Vec<NodeId>, HostError> {
h.charge_call(st.doc.text_threads.len() as u64)?;
let frames = frames_of(st, id);
h.charge_call(frames.len() as u64)?;
Ok(frames)
}
/// Whether type object `id` is area type or type on a path.
fn threadable(st: &DocState, id: NodeId) -> bool {
text_of(st, id).is_some_and(|t| !matches!(t.kind, TextKind::Point))
}
// ---- nextFrame and previousFrame ----
fn neighbor(h: &Host, a: &[Data], next: bool) -> Answer {
let item = this_frame(h, a)?;
with_doc(h, item.doc, |_, st| {
let frames = charged_frames(h, st, item.id)?;
let i = frames.iter().position(|f| *f == item.id);
let other = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) });
Ok(other.map_or(Data::Null, |f| item_ref(h, st, *f)))
})
}
fn next_frame(h: &Host, a: &[Data]) -> Answer {
neighbor(h, a, true)
}
fn previous_frame(h: &Host, a: &[Data]) -> Answer {
neighbor(h, a, false)
}
/// Assigns `nextFrame` (`next`) or `previousFrame` with `text.thread.setNeighbor`.
fn set_neighbor(h: &Host, a: &[Data], next: bool) -> Answer {
let name = if next { "nextFrame" } else { "previousFrame" };
let item = this_frame(h, a)?;
let other = match arg(a, 1) {
Data::Null => None,
d if handle_of(d, "TextFrame").is_some() => Some(item_of(h, d)?),
_ => return Err(HostError::Type(format!("{name} must be a TextFrame or null"))),
};
if other.is_some_and(|o| o.doc.uid != item.doc.uid) {
return Err(HostError::Error(format!("{name}: the two frames are in different documents")));
}
let now = with_doc(h, item.doc, |_, st| {
if !threadable(st, item.id) || other.is_some_and(|o| !threadable(st, o.id)) {
return Err(HostError::Error(format!("{name}: only area type and type on a path can be threaded")));
}
let frames = charged_frames(h, st, item.id)?;
let i = frames.iter().position(|f| *f == item.id);
let current = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) });
Ok(current.copied())
})?;
if now == other.map(|o| o.id) {
return Ok(Data::Undefined);
}
let side = if next { "next" } else { "previous" };
let params = json!({"id": item.id.0, "side": side, "neighbor": other.map(|o| o.id.0)});
edit_item(h, item, "text.thread.setNeighbor", &params).map_err(|e| match e {
HostError::Error(m) => HostError::Error(format!("{name}: {m}")),
e => e,
})?;
Ok(Data::Undefined)
}
fn set_next_frame(h: &Host, a: &[Data]) -> Answer {
set_neighbor(h, a, true)
}
fn set_previous_frame(h: &Host, a: &[Data]) -> Answer {
set_neighbor(h, a, false)
}
/// `TextFrame.story`.
fn frame_story(h: &Host, a: &[Data]) -> Answer {
let item = this_frame(h, a)?;
Ok(story_ref(h, item))
}
/// `TextRange.story`: the story of the range's frame.
fn range_story(h: &Host, a: &[Data]) -> Answer {
let r = super::this_range(h, a)?;
super::resolve(h, r)?;
Ok(story_ref(h, r.item))
}
// ---- creating a frame threaded to another ----
/// The `baseFrame` and `postFix` arguments of `areaText` and `pathText`, checked before the frame
/// is made: the frame to thread the new one to, and whether the new one goes after it.
pub(super) fn base_frame(h: &Host, doc: Doc, base: &Data, post: &Data) -> std::result::Result<Option<(Item, bool)>, HostError> {
if matches!(base, Data::Undefined | Data::Null) {
return Ok(None);
}
if handle_of(base, "TextFrame").is_none() {
return Err(HostError::Type("baseFrame must be a TextFrame".into()));
}
let item = item_of(h, base)?;
if item.doc.uid != doc.uid {
return Err(HostError::Error("baseFrame: the frame is in another document".into()));
}
let postfix = match post {
Data::Undefined => true,
d => boolean(d, "postFix")?,
};
with_doc(h, item.doc, |_, st| {
if !threadable(st, item.id) {
return Err(HostError::Error("baseFrame: only area type and type on a path can be threaded".into()));
}
let editable = st.doc.editable();
if charged_frames(h, st, item.id)?.iter().any(|f| !editable(*f)) {
return Err(HostError::Error("baseFrame: a frame of its story is hidden or locked".into()));
}
Ok(())
})?;
Ok(Some((item, postfix)))
}
/// Refuses a `baseFrame` for a path inside a compound path before the path is turned into type:
/// `text.thread.add` does not thread type there.
pub(super) fn check_base_path(h: &Host, path: Item) -> std::result::Result<(), HostError> {
if in_compound(h, path) {
return Err(HostError::Error("baseFrame: type made from a path inside a compound path cannot be threaded".into()));
}
Ok(())
}
/// Threads the new frame `id` after `base`, or before it when `postfix` is false.
pub(super) fn thread_new(h: &Host, base: Item, id: NodeId, postfix: bool) -> std::result::Result<(), HostError> {
edit_item(h, base, "text.thread.add", &json!({"from": base.id.0, "to": id.0, "before": !postfix}))?;
Ok(())
}
// ---- Story ----
fn story_ref(h: &Host, item: Item) -> Data {
let [high, low] = id_parts(item.id);
host_ref("Story", &[float(h.run), float(item.doc.uid), high, low])
}
/// The frame the story `d` was read from, which must still be a type object.
fn story_of_data(h: &Host, d: &Data) -> std::result::Result<Item, HostError> {
let Some(handle) = handle_of(d, "Story") else { return Err(HostError::Type("this is not a Story".into())) };
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Story".into())) };
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_STORY.into()))?;
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_STORY.into()))?;
match with_doc(h, doc, |_, st| text_of(st, id).is_some()) {
true => Ok(Item { doc, id }),
false => Err(HostError::Error(STALE_STORY.into())),
}
}
fn this_story(h: &Host, a: &[Data]) -> std::result::Result<Item, HostError> {
story_of_data(h, arg(a, 0))
}
fn story_frames(h: &Host, a: &[Data]) -> Answer {
let story = this_story(h, a)?;
with_doc(h, story.doc, |_, st| Ok(Data::Array(charged_frames(h, st, story.id)?.iter().map(|f| item_ref(h, st, *f)).collect())))
}
fn story_parent(h: &Host, a: &[Data]) -> Answer {
let story = this_story(h, a)?;
Ok(doc_ref(h, story.doc.uid))
}
/// The story's one frame, or `None` for a story of two or more frames.
fn single(h: &Host, story: Item) -> std::result::Result<Option<Item>, HostError> {
with_doc(h, story.doc, |_, st| {
let frames = charged_frames(h, st, story.id)?;
Ok(match frames[..] {
[one] => Some(Item { doc: story.doc, id: one }),
_ => None,
})
})
}
fn story_length(h: &Host, a: &[Data]) -> Answer {
let story = this_story(h, a)?;
let (index, _) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?;
Ok(num(float(index.len() as u64)))
}
/// A range or a collection of the whole story, as `frame_class` for a story of one frame and
/// `story_class` for a longer one.
fn story_whole(h: &Host, a: &[Data], frame_class: &str, story_class: &str) -> Answer {
let story = this_story(h, a)?;
if let Some(frame) = single(h, story)? {
let (_, r) = whole_span(h, frame)?;
return Ok(range_ref(h, frame, r.start, r.end, r.stamp, frame_class));
}
let (index, stamp) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?;
Ok(span_ref(h, story, 0, index.len(), stamp, story_class))
}
fn story_text_range(h: &Host, a: &[Data]) -> Answer {
story_whole(h, a, "TextRange", "StoryRange")
}
fn story_characters(h: &Host, a: &[Data]) -> Answer {
story_whole(h, a, "Characters", "StoryCharacters")
}
fn story_words(h: &Host, a: &[Data]) -> Answer {
story_whole(h, a, "Words", "StoryWords")
}
fn story_paragraphs(h: &Host, a: &[Data]) -> Answer {
story_whole(h, a, "Paragraphs", "StoryParagraphs")
}
// ---- the text of a story of two or more frames ----
/// The frames of the story and the text of each, in thread order.
fn story_text(st: &DocState, frames: &[NodeId]) -> String {
frames.iter().filter_map(|f| text_of(st, *f)).flat_map(|t| t.runs.iter().map(|r| r.text.as_str())).collect()
}
/// The story's index and its generation now, read again when its document changed. The stories
/// read from the frames of one story share one index of its text while the document is unchanged.
fn observe(h: &Host, st: &DocState, anchor: NodeId) -> std::result::Result<(Rc<Index>, u64), HostError> {
if text_of(st, anchor).is_none() {
return Err(HostError::Error(STALE_STORY.into()));
}
let mut logs = h.dom.text.stories.logs.borrow_mut();
let key = (st.uid, anchor.0);
let now = Arc::as_ptr(&st.doc);
let current = |l: &Log| std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts;
if !logs.get(&key).is_some_and(current) {
let frames = charged_frames(h, st, anchor)?;
// Another frame of the same story read at this state of the document has the same text;
// a frame listed in two threads can belong to another story, so its frames must match.
let mut shared = None;
if frames.len() > 1 {
h.charge_call(frames.len() as u64)?;
if let Some((f, l)) =
frames.iter().filter(|f| **f != anchor).find_map(|f| logs.get(&(st.uid, f.0)).filter(|l| current(l)).map(|l| (*f, l)))
&& charged_frames(h, st, f)? == frames
{
shared = Some(l.index.clone());
}
}
let index = match shared {
Some(index) => index,
None => {
let text = story_text(st, &frames);
// Joining the frames' text costs its length, as rebuilding the index does elsewhere.
h.charge_call(text.len() as u64)?;
match logs.get(&key) {
Some(l) if l.reverts == st.reverts && l.index.text == text => l.index.clone(),
_ => Rc::new(Index::new(text)),
}
}
};
match logs.get_mut(&key) {
Some(l) => {
if l.reverts != st.reverts || index.text != l.index.text {
l.stamp += 1;
l.floor = l.stamp;
l.edits.clear();
}
l.index = index;
l.doc = Arc::downgrade(&st.doc);
l.reverts = st.reverts;
}
None => {
logs.insert(key, Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, index, stamp: 0, floor: 0, edits: VecDeque::new() });
}
}
}
let l = logs.get(&key).ok_or_else(|| HostError::Error(STALE_STORY.into()))?;
Ok((l.index.clone(), l.stamp))
}
/// A range of a story: the frame the story was read from, its span in UTF-16 units and the
/// generation it was made at.
#[derive(Clone, Copy)]
struct StorySpan {
story: Item,
start: usize,
end: usize,
stamp: u64,
}
const STORY_PARTS: [(&str, Part); 3] = [("StoryCharacters", Part::Characters), ("StoryWords", Part::Words), ("StoryParagraphs", Part::Paragraphs)];
fn span_ref(h: &Host, story: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data {
let [high, low] = id_parts(story.id);
host_ref(class, &[float(h.run), float(story.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp)])
}
/// The story span `d` names, when it is an object of one of `classes`.
fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result<StorySpan, HostError> {
let handle = classes.iter().find_map(|c| handle_of(d, c));
let Some(&[run, uid, high, low, s, e, stamp]) = handle.as_deref() else {
return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange"))));
};
let story = story_of_data(h, &host_ref("Story", &[run, uid, high, low])).map_err(|_| HostError::Error(STALE_RANGE.into()))?;
let (Some(start), Some(end), Some(stamp)) = (usize_of(s), usize_of(e), whole(stamp)) else { return Err(HostError::Error(STALE_RANGE.into())) };
Ok(StorySpan { story, start, end, stamp })
}
fn this_span(h: &Host, a: &[Data]) -> std::result::Result<StorySpan, HostError> {
span_of(h, arg(a, 0), &["StoryRange"])
}
/// The span and index of `r` now.
fn resolve(h: &Host, r: StorySpan) -> std::result::Result<(Rc<Index>, usize, usize, u64), HostError> {
with_doc(h, r.story.doc, |_, st| {
let (index, stamp) = observe(h, st, r.story.id)?;
let logs = h.dom.text.stories.logs.borrow();
let l = logs.get(&(st.uid, r.story.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?;
if r.stamp < l.floor || r.stamp > l.stamp {
return Err(HostError::Error(STALE_RANGE.into()));
}
let (mut s, mut e) = (r.start, r.end);
let from = l.edits.partition_point(|x| x.stamp <= r.stamp);
for x in l.edits.range(from..) {
let moved = |v: usize| v - x.removed + x.inserted;
s = if s <= x.at {
s
} else if s >= x.at + x.removed {
moved(s)
} else {
x.at
};
// An end inside the removed text goes to the end of the new text.
e = if e < x.at || (e == x.at && x.removed > 0) {
e
} else if e >= x.at + x.removed {
moved(e)
} else {
x.at + x.inserted
};
}
let e = e.min(index.len());
Ok((index, s.min(e), e, stamp))
})
}
/// Records an edit the model made to the story: `removed` units at `at` replaced by `inserted`.
/// When the text is not what that edit gives, every earlier range goes stale. The ranges of the
/// same story read from its other frames record the edit too, when they knew the text before it.
fn record(h: &Host, story: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> {
with_doc(h, story.doc, |_, st| {
if text_of(st, story.id).is_none() {
return Err(HostError::Error(STALE_STORY.into()));
}
let frames = charged_frames(h, st, story.id)?;
let now = story_text(st, &frames);
let (a, b) = (before.byte(at, false), before.byte(at + removed, true));
let expected = before.text.len() - (b - a) + inserted.len() == now.len()
&& now.as_bytes().starts_with(&before.text.as_bytes()[..a])
&& now.as_bytes().ends_with(&before.text.as_bytes()[b..])
&& now.get(a..a + inserted.len()) == Some(inserted);
let members: HashSet<u64> = frames.iter().map(|f| f.0).collect();
let index = Rc::new(Index::new(now));
let inserted = inserted.encode_utf16().count();
let mut logs = h.dom.text.stories.logs.borrow_mut();
let mut found = false;
for (&(uid, anchor), l) in logs.iter_mut() {
if uid != st.uid || !members.contains(&anchor) {
continue;
}
let own = anchor == story.id.0;
let current = l.reverts == st.reverts;
if !own {
h.charge_call(l.index.text.len() as u64)?;
if !expected || !current || l.index.text != before.text {
continue;
}
}
found |= own;
if expected && current {
l.push(at, removed, inserted);
} else {
l.stamp += 1;
l.floor = l.stamp;
l.edits.clear();
}
l.index = index.clone();
l.doc = Arc::downgrade(&st.doc);
l.reverts = st.reverts;
}
if found { Ok(()) } else { Err(HostError::Error(STALE_RANGE.into())) }
})
}
/// Replaces bytes `a..b` of the story's text with `insert`, a frame at a time from the end, with
/// `text.editRange`: the frames before the one an edit changes keep their text, so `a` stays in
/// place while the frames after it flow again.
fn replace(h: &Host, story: Item, a: usize, mut b: usize, insert: &str) -> std::result::Result<(), HostError> {
loop {
let spans: Vec<(NodeId, usize, usize)> = with_doc(h, story.doc, |_, st| {
if text_of(st, story.id).is_none() {
return Err(HostError::Error(STALE_STORY.into()));
}
let mut at = 0;
let spans = charged_frames(h, st, story.id)?
.into_iter()
.map(|f| {
let n: usize = text_of(st, f).map_or(0, |t| t.runs.iter().map(|r| r.text.len()).sum());
at += n;
(f, at - n, at)
})
.collect();
Ok(spans)
})?;
let target =
if b > a { spans.iter().find(|(_, x, y)| *x < b && b <= *y) } else { spans.iter().find(|(_, x, y)| *x < a && a <= *y).or(spans.first()) };
let Some(&(f, x, _)) = target else { return Err(HostError::Error(STALE_RANGE.into())) };
let item = Item { doc: story.doc, id: f };
if x <= a {
edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": a - x, "end": b - x, "insert": insert}))?;
return Ok(());
}
edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": 0, "end": b - x, "insert": ""}))?;
b = x;
}
}
fn write_contents(h: &Host, r: StorySpan, value: &Data) -> Answer {
let Data::String(v) = value else { return Err(HostError::Type("contents must be a string".into())) };
let insert = from_script(v);
let (index, s, e, _) = resolve(h, r)?;
let (a, b) = (index.byte(s, false), index.byte(e, true));
if index.text[a..b] == insert {
return Ok(Data::Undefined);
}
let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count());
replace(h, r.story, a, b, &insert)?;
record(h, r.story, &index, s, e - s, &insert)?;
Ok(Data::Undefined)
}
fn span_contents(h: &Host, a: &[Data]) -> Answer {
let (index, s, e, _) = resolve(h, this_span(h, a)?)?;
let (x, y) = (index.byte(s, false), index.byte(e, true));
Ok(text(to_script(&index.text[x..y])))
}
fn span_set_contents(h: &Host, a: &[Data]) -> Answer {
write_contents(h, this_span(h, a)?, arg(a, 1))
}
fn span_remove(h: &Host, a: &[Data]) -> Answer {
write_contents(h, this_span(h, a)?, &text(""))
}
fn span_start(h: &Host, a: &[Data]) -> Answer {
let (_, s, _, _) = resolve(h, this_span(h, a)?)?;
Ok(num(float(s as u64)))
}
fn span_end(h: &Host, a: &[Data]) -> Answer {
let (_, _, e, _) = resolve(h, this_span(h, a)?)?;
Ok(num(float(e as u64)))
}
fn span_length(h: &Host, a: &[Data]) -> Answer {
let (_, s, e, _) = resolve(h, this_span(h, a)?)?;
Ok(num(float((e - s) as u64)))
}
fn span_story(h: &Host, a: &[Data]) -> Answer {
let r = this_span(h, a)?;
resolve(h, r)?;
Ok(story_ref(h, r.story))
}
fn span_paragraph_length(h: &Host, a: &[Data]) -> Answer {
let (index, s, e, _) = resolve(h, this_span(h, a)?)?;
let p = touched(&index.paras, s, e).next().and_then(|i| index.paras.get(i)).map_or(0, |(x, y)| y - x);
Ok(num(float(p as u64)))
}
fn span_part(h: &Host, a: &[Data], class: &str) -> Answer {
let r = this_span(h, a)?;
let (_, s, e, stamp) = resolve(h, r)?;
Ok(span_ref(h, r.story, s, e, stamp, class))
}
fn span_characters(h: &Host, a: &[Data]) -> Answer {
span_part(h, a, "StoryCharacters")
}
fn span_words(h: &Host, a: &[Data]) -> Answer {
span_part(h, a, "StoryWords")
}
fn span_paragraphs(h: &Host, a: &[Data]) -> Answer {
span_part(h, a, "StoryParagraphs")
}
fn this_part(h: &Host, a: &[Data]) -> std::result::Result<(StorySpan, Part), HostError> {
let part = STORY_PARTS.iter().find(|(c, _)| handle_of(arg(a, 0), c).is_some()).map(|(_, p)| *p);
let part = part.ok_or_else(|| HostError::Type("this is not a collection of text".into()))?;
Ok((span_of(h, arg(a, 0), &STORY_PARTS.map(|(c, _)| c))?, part))
}
fn part_typename(h: &Host, a: &[Data]) -> Answer {
let (r, part) = this_part(h, a)?;
resolve(h, r)?;
Ok(text(match part {
Part::Characters => "Characters",
Part::Words => "Words",
Part::Paragraphs => "Paragraphs",
}))
}
fn span_typename(h: &Host, a: &[Data]) -> Answer {
resolve(h, this_span(h, a)?)?;
Ok(text("TextRange"))
}
fn story_typename(h: &Host, a: &[Data]) -> Answer {
this_story(h, a)?;
Ok(text("Story"))
}
fn part_length(h: &Host, a: &[Data]) -> Answer {
let (r, part) = this_part(h, a)?;
let (index, s, e, _) = resolve(h, r)?;
Ok(num(float(part_spans(&index, part, s, e).0.len() as u64)))
}
fn part_parent(h: &Host, a: &[Data]) -> Answer {
let (r, _) = this_part(h, a)?;
let (_, s, e, stamp) = resolve(h, r)?;
Ok(span_ref(h, r.story, s, e, stamp, "StoryRange"))
}
fn part_at(h: &Host, a: &[Data]) -> Answer {
let (r, part) = this_part(h, a)?;
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
let (index, s, e, stamp) = resolve(h, r)?;
let (items, spans) = part_spans(&index, part, s, e);
let Some(k) = items.start.checked_add(i).filter(|k| *k < items.end) else { return Ok(Data::Undefined) };
let span = match spans {
None => index.char_span(k),
Some(list) => list.get(k).copied(),
};
Ok(span.map_or(Data::Undefined, |(x, y)| span_ref(h, r.story, x, y, stamp, "StoryRange")))
}
// ---- Stories ----
fn doc_stories_impl(h: &Host, a: &[Data]) -> Answer {
let doc = doc_of(h, arg(a, 0), "Document")?;
Ok(host_ref("Stories", &[float(h.run), float(doc.uid)]))
}
/// `document.stories`.
pub(in crate::script::dom) fn doc_stories(link: &Link) -> HostMember {
get(link, doc_stories_impl)
}
/// The first frame of each story of the document in paint order, kept while the document is
/// unchanged.
fn heads(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
if let Some((uid, doc, ids)) = &*h.dom.text.stories.list.borrow()
&& *uid == st.uid
&& std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))
{
return Ok(ids.clone());
}
let ids = frame_ids(h, st);
h.charge_call(ids.len() as u64 + st.doc.text_threads.iter().map(|t| t.len() as u64).sum::<u64>())?;
// A frame listed by an earlier thread belongs to that one, as `story_of` finds it.
let (mut threaded, mut first) = (HashSet::new(), HashSet::new());
let mut seen = HashSet::new();
for thread in &st.doc.text_threads {
let live: Vec<NodeId> = thread.iter().copied().filter(|f| threadable(st, *f) && seen.insert(*f)).collect();
if live.len() >= 2 {
first.insert(live[0]);
threaded.extend(live);
}
}
let heads: Vec<NodeId> = ids.iter().copied().filter(|id| !threaded.contains(id) || first.contains(id)).collect();
let heads = Rc::new(heads);
*h.dom.text.stories.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), heads.clone()));
Ok(heads)
}
fn stories_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
doc_of(h, arg(a, 0), "Stories")
}
fn stories_length(h: &Host, a: &[Data]) -> Answer {
let doc = stories_doc(h, a)?;
let n = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.len()))?;
Ok(num(float(n as u64)))
}
fn stories_typename(h: &Host, a: &[Data]) -> Answer {
stories_doc(h, a)?;
Ok(text("Stories"))
}
fn stories_parent(h: &Host, a: &[Data]) -> Answer {
let doc = stories_doc(h, a)?;
Ok(doc_ref(h, doc.uid))
}
fn stories_at(h: &Host, a: &[Data]) -> Answer {
let doc = stories_doc(h, a)?;
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
let id = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.get(i).copied()))?;
Ok(id.map_or(Data::Undefined, |id| story_ref(h, Item { doc, id })))
}
/// `stories.index(key)`: by number, or by the name of a story's first frame.
fn stories_index(h: &Host, a: &[Data]) -> Answer {
let doc = stories_doc(h, a)?;
match arg(a, 1) {
Data::Number(_) => match stories_at(h, a)? {
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
d => Ok(d),
},
Data::String(name) => {
let id = with_doc(h, doc, |_, st| {
let list = heads(h, st)?;
h.charge_call(list.len() as u64)?;
Ok::<_, HostError>(list.iter().copied().find(|i| st.doc.node(*i).and_then(|n| n.name.as_deref()) == Some(name.as_str())))
})?;
id.map(|id| story_ref(h, Item { doc, id })).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
}
_ => Err(HostError::Type("give a name or an index".into())),
}
}
// ---- classes ----
/// A member of the range of a story of two or more frames that is not available yet: reading or
/// assigning it throws, after the check that the range is still there, and `reflect` leaves it out.
fn range_later(link: &Link, name: &'static str) -> Described {
let message = format!("TextRange.{name} is not available yet");
let l = link.clone();
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
let h = current(&l)?;
h.charge_call(16)?;
resolve(&h, this_span(&h, &a)?)?;
Err(HostError::Error(message.clone()))
});
(name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() })
}
/// A member of `Story` that is not available yet: reading or assigning it throws, after the check
/// that the story is still there, and `reflect` leaves it out.
fn story_later(link: &Link, name: &'static str) -> Described {
let message = format!("Story.{name} is not available yet");
let l = link.clone();
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
let h = current(&l)?;
h.charge_call(16)?;
this_story(&h, &a)?;
Err(HostError::Error(message.clone()))
});
(name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() })
}
/// The members of `TextFrame` this module adds.
pub(super) fn frame_members(l: &Link) -> Vec<Described> {
named(vec![
("nextFrame", property(l, next_frame, set_next_frame), typed("TextFrame")),
("previousFrame", property(l, previous_frame, set_previous_frame), typed("TextFrame")),
("story", get(l, frame_story), typed("Story")),
])
}
/// `TextRange.story`.
pub(super) fn range_member(l: &Link) -> Described {
("story".into(), get(l, range_story), typed("Story"))
}
/// `Story`, `Stories` and the range and collections of the text of a story of two or more frames.
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
let collection = |t: &str| MemberInfo { collection: true, ..typed(t) };
let mut story = named(vec![
("typename", get(l, story_typename), typed("string")),
("parent", get(l, story_parent), typed("Document")),
("length", get(l, story_length), typed("number")),
("textFrames", get(l, story_frames), typed("Array")),
("textRange", get(l, story_text_range), typed("*")),
("characters", get(l, story_characters), collection("*")),
("words", get(l, story_words), collection("*")),
("paragraphs", get(l, story_paragraphs), collection("*")),
]);
story.extend(["lines", "insertionPoints", "textRanges", "textSelection"].into_iter().map(|m| story_later(l, m)));
let mut range = named(vec![
("typename", get(l, span_typename), typed("string")),
("parent", get(l, span_story), typed("Story")),
("story", get(l, span_story), typed("Story")),
("contents", property(l, span_contents, span_set_contents), typed("string")),
("start", read_only(l, span_start, "TextRange", "start"), typed("number")),
("end", read_only(l, span_end, "TextRange", "end"), typed("number")),
("characterOffset", read_only(l, span_start, "TextRange", "characterOffset"), typed("number")),
("length", read_only(l, span_length, "TextRange", "length"), typed("number")),
("characters", get(l, span_characters), collection("StoryCharacters")),
("words", get(l, span_words), collection("StoryWords")),
("paragraphs", get(l, span_paragraphs), collection("StoryParagraphs")),
("getParagraphLength", method(l, span_paragraph_length), returns("number", &[])),
("remove", method(l, span_remove), returns("undefined", &[])),
]);
range.extend(
[
"lines",
"insertionPoints",
"textRanges",
"characterAttributes",
"paragraphAttributes",
"kerning",
"characterStyles",
"paragraphStyles",
"textSelection",
"changeCaseTo",
"select",
"deSelect",
"duplicate",
"move",
"getTextRunLength",
"getLocalCharOverridesJSON",
"getLocalParaOverridesJSON",
]
.into_iter()
.chain(ATTRS.iter().map(|(n, _)| *n))
.map(|m| range_later(l, m)),
);
let part = |name: &'static str| {
class(
name,
None,
named(vec![
("typename", get(l, part_typename), typed("string")),
("length", get(l, part_length), typed("number")),
("parent", get(l, part_parent), typed("StoryRange")),
]),
Some(function(l, part_at)),
)
};
vec![
class("Story", None, story, None),
class("StoryRange", None, range, None),
part("StoryCharacters"),
part("StoryWords"),
part("StoryParagraphs"),
class(
"Stories",
None,
named(vec![
("typename", get(l, stories_typename), typed("string")),
("length", get(l, stories_length), typed("number")),
("parent", get(l, stories_parent), typed("Document")),
("index", method(l, stories_index), returns("number", &[("itemKey", "*")])),
]),
Some(function(l, stories_at)),
),
]
}
+18
View File
@@ -48,6 +48,7 @@
//! that holds the run's host only while the run goes on. An error, a limit or a stop puts the
//! documents back and keeps the engine's globals; an internal error drops the engine.
pub mod actions;
pub mod console;
pub mod dialogs;
pub mod dollar;
@@ -206,6 +207,8 @@ pub(crate) struct Request {
pub locale: String,
/// The answers to the dialogs of a run with nobody to ask, in order.
pub answers: Vec<DialogAnswer>,
/// The actions `app.doScript` can play.
pub actions: Vec<actions::Playable>,
}
thread_local! {
@@ -806,6 +809,15 @@ struct Host {
args: RefCell<(Data, u64)>,
/// The run's state of the script object model (`app`).
dom: dom::State,
/// The actions `app.doScript` can play.
actions: Vec<actions::Playable>,
/// The index of each open document's active artboard as the run starts, by document uid. The
/// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it.
active_artboards: Vec<(u64, usize)>,
/// The artboards the Artboard tool had selected in the active document as the run starts (two or
/// more), with that document's uid. The run gives the tool fresh state, which drops them, so the
/// steps `app.doScript` plays read them here.
artboard_picks: Option<(u64, Vec<usize>)>,
/// The documents open when the run began as the person last left them, each with its own file
/// and the file it was read from ([`crate::DocState::as_person_left`],
/// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files
@@ -2063,6 +2075,9 @@ impl Session {
if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() {
return Err(EngineError::Other(NO_RECOVERY_COPY.to_string()));
}
// The Artboard tool's selection, which the fresh tool state below drops.
let picks = cmd::artboard_tool_picks(self);
let artboard_picks = self.active().filter(|_| !picks.is_empty()).map(|d| (d.uid, picks));
self.reset_tool();
let open: Vec<u64> = self.docs.iter().map(|d| d.uid).collect();
self.script_high_water.retain(|uid, _| open.contains(uid));
@@ -2182,6 +2197,9 @@ impl Session {
dollar: dollar::RunState::new(&request.locale),
args: RefCell::new((Data::Undefined, 0)),
dom: dom::State::new(heap_bytes),
actions: request.actions,
active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(),
artboard_picks,
run_docs: RefCell::new(
self.docs
.iter()
+3 -1
View File
@@ -49,7 +49,7 @@ mod css;
mod curvature_circle;
mod cut;
mod dashalign;
mod dcs;
pub(super) mod dcs;
mod delete_keeps_joined;
mod distort;
mod docsetup;
@@ -175,6 +175,7 @@ mod repeat_edit;
mod save;
mod saveoptions;
mod scalestrokes;
mod script_actions;
mod script_console;
mod script_dialogs;
mod script_dollar;
@@ -187,6 +188,7 @@ mod script_run;
mod script_scriptui;
mod script_tags;
mod script_text;
mod script_threads;
mod script_variables;
mod script_xmp;
mod scripts;
+20
View File
@@ -4046,6 +4046,26 @@ fn live_paint_bucket_refuses_a_bad_target_or_aligned() {
}
}
/// With nothing selected, Invert and Complement refuse a bad `target` or `aligned` and leave the
/// default fill and stroke as they are.
#[test]
fn invert_and_complement_refuse_a_bad_target_or_aligned_with_nothing_selected() {
let mut s = session();
s.execute("paint.setFill", &json!({"color": "#336699", "defaultsOnly": true})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let before = (s.paint.fill.clone(), s.paint.stroke.clone());
for cmd in ["paint.invert", "paint.complement"] {
for p in
[json!({"stroke": false, "target": "content"}), json!({"stroke": false, "aligned": "yes"}), json!({"stroke": true, "target": "bogus"})]
{
assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}");
assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone()), before, "{cmd} {p}");
}
}
s.execute("paint.invert", &json!({"stroke": false})).unwrap();
assert_ne!(s.paint.fill, before.0, "a good call still inverts the default");
}
/// While the Live Paint Bucket is active, each preview of a paint command in one interaction starts
/// from the colors the interaction began with, so previewing a swap twice and committing swaps once.
#[test]
+28 -1
View File
@@ -56,7 +56,7 @@ fn single_file(plates: &[(&str, String)], extra: &str) -> Vec<u8> {
}
/// Cyan solid on the top row, PANTONE 185 C at 50% on the left column.
fn two_plates() -> Vec<u8> {
pub(crate) fn two_plates() -> Vec<u8> {
single_file(
&[("Cyan", plate_eps([0, 0, 255, 255])), ("PANTONE 185 C", plate_eps([127, 255, 127, 255]))],
"%%DocumentCustomColors: (PANTONE 185 C)\n%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n",
@@ -267,6 +267,33 @@ fn update_and_relink_draw_the_files_clipping_path_through_a_distorted_images_cor
assert_eq!(node(&s).image_corners().unwrap(), corners);
}
/// Place with Replace of an image changed by Perspective Distort or Free Distort by a DCS file puts
/// the file's image between the corners and draws its clipping path through them.
#[test]
fn place_with_replace_draws_the_files_clipping_path_through_a_distorted_images_corners() {
let dir = temp_dir("replace-distorted-clip");
let path = write(&dir, "pic.eps", &two_plates());
let mut s = session();
let png = crate::tests_links::png(4, 4, [255, 0, 0]);
let r = s.execute("file.place", &json!({ "name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100] })).unwrap();
let old = NodeId(r["ids"][0].as_u64().unwrap());
s.execute("object.distort", &json!({ "corners": [[100, 100], [160, 104], [150, 140], [96, 136]] })).unwrap();
let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap();
let r = s.execute("file.place", &json!({ "path": path, "replace": true })).unwrap();
let group = NodeId(r["ids"][0].as_u64().unwrap());
let id = NodeId(r["image"].as_u64().unwrap());
let node = s.doc().unwrap().doc.node(id).unwrap().clone();
assert!(node.is_distorted_image());
assert_eq!(node.image_corners().unwrap(), corners);
let NodeKind::Group { children, clip: true } = &s.doc().unwrap().doc.node(group).unwrap().kind else { panic!("a clipping group") };
let NodeKind::Path { path, clipping: true, .. } = &children[0].kind else { panic!("a clipping path") };
let anchors: Vec<_> = path.anchors().map(|(_, _, a)| a.p).collect();
// The left half of the 2 × 2 pixels, where the corners put it.
let map = node.image_map().unwrap();
let want = [(0.0, 0.0), (1.0, 0.0), (1.0, 2.0), (0.0, 2.0)].map(|(x, y)| map.apply(vectorcraft_geom::Point::new(x, y)).unwrap());
assert!(anchors.len() == want.len() && want.iter().all(|w| anchors.iter().any(|a| a.distance(*w) < 1e-6)), "{anchors:?} vs {want:?}");
}
#[test]
fn update_link_clips_an_image_whose_file_gained_a_clipping_path() {
let dir = temp_dir("update-gained-clip");
+41
View File
@@ -812,6 +812,47 @@ fn relink_embed_and_unembed_keep_a_distorted_images_corners() {
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
}
/// Place with Replace of a distorted image by an image file keeps its corners, in one undo step:
/// the new file's pixels fill them, the new image is linked to that file, and its transform is the
/// old image's scaled to the new pixel size. Undo brings the old image back between the same
/// corners.
#[test]
fn place_with_replace_keeps_a_distorted_images_corners() {
let dir = Folder::new("distorted-place-replace");
let (photo, other) = (dir.file("photo.png"), dir.file("other.png"));
write(&photo, &png(20, 10, RED));
write(&other, &png(60, 20, BLUE));
let mut s = session();
let id = place(&mut s, &photo);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
// Around the artboard's center, where `centre_colour` looks.
s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap();
let node = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).cloned();
let before = node(&s, id).unwrap().image_corners().unwrap();
let old_xf = image(&s, id).xf;
let undo_len = |s: &Session| s.doc().unwrap().history.undo.len();
let undo = undo_len(&s);
let r = s.execute("file.place", &json!({"path": other, "replace": true})).unwrap();
let new = NodeId(r["ids"][0].as_u64().unwrap());
assert_eq!(undo_len(&s), undo + 1);
assert!(node(&s, id).is_none(), "the old image is replaced");
let n = node(&s, new).unwrap();
assert!(n.is_distorted_image());
assert_eq!(n.image_corners().unwrap(), before);
let im = image(&s, new);
assert_eq!((im.width, im.height), (60, 20));
assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(other.as_str()));
let want = old_xf * vectorcraft_geom::Affine::scale_non_uniform(20.0 / 60.0, 10.0 / 20.0);
assert!(im.xf.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{:?} against {want:?}", im.xf);
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
s.execute("edit.undo", &json!({})).unwrap();
assert!(node(&s, new).is_none());
assert_eq!(node(&s, id).unwrap().image_corners().unwrap(), before);
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
}
/// Unembed into a folder keeps a distorted image's corners, in one undo step.
#[test]
fn unembed_to_a_folder_keeps_a_distorted_images_corners() {
+396
View File
@@ -0,0 +1,396 @@
//! `app.doScript`: a script plays an action of `script.run`'s `actions`.
use serde_json::{Value, json};
use crate::*;
fn run_with(s: &mut Session, source: &str, actions: &Value) -> Result<Value> {
s.execute("script.run", &json!({"source": source, "name": "t.js", "actions": actions}))
}
fn log_with(s: &mut Session, source: &str, actions: &Value) -> Vec<Value> {
let r = run_with(s, source, actions).unwrap_or_else(|e| panic!("{source}: {e}"));
r["log"].as_array().cloned().unwrap_or_default()
}
/// The error message a `try` around `call` logs, or `"ok"`.
fn caught(s: &mut Session, call: &str, actions: &Value) -> String {
let source = format!("try {{ {call}; vc.log('ok'); }} catch (e) {{ vc.log(e.name + ': ' + e.message); }}");
log_with(s, &source, actions).first().and_then(Value::as_str).unwrap_or_default().to_string()
}
fn doc() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
fn objects(s: &Session) -> usize {
s.active().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum()
}
fn undo_labels(s: &Session) -> Vec<String> {
s.active().unwrap().history.undo.iter().map(|e| e.label.clone()).collect()
}
fn rect(x: i64) -> Value {
json!({"command": "shape.rectangle", "params": {"x": x, "y": 10, "width": 20, "height": 20}})
}
/// One set, `Set`, with the actions given as (name, steps).
fn set(actions: &[(&str, Vec<Value>)]) -> Value {
Value::Array(actions.iter().map(|(name, steps)| json!({"set": "Set", "name": name, "steps": steps})).collect())
}
#[test]
fn do_script_plays_every_step_as_one_undo_step_with_the_script() {
let mut s = doc();
let before = undo_labels(&s);
let actions = set(&[("Two", vec![rect(0), rect(50)])]);
let out = log_with(&mut s, "vc.run('shape.rectangle', {x: 100, y: 10, width: 5, height: 5}); vc.log(app.doScript('Two', 'Set'));", &actions);
assert_eq!(out, vec![Value::Null], "doScript returns undefined");
assert_eq!(objects(&s), 3);
let after = undo_labels(&s);
assert_eq!(after.len(), before.len() + 1, "{after:?}");
assert_eq!(after.last().map(String::as_str), Some(script::STEP_LABEL));
// The steps of a recorded `command.batch` run one by one, each counted as a host call.
let batch = set(&[("Batch", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), rect(10), rect(20)]}})])]);
let r = run_with(&mut s, "app.doScript('Batch', 'Set', false);", &batch).unwrap();
assert_eq!(objects(&s), 6);
let r0 = run_with(&mut s, "1;", &batch).unwrap();
assert!(r["hostCalls"].as_u64().unwrap() >= r0["hostCalls"].as_u64().unwrap() + 4, "{r}");
}
#[test]
fn a_later_throw_puts_back_what_the_action_did() {
let mut s = doc();
let before = (objects(&s), undo_labels(&s));
let actions = set(&[("Two", vec![rect(0), rect(50)])]);
let e = run_with(&mut s, "app.doScript('Two', 'Set'); throw new Error('late');", &actions).unwrap_err().to_string();
assert!(e.contains("late"), "{e}");
assert_eq!((objects(&s), undo_labels(&s)), before);
}
#[test]
fn a_failed_step_is_put_back_and_the_steps_before_it_stay() {
let mut s = doc();
let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}});
let actions = set(&[("Bad", vec![rect(0), bad, rect(50)])]);
let m = caught(&mut s, "app.doScript('Bad', 'Set')", &actions);
assert!(m.starts_with("Error: action step 2 of “Bad” (`object.move`) failed:"), "{m}");
assert_eq!(objects(&s), 1, "the first step stays done and the third never runs");
}
#[test]
fn names_are_matched_exactly_and_must_be_one_action() {
let mut s = doc();
let actions = json!([
{"set": "Set", "name": "One", "steps": [rect(0)]},
{"set": "Set", "name": "Twice", "steps": [rect(0)]},
{"set": "Set", "name": "Twice", "steps": [rect(0)]},
{"set": "Set", "name": "Empty", "steps": []},
]);
assert_eq!(caught(&mut s, "app.doScript('one', 'Set')", &actions), "Error: the set “Set” has no action “one”");
assert_eq!(caught(&mut s, "app.doScript('One', 'set')", &actions), "Error: there is no action set “set”");
assert_eq!(caught(&mut s, "app.doScript('Twice', 'Set')", &actions), "Error: the set “Set” has more than one action “Twice”");
assert_eq!(caught(&mut s, "app.doScript('Empty', 'Set')", &actions), "Error: the action “Empty” has no included steps");
assert_eq!(caught(&mut s, "app.doScript('One', 'Set')", &json!([])), "Error: there is no action set “Set”");
assert_eq!(objects(&s), 0);
assert_eq!(caught(&mut s, "app.doScript('One', 'Set', true)", &actions), "ok");
assert_eq!(objects(&s), 1);
assert_eq!(caught(&mut s, "app.loadAction(1)", &actions), "Error: Application.loadAction is not available yet");
assert_eq!(caught(&mut s, "app.unloadAction('Set', '')", &actions), "Error: Application.unloadAction is not available yet");
}
#[test]
fn bad_arguments_throw_and_change_nothing() {
let mut s = doc();
let actions = set(&[("One", vec![rect(0)])]);
for (call, want) in [
("app.doScript()", "TypeError"),
("app.doScript(1, 'Set')", "TypeError"),
("app.doScript('One', {})", "TypeError"),
("app.doScript('One', 'Set', 'yes')", "TypeError"),
("app.doScript('One', 'Set', 1)", "TypeError"),
("app.doScript('One', 'Set', false, 4)", "TypeError"),
("app.doScript('', 'Set')", "Error"),
("app.doScript(new Array(2000).join('x'), 'Set')", "RangeError"),
] {
let m = caught(&mut s, call, &actions);
assert!(m.starts_with(&format!("{want}:")), "{call}: {m}");
}
assert_eq!(objects(&s), 0);
}
#[test]
fn steps_a_script_may_not_run_stop_the_action_before_any_step() {
let mut s = doc();
s.prefs.show_external_script_warning = true;
let steps = [
(json!({"command": "script.run", "params": {"source": "1"}}), "runs `script.run`, which a script cannot run"),
(json!({"command": "prefs.set", "params": {"key": "showExternalScriptWarning", "value": false}}), "runs `prefs.set`"),
(json!({"command": "ui.action.play", "params": {"set": "Set", "action": "Loop"}}), "runs `ui.action.play`"),
(json!({"command": "ui.runScript", "params": {"source": "1"}}), "runs `ui.runScript`"),
(json!({"command": "view.zoomIn"}), "runs `view.zoomIn`"),
(json!({"command": "action.stop", "params": {"message": "wait"}}), "is a stop, which a script cannot wait at"),
];
for (bad, want) in steps {
let actions = set(&[("Loop", vec![rect(0), bad.clone()])]);
let m = caught(&mut s, "app.doScript('Loop', 'Set')", &actions);
assert!(m.starts_with("Error: step 2 of “Loop” ") && m.contains(want), "{bad}: {m}");
assert_eq!(objects(&s), 0, "{bad}: no step ran");
}
assert!(s.prefs.show_external_script_warning);
// A refused command inside a recorded batch is refused too.
let batch = set(&[("B", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), {"command": "script.run", "params": {}}]}})])]);
let m = caught(&mut s, "app.doScript('B', 'Set')", &batch);
assert!(m.starts_with("Error: step 1.2 of “B” runs `script.run`"), "{m}");
assert_eq!(objects(&s), 0);
// So is one among the commands a Batch step plays on each file, before the steps ahead of it run.
let files = json!({"command": "action.batch", "params": {"commands": [{"command": "select.all"}, {"command": "prefs.set", "params": {}}]}});
let batch = set(&[("F", vec![rect(0), files])]);
let m = caught(&mut s, "app.doScript('F', 'Set')", &batch);
assert!(m.starts_with("Error: step 2.2 of “F” runs `prefs.set`, which a script cannot run"), "{m}");
assert_eq!(objects(&s), 0);
}
#[test]
fn an_action_step_keeps_the_scripts_file_gate() {
let mut s = doc();
let path = std::env::temp_dir().join(format!("vc-do-script-{}.svg", std::process::id()));
let _ = std::fs::remove_file(&path);
let export = json!({"command": "document.export", "params": {"path": path.to_string_lossy(), "format": "svg"}});
let actions = set(&[("Export", vec![export])]);
let m = caught(&mut s, "app.doScript('Export', 'Set')", &actions);
assert!(m.contains("Script file access denied"), "{m}");
assert!(!path.exists());
}
#[test]
fn a_long_action_is_held_to_the_host_call_limit() {
let mut s = doc();
// Each step counts as a host call of its own, and its result as another, as for `vc.run`, so the
// steps of one call cannot pass the limit.
let calls = |s: &mut Session, steps: usize| {
let actions = set(&[("One", vec![json!({"command": "select.none"}); steps])]);
run_with(s, "app.doScript('One', 'Set');", &actions).unwrap()["hostCalls"].as_u64().unwrap()
};
let (one, many) = (calls(&mut s, 1), calls(&mut s, 1001));
assert!(many >= one + 2000, "{one} {many}");
}
#[test]
fn bad_action_lists_are_refused_before_the_script_runs() {
let mut s = doc();
let step = || json!({"command": "select.none"});
let cases = [
(json!({}), "`actions` must be a list"),
(json!([1]), "`actions[0]` must be an object"),
(json!([{"set": "S", "name": 1, "steps": []}]), "`actions[0]`.name must be a string"),
(json!([{"set": "S", "name": "A"}]), "`actions[0]`.steps must be a list"),
(json!([{"set": "S", "name": "A", "steps": [], "key": 1}]), "unknown key `key`"),
(json!([{"set": "S", "name": "A", "steps": [{"command": ""}]}]), "command must be a command id"),
(json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "params": []}]}]), "params must be an object"),
(json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "step": 0}]}]), "step must be a whole number"),
(json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {}}]}]), "params.commands must be a list"),
(
json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {"commands": [{"command": "command.batch", "params": {"commands": []}}]}}]}]),
"a command.batch inside a command.batch",
),
(json!([{"set": "S", "name": "x".repeat(2000), "steps": []}]), "longer than 1024 bytes"),
(Value::Array(vec![json!({"set": "S", "name": "A", "steps": []}); script::actions::MAX_ACTIONS + 1]), "more than 4096 actions"),
(json!([{"set": "S", "name": "A", "steps": vec![step(); script::actions::MAX_ACTION_STEPS + 1]}]), "more than 10000 steps"),
];
for (actions, want) in cases {
let e = run_with(&mut s, "vc.run('shape.rectangle', {x: 0, y: 0, width: 1, height: 1});", &actions).unwrap_err().to_string();
assert!(e.contains(want), "{want}: {e}");
}
let many: Vec<Value> = (0..11).map(|i| json!({"set": "S", "name": format!("A{i}"), "steps": vec![step(); 10_000]})).collect();
let e = run_with(&mut s, "1;", &Value::Array(many)).unwrap_err().to_string();
assert!(e.contains("more than 100000 steps in all"), "{e}");
assert_eq!(objects(&s), 0, "no run started");
}
#[test]
fn a_kept_engine_plays_the_actions_of_the_run_that_calls_it() {
let mut s = doc();
let first = set(&[("One", vec![rect(0)])]);
log_with(&mut s, "#targetengine keep\nvar play = function () { app.doScript('One', 'Set'); };", &first);
assert_eq!(objects(&s), 0);
// The next run has no actions: the function kept from the first run finds none.
let call = "#targetengine keep\ntry { play(); vc.log('ok'); } catch (e) { vc.log(e.message); }";
assert_eq!(log_with(&mut s, call, &json!([])), vec![json!("there is no action set “Set”")]);
let two = set(&[("One", vec![rect(0), rect(30)])]);
assert_eq!(log_with(&mut s, call, &two), vec![json!("ok")]);
assert_eq!(objects(&s), 2);
}
/// Makes artboard `index` of the active document the view's active one, as the app does before each
/// command.
fn make_active(s: &mut Session, index: usize) {
let id = s.active().unwrap().doc.artboards[index].id;
s.doc_mut().unwrap().active_artboard = Some(id);
}
/// A step that acts on the active artboard, Align to Artboard in a recorded batch and Fit to Selected
/// Art, acts on the active artboard's index as the run started; after the script deletes that
/// artboard, the last one. A step that names its artboard keeps it.
#[test]
fn steps_act_on_the_artboard_active_as_they_run() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
let was = boards(&s);
make_active(&mut s, 2);
let align = |to: Value| json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard", "artboard": to}});
let mut first = align(json!(0));
first["params"].as_object_mut().unwrap().remove("artboard");
let actions = set(&[
("Align", vec![json!({"command": "command.batch", "params": {"commands": [first]}})]),
("Align 1", vec![align(json!(0))]),
("Fit", vec![json!({"command": "artboard.fitToSelection"})]),
]);
let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0;
log_with(&mut s, "vc.run('artboard.delete', {index: 2}); app.doScript('Align', 'Set'); app.doScript('Fit', 'Set');", &actions);
let art = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
assert_eq!(art.x0, was[1].x0, "aligned to the last artboard, where the deleted active one was");
assert_eq!(boards(&s), [was[0], art], "Fit to Selected Art resizes that artboard and leaves the other");
log_with(&mut s, "app.doScript('Align 1', 'Set');", &actions);
assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it");
}
/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none,
/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it.
#[test]
fn a_batch_steps_artboard_holds_for_its_steps_that_name_none() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
make_active(&mut s, 1);
let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}});
let mut own = align.clone();
own["params"]["artboard"] = json!(1);
let batch = |artboard: u64, step: &Value| json!({"command": "command.batch", "params": {"artboard": artboard, "commands": [step]}});
let actions = set(&[("First", vec![batch(0, &align)]), ("Past", vec![batch(9, &align)]), ("Own", vec![batch(0, &own)])]);
let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0;
log_with(&mut s, "app.doScript('First', 'Set');", &actions);
assert_eq!(left(&s), was[0].x0, "the batch's artboard 0");
log_with(&mut s, "app.doScript('Past', 'Set');", &actions);
assert_eq!(left(&s), was[2].x0, "past the last artboard, the last one");
log_with(&mut s, "app.doScript('Own', 'Set');", &actions);
assert_eq!(left(&s), was[1].x0, "a step that names artboard 1 keeps it");
}
/// The active artboard a step gets is the index it had as the run started: after a step deletes an
/// artboard before it, the artboard now at that index, as the view shows it.
#[test]
fn steps_keep_the_active_artboards_index() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap();
let uid = s.active().unwrap().uid;
let start = script::actions::Start { active: &[(uid, 1)], picks: None, batch: None };
let add = |s: &Session| script::actions::on_active_artboard(s, &start, "object.align", &json!({}));
assert_eq!(add(&s), json!({"artboard": 1}));
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
assert_eq!(add(&s), json!({"artboard": 1}), "the artboard now at index 1");
s.execute("artboard.delete", &json!({"index": 1})).unwrap();
assert_eq!(add(&s), json!({"artboard": 0}), "past the last artboard, the last one");
}
/// A Fit to Artwork Bounds step that names no artboard fits the active one; one that names its
/// `indices` fits those.
#[test]
fn a_fit_to_artwork_bounds_step_fits_the_active_artboard_or_its_own() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap();
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
let mut art = Vec::new();
for b in &was {
let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap());
}
make_active(&mut s, 1);
let actions = set(&[
("Fit", vec![json!({"command": "artboard.fitToArt"})]),
("Fit first", vec![json!({"command": "artboard.fitToArt", "params": {"indices": [0]}})]),
]);
let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
log_with(&mut s, "app.doScript('Fit', 'Set');", &actions);
assert_eq!(boards(&s), [was[0], art[1]], "the active artboard fits its art");
log_with(&mut s, "app.doScript('Fit first', 'Set');", &actions);
assert_eq!(boards(&s), art, "the step's own indices");
}
/// While the Artboard tool has several artboards selected, a paste step gets no artboard, so that it
/// pastes on those, and a Fit to Artwork Bounds step gets those as its `indices`; the other steps
/// still get the active one.
#[test]
fn paste_and_fit_steps_keep_the_artboard_tools_selection() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap();
make_active(&mut s, 1);
let start = script::actions::Start { active: &[], picks: None, batch: None };
let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({}));
assert_eq!(add(&s, "edit.pasteInPlace"), json!({"artboard": 1}));
assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1}));
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
s.set_tool_option("selected", &json!([0, 2]));
for id in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] {
assert_eq!(add(&s, id), json!({}), "{id}");
}
assert_eq!(add(&s, "artboard.fitToArt"), json!({"indices": [0, 2]}));
assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1}));
assert_eq!(add(&s, "object.align"), json!({"artboard": 1}));
assert_eq!(add(&s, "shape.rectangle"), json!({}));
}
/// The Artboard tool's selection as `script.run` starts holds for the steps `app.doScript` plays,
/// though the run gives the tool fresh state: a paste step pastes on those artboards and a Fit to
/// Artwork Bounds step fits them.
#[test]
fn a_run_keeps_the_artboard_tools_selection_for_its_steps() {
// Three artboards with a rectangle on each, artboard 1 active and the Artboard tool holding 0 and 2.
let setup = || {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
let mut art = Vec::new();
for b in &was {
let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap());
}
s.execute("edit.copy", &json!({})).unwrap();
make_active(&mut s, 1);
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
s.set_tool_option("selected", &json!([0, 2]));
(s, was, art)
};
let actions = set(&[("Paste", vec![json!({"command": "edit.pasteInPlace"})]), ("Fit", vec![json!({"command": "artboard.fitToArt"})])]);
let (mut s, ..) = setup();
let before = objects(&s);
log_with(&mut s, "app.doScript('Paste', 'Set');", &actions);
assert_eq!(objects(&s), before + 2, "one copy on each selected artboard");
let (mut s, was, art) = setup();
log_with(&mut s, "app.doScript('Fit', 'Set');", &actions);
let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
assert_eq!(boards, [art[0], was[1], art[2]], "the selected artboards fit their art");
// A kept artboard past the last one is left out; with fewer than two left, the active one applies.
let (mut s, ..) = setup();
s.reset_tool();
let uid = s.active().unwrap().uid;
let kept = (uid, vec![0, 2]);
let start = script::actions::Start { active: &[(uid, 1)], picks: Some(&kept), batch: None };
let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({}));
assert_eq!(add(&s, "edit.pasteInBack"), json!({"artboards": [0, 2]}));
assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1}));
s.execute("artboard.delete", &json!({"index": 2})).unwrap();
assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1}));
}
+30
View File
@@ -2232,6 +2232,36 @@ fn a_collection_read_with_a_name_gives_the_named_object() {
assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]);
}
/// A collection read with a name that is the text of a number but not an array index, such as `-1`
/// or `1.5`, gives the object of that name, and `undefined` when nothing has it; array indices stay
/// positions, and `index` still takes a number as a position.
#[test]
fn a_collection_read_with_a_number_name_that_is_not_an_index_gives_the_named_object() {
let (mut s, a, b) = doc();
s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap();
s.execute("object.setProps", &json!({"ids": [b.0], "name": "NaN"})).unwrap();
let out = log(
&mut s,
"var p = app.activeDocument.pageItems, m = [];\
vc.log([p['-1'] === p.getByName('-1'), '-1' in p, p[-1] === p.getByName('-1'), p.NaN === p.getByName('NaN'), 'NaN' in p]);\
vc.log([p['1.5'] === undefined, '1.5' in p, p[0].name, p['1'].name]);\
try { p.index(-1); } catch (e) { m.push(e.message); }\
var t = new DocumentPreset(); t.title = '1.5'; var d = app.documents.addDocument('Print', t);\
var ds = app.documents; vc.log([ds['1.5'] === d, '1.5' in ds, ds[1.5] === d, ds['-1'] === undefined, '-1' in ds]);\
try { ds.index(1.5); } catch (e) { m.push(e.message); }\
vc.log(m);",
);
assert_eq!(
out,
vec![
json!([true, true, true, true, true]),
json!([true, false, "NaN", "-1"]),
json!([true, true, true, true, false]),
json!(["Not found", "Not found"]),
]
);
}
/// `opacity`, `blendingMode`, `hidden`, `locked` and the position and size setters on an object in a hidden or
/// locked layer throw and the run changes nothing, while its name and note still change; an object
/// that is hidden or locked itself takes them.
+1
View File
@@ -376,6 +376,7 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() {
fuel: script::DEFAULT_FUEL,
locale: "en_US".into(),
answers: Vec::new(),
actions: Vec::new(),
};
s.script_start(request).unwrap();
assert_eq!(s.script_run_to_end().unwrap()["log"], json!([1]));
+1 -1
View File
@@ -182,7 +182,7 @@ fn failed_script_report_keeps_message_and_adds_origin() {
("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"),
("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"),
("throw 'invalid array length';", "thrown", "invalid array length", "script"),
("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"),
("throw 'ReferenceError: BridgeTalk is not defined';", "thrown", "ReferenceError: BridgeTalk is not defined", "script"),
("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"),
("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"),
("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"),
+24
View File
@@ -489,6 +489,30 @@ fn setting_a_ranges_length_moves_its_end_and_leaves_the_text() {
assert_eq!(undo_steps(&s), before + 1);
}
/// A length that ends inside a surrogate pair moves the range's end out to the end of the character.
#[test]
fn a_length_ending_inside_a_surrogate_pair_keeps_the_character_whole() {
let (mut s, _) = doc_with("a\u{1F600}b");
let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.length = 2; vc.log([r.length, r.end, r.contents]);");
assert_eq!(out, vec![json!([3, 3, "a\u{1F600}"])]);
}
/// `textFrames.removeAll()` deletes nothing when type is on a locked artboard.
#[test]
fn remove_all_type_refuses_type_on_a_locked_artboard() {
let (mut s, id) = doc_with("kept");
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let steps = undo_steps(&s);
let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();");
assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", id.0)), "{e}");
assert!(s.active().unwrap().doc.node(id).is_some());
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn collections_of_text_add_words_characters_and_paragraphs() {
let cases = [
+639
View File
@@ -0,0 +1,639 @@
//! Threaded type in the script object model: `nextFrame`, `previousFrame`, `story`,
//! `document.stories`, and the text of a story of several frames.
use serde_json::{Value, json};
use crate::*;
fn run(s: &mut Session, source: &str) -> Result<Value> {
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
}
/// What the run logged.
fn log(s: &mut Session, source: &str) -> Vec<Value> {
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
r["log"].as_array().cloned().unwrap_or_default()
}
/// The message of the run's failure.
fn failure(s: &mut Session, source: &str) -> String {
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
}
fn undo_steps(s: &Session) -> usize {
s.active().unwrap().history.undo.len()
}
fn new_doc() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
s
}
/// Area type `width` × `height` at `x` holding `text`.
fn area(s: &mut Session, x: f64, width: f64, height: f64, text: &str) -> NodeId {
let r = s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "size": 12, "area": {"width": width, "height": height}})).unwrap();
NodeId(r["id"].as_u64().unwrap())
}
fn plain(s: &Session, id: NodeId) -> String {
match &s.active().unwrap().doc.node(id).unwrap().kind {
NodeKind::Text(t) => t.plain_text(),
_ => panic!("not text"),
}
}
fn threads(s: &Session) -> Vec<Vec<NodeId>> {
s.active().unwrap().doc.text_threads.clone()
}
/// The text of every frame of the document's threads, in thread order.
fn story(s: &Session, frames: &[NodeId]) -> String {
frames.iter().map(|f| plain(s, *f)).collect()
}
/// Two area frames threaded into one story whose text starts in the first, one line high, and
/// flows on into the second.
fn threaded(text: &str) -> (Session, NodeId, NodeId) {
let mut s = new_doc();
let a = area(&mut s, 10.0, 90.0, 18.0, text);
let b = area(&mut s, 150.0, 200.0, 200.0, "");
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
s.execute("select.none", &json!({})).unwrap();
assert_eq!(threads(&s), vec![vec![a, b]]);
(s, a, b)
}
const STORY: &str = "alpha beta gamma\ndelta \u{1F600}";
#[test]
fn stories_list_one_story_for_each_thread_and_each_frame_in_none() {
let (mut s, _, _) = threaded(STORY);
area(&mut s, 400.0, 120.0, 40.0, "Alone");
let out = log(
&mut s,
"var d = app.activeDocument, st = d.stories[1];\
vc.log(d.stories.length); vc.log(st.typename); vc.log(st.textFrames.length);\
vc.log(st.textFrames[0].nextFrame.previousFrame.contents === st.textFrames[0].contents);\
vc.log(st.textFrames[1].nextFrame === null && st.textFrames[0].previousFrame === null);\
vc.log(d.stories[0].textFrames[0].contents); vc.log(d.stories[0].textFrames.length);\
d.textFrames.add(); vc.log(d.stories.length);\
vc.log(d.stories.parent.typename); vc.log(st.parent.typename); vc.log(d.stories.typename);\
vc.log(d.textFrames[1].story.textFrames[0].contents);",
);
assert_eq!(
out,
vec![
json!(2),
json!("Story"),
json!(2),
json!(true),
json!(true),
json!("Alone"),
json!(1),
json!(3),
json!("Document"),
json!("Document"),
json!("Stories"),
json!("Alone")
]
);
}
#[test]
fn a_story_range_counts_utf16_units_across_its_frames() {
let (mut s, a, b) = threaded(STORY);
let (first, second) = (plain(&s, a), plain(&s, b));
assert!(!first.is_empty() && !second.is_empty(), "the story flows through both frames: {first:?} {second:?}");
assert_eq!(first.clone() + &second, STORY);
let out = log(
&mut s,
"var st = app.activeDocument.textFrames[0].story, r = st.textRange;\
vc.log(st.length); vc.log(r.length); vc.log(r.contents); vc.log(r.typename);\
vc.log(st.characters.length); vc.log(st.words.length); vc.log(st.paragraphs.length);\
vc.log(st.paragraphs[0].contents); vc.log(st.words[4].contents); vc.log(st.words[4].start);\
vc.log(r.paragraphs[1].getParagraphLength()); vc.log(r.story.length);\
vc.log(app.activeDocument.textFrames[0].textRange.length < r.length);",
);
assert_eq!(
out,
vec![
json!(25),
json!(25),
json!("alpha beta gamma\rdelta \u{1F600}"),
json!("TextRange"),
json!(24),
json!(5),
json!(2),
json!("alpha beta gamma\r"),
json!("\u{1F600}"),
json!(23),
json!(8),
json!(25),
json!(true)
]
);
}
/// The members a long story's range does not have yet throw that they are not available, and
/// first that a range that went stale is stale.
#[test]
fn a_story_range_names_the_members_it_does_not_have_yet() {
let (mut s, _, b) = threaded(STORY);
let out = log(
&mut s,
"var r = app.activeDocument.textFrames[0].story.textRange;\
try { r.characterAttributes; } catch (e) { vc.log(String(e.message)); }\
try { r.size = 20; } catch (e) { vc.log(String(e.message)); }\
try { app.activeDocument.textFrames[0].story.lines; } catch (e) { vc.log(String(e.message)); }",
);
assert_eq!(
out,
vec![
json!("TextRange.characterAttributes is not available yet"),
json!("TextRange.size is not available yet"),
json!("Story.lines is not available yet")
]
);
let message = failure(
&mut s,
&format!(
"var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.characterAttributes;",
b.0
),
);
assert!(message.contains("Stale text range"), "{message}");
let message = failure(
&mut s,
&format!(
"var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.typename;",
b.0
),
);
assert!(message.contains("Stale text range"), "{message}");
}
/// Ranges of one story read from different frames keep their places through each other's edits.
#[test]
fn story_ranges_read_from_different_frames_follow_each_others_edits() {
let (mut s, _, _) = threaded(STORY);
let out = log(
&mut s,
"var t = app.activeDocument.textFrames, x = t[0].story.words[0], y = t[1].story.words[1];\
x.contents = 'Q'; vc.log(y.contents); vc.log(y.start); y.contents = 'B'; vc.log(x.contents);\
vc.log(t[1].story.textRange.contents);",
);
assert_eq!(out, vec![json!("beta"), json!(2), json!("Q"), json!("Q B gamma\rdelta \u{1F600}")]);
}
/// A story range that an edit covers holds the edit's new text, as a frame's range does.
#[test]
fn a_story_range_an_edit_covers_holds_the_new_text() {
let (mut s, _, _) = threaded(STORY);
let out = log(
&mut s,
"var st = app.activeDocument.textFrames[0].story, w = st.words[1], p = st.paragraphs[1];\
st.textRange.contents = 'Z'; vc.log(w.contents); vc.log(p.contents); vc.log(w.typename); vc.log(st.words.typename);",
);
assert_eq!(out, vec![json!("Z"), json!("Z"), json!("TextRange"), json!("Words")]);
}
#[test]
fn a_story_edit_across_frames_reflows_in_one_undo_step() {
let (mut s, a, b) = threaded(STORY);
let before = undo_steps(&s);
let out = log(
&mut s,
"var st = app.activeDocument.textFrames[0].story, frame = app.activeDocument.textFrames[1].textRange;\
var p = st.paragraphs[0], tail = st.paragraphs[1];\
p.contents = 'X\\r'; vc.log(st.textRange.contents); vc.log(tail.contents); vc.log(tail.start);\
try { frame.contents; } catch (e) { vc.log(String(e.message)); }\
st.words[2].remove(); vc.log(st.textRange.contents);",
);
assert_eq!(out, vec![json!("X\rdelta \u{1F600}"), json!("delta \u{1F600}"), json!(2), json!("Stale text range"), json!("X\rdelta ")]);
assert_eq!(story(&s, &[a, b]), "X\ndelta ");
assert_eq!(undo_steps(&s), before + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(story(&s, &[a, b]), STORY);
}
#[test]
fn a_story_range_is_stale_after_another_change_to_the_story() {
let (mut s, _, b) = threaded(STORY);
let message = failure(
&mut s,
&format!(
"var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.contents;",
b.0
),
);
assert!(message.contains("Stale text range"), "{message}");
}
#[test]
fn a_story_range_made_before_file_revert_is_stale_even_when_the_text_is_the_same() {
let (mut s, _, _) = threaded(STORY);
let path = std::env::temp_dir().join(format!("vc-story-revert-{}.vectorcraft", std::process::id()));
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
let out = log(
&mut s,
"var r = app.activeDocument.textFrames[0].story.words[1];\
vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\
var st = app.activeDocument.textFrames[0].story;\
vc.log(st.textFrames.length); vc.log(st.textRange.contents);\
try { vc.log(r.contents); } catch (e) { vc.log(String(e.message)); }\
vc.log(st.words[1].contents);",
);
let _ = std::fs::remove_file(&path);
assert_eq!(out[0], json!(2), "the reverted file keeps the thread");
assert_eq!(out[1], json!("alpha beta gamma\rdelta \u{1F600}"), "the reverted file holds the same text");
assert!(out[2].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}");
assert_eq!(out[3], json!("beta"), "a range made after the revert reads the reverted text");
}
#[test]
fn next_frame_joins_two_stories_in_one_undo_step_keeping_the_selection() {
let mut s = new_doc();
let a = area(&mut s, 10.0, 120.0, 60.0, "First story.");
let b = area(&mut s, 150.0, 120.0, 60.0, "Second.");
let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [p.0]})).unwrap();
let before = undo_steps(&s);
let out = log(
&mut s,
"var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];\
vc.log(app.activeDocument.stories.length); vc.log(t[1].previousFrame.contents); vc.log(t[2].story.textRange.contents);\
t[2].nextFrame = t[1];",
);
assert_eq!(out, vec![json!(2), json!("First story.Second."), json!("First story.Second.")]);
assert_eq!(threads(&s), vec![vec![a, b]]);
assert_eq!(story(&s, &[a, b]), "First story.Second.");
assert_eq!(undo_steps(&s), before + 1);
assert_eq!(s.active().unwrap().selection.objects.to_vec(), vec![p]);
// previousFrame links the other way.
s.execute("edit.undo", &json!({})).unwrap();
assert!(threads(&s).is_empty());
assert_eq!((plain(&s, a), plain(&s, b)), ("First story.".into(), "Second.".into()));
log(&mut s, "var t = app.activeDocument.textFrames; t[2].previousFrame = t[1];");
assert_eq!(threads(&s), vec![vec![b, a]]);
assert_eq!(story(&s, &[b, a]), "Second.First story.");
}
#[test]
fn null_breaks_the_link_and_each_frame_keeps_its_text() {
let (mut s, a, b) = threaded(STORY);
let (first, second) = (plain(&s, a), plain(&s, b));
let before = undo_steps(&s);
let out = log(
&mut s,
"var t = app.activeDocument.textFrames, st = t[0].story; t[0].previousFrame = null;\
vc.log(app.activeDocument.stories.length); vc.log(st.textFrames.length); vc.log(t[1].nextFrame);\
t[1].nextFrame = null;",
);
assert_eq!(out, vec![json!(2), json!(1), json!(null)]);
assert!(threads(&s).is_empty());
assert_eq!((plain(&s, a), plain(&s, b)), (first, second));
assert_eq!(undo_steps(&s), before + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(threads(&s), vec![vec![a, b]]);
}
#[test]
fn area_and_path_text_thread_the_new_frame_to_a_base_frame() {
let mut s = new_doc();
let base = area(&mut s, 10.0, 120.0, 40.0, "Base text that is long enough to flow on into the frames made after it.");
s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap();
s.execute("shape.rectangle", &json!({"x": 350, "y": 10, "width": 120, "height": 60})).unwrap();
s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 300}, {"x": 400, "y": 320}], "closed": false})).unwrap();
let before = undo_steps(&s);
let out = log(
&mut s,
"var d = app.activeDocument, p = d.pageItems, base = d.textFrames[0];\
var after = d.textFrames.areaText(p[2], undefined, base);\
var first = d.textFrames.areaText(p[1], TextOrientation.HORIZONTAL, base, false);\
var last = d.textFrames.pathText(p[0], undefined, undefined, undefined, after, true);\
vc.log(base.story.textFrames.length); vc.log(base.previousFrame.kind); vc.log(after.nextFrame.kind); vc.log(d.stories.length);",
);
assert_eq!(out, vec![json!(4), json!("TextType.AREATEXT"), json!("TextType.PATHTEXT"), json!(1)]);
let t = threads(&s);
assert_eq!(t.len(), 1);
assert_eq!(t[0][1], base, "the frame made with postFix false comes before the base frame: {t:?}");
assert_eq!(undo_steps(&s), before + 1);
}
#[test]
fn a_bad_base_frame_is_refused_before_a_frame_is_made() {
let mut s = new_doc();
s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap();
let count = |s: &Session| s.active().unwrap().doc.node_count();
let (n, before) = (count(&s), undo_steps(&s));
let d = "var d = app.activeDocument, p = d.pageItems;";
assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0]);")).contains("only area type"));
assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, p[0]);")).contains("baseFrame must be a TextFrame"));
assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0], 'yes');")).contains("postFix"));
assert_eq!((count(&s), undo_steps(&s)), (n, before));
}
/// A base frame given with a path inside a compound path is refused before the path is turned
/// into type, so a script that catches the error finds the path as it was.
#[test]
fn a_base_frame_for_a_path_in_a_compound_path_leaves_the_path() {
let mut s = new_doc();
area(&mut s, 10.0, 120.0, 60.0, "Base.");
let r1 = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
let r2 = s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [r1, r2]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let before = undo_steps(&s);
let out = log(
&mut s,
"var d = app.activeDocument, p = null;\
for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename == 'PathItem') { p = d.pageItems[i]; break; } }\
try { d.textFrames.areaText(p, undefined, d.textFrames[0]); } catch (e) { vc.log(String(e.message)); }\
vc.log(p.typename); vc.log(d.textFrames.length);",
);
assert_eq!(out, vec![json!("baseFrame: type made from a path inside a compound path cannot be threaded"), json!("PathItem"), json!(1)]);
assert_eq!(undo_steps(&s), before);
}
/// A thread of `a` and `b`, a third area frame `c`, and point type `p`; what the document holds
/// now, to check that a refused change left it alone.
fn three() -> (Session, [NodeId; 4]) {
let (mut s, a, b) = threaded(STORY);
let c = area(&mut s, 400.0, 120.0, 40.0, "Third");
let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap());
(s, [a, b, c, p])
}
fn unchanged(s: &Session, ids: &[NodeId], before: &(Vec<Vec<NodeId>>, Vec<String>, usize)) {
assert_eq!((threads(s), ids.iter().map(|i| plain(s, *i)).collect::<Vec<_>>(), undo_steps(s)), *before);
}
fn state(s: &Session, ids: &[NodeId]) -> (Vec<Vec<NodeId>>, Vec<String>, usize) {
(threads(s), ids.iter().map(|i| plain(s, *i)).collect(), undo_steps(s))
}
#[test]
fn a_link_to_the_frame_itself_is_refused() {
let (mut s, ids) = three();
let before = state(&s, &ids);
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[2];");
assert!(m.contains("nextFrame") && m.contains("itself"), "{m}");
unchanged(&s, &ids, &before);
}
#[test]
fn a_link_that_makes_a_loop_is_refused() {
let (mut s, ids) = three();
let before = state(&s, &ids);
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[3];");
assert!(m.contains("loop"), "{m}");
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].previousFrame = t[2];");
assert!(m.contains("loop"), "{m}");
unchanged(&s, &ids, &before);
}
#[test]
fn a_link_into_the_middle_of_a_story_is_refused() {
let (mut s, ids) = three();
let before = state(&s, &ids);
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[2];");
assert!(m.contains("already has a previous frame"), "{m}");
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].previousFrame = t[3];");
assert!(m.contains("already has a next frame"), "{m}");
unchanged(&s, &ids, &before);
}
#[test]
fn point_type_and_other_values_cannot_be_linked() {
let (mut s, ids) = three();
let before = state(&s, &ids);
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[0];");
assert!(m.contains("only area type"), "{m}");
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];");
assert!(m.contains("only area type"), "{m}");
let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = 5;");
assert!(m.contains("TypeError") && m.contains("TextFrame or null"), "{m}");
let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = undefined;");
assert!(m.contains("TextFrame or null"), "{m}");
unchanged(&s, &ids, &before);
}
#[test]
fn a_hidden_or_locked_frame_in_either_story_stops_a_link() {
let (mut s, ids) = three();
log(&mut s, "app.activeDocument.textFrames[2].locked = true;");
let before = state(&s, &ids);
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];");
assert!(m.contains("hidden or locked"), "{m}");
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].nextFrame = null;");
assert!(m.contains("hidden or locked"), "{m}");
// A script that catches the error goes on, and the links stay as they were.
let out = log(
&mut s,
"var t = app.activeDocument.textFrames; try { t[2].nextFrame = t[1]; } catch (e) { vc.log([e.name, /hidden or locked/.test(e.message)]); }\
vc.log(t[2].nextFrame === null);",
);
assert_eq!(out, vec![json!(["Error", true]), json!(true)]);
unchanged(&s, &ids, &before);
}
/// Reading a story whose text is larger than what one run may pass to and from the host stops
/// the run when the story's text is joined.
#[test]
fn joining_a_storys_text_counts_toward_the_runs_data_limit() {
let text = "word ".repeat(40_000);
let (mut s, _, _) = threaded(&text);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(100_000)));
let r = run(&mut s, "vc.log(app.activeDocument.stories[0].length);");
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
let e = r.map(|r| panic!("the run read a 200 KB story within a 100 KB limit: {r}")).unwrap_err().to_string();
assert!(e.contains("more data to and from commands"), "{e}");
}
#[test]
fn a_frame_of_another_document_cannot_be_linked() {
let (mut s, ids) = three();
let before = state(&s, &ids);
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
area(&mut s, 10.0, 100.0, 40.0, "Elsewhere");
s.execute("shape.rectangle", &json!({"x": 150, "y": 10, "width": 80, "height": 60})).unwrap();
let m = failure(&mut s, "app.documents[1].textFrames[1].nextFrame = app.documents[0].textFrames[0];");
assert!(m.contains("different documents"), "{m}");
let out = log(
&mut s,
"var d = app.documents[0], p = d.pageItems[0];\
try { d.textFrames.areaText(p, undefined, app.documents[1].textFrames[1]); } catch (e) { vc.log(String(e.message)); }\
vc.log(p.typename); vc.log(d.textFrames.length);",
);
assert_eq!(out, vec![json!("baseFrame: the frame is in another document"), json!("PathItem"), json!(1)]);
s.execute("document.activate", &json!({"index": 0})).unwrap();
unchanged(&s, &ids, &before);
}
#[test]
fn a_deleted_frame_makes_its_story_and_links_stale() {
let (mut s, _, _) = threaded(STORY);
let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.length;");
assert!(m.contains("Stale story"), "{m}");
let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.lines;");
assert!(m.contains("Stale story"), "{m}");
let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], g = app.activeDocument.textFrames[0]; g.remove(); f.nextFrame = g;");
assert!(m.contains("Stale page item"), "{m}");
let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], r = f.story.textRange; f.remove(); r.contents;");
assert!(m.contains("Stale text range"), "{m}");
// A story read from a frame that stays follows it when its link is broken.
let out = log(&mut s, "var t = app.activeDocument.textFrames, st = t[0].story; t[1].nextFrame = null; vc.log(st.textFrames.length);");
assert_eq!(out, vec![json!(1)]);
}
#[test]
fn stories_refuse_bad_keys_and_huge_numbers() {
let (mut s, _, _) = threaded(STORY);
let out = log(
&mut s,
"var st = app.activeDocument.stories; vc.log(st[1e300] === undefined); vc.log(st[-1] === undefined); vc.log(st[0.5] === undefined);",
);
assert_eq!(out, vec![json!(true), json!(true), json!(true)]);
assert!(failure(&mut s, "app.activeDocument.stories.index(1e20);").contains("Not found"));
assert!(failure(&mut s, "app.activeDocument.stories.index('nobody');").contains("Not found"));
assert!(failure(&mut s, "app.activeDocument.stories.index({});").contains("TypeError"));
log(&mut s, "app.activeDocument.textFrames[1].name = 'Lead';");
assert_eq!(log(&mut s, "vc.log(app.activeDocument.stories.index('Lead').textFrames.length);"), vec![json!(2)]);
}
#[test]
fn a_long_story_walks_to_its_end_and_refuses_a_loop() {
let mut s = new_doc();
let ids: Vec<NodeId> = (0..120).map(|i| area(&mut s, f64::from(i % 12) * 45.0, 40.0, 20.0, if i == 0 { STORY } else { "" })).collect();
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
s.execute("select.none", &json!({})).unwrap();
assert_eq!(threads(&s), vec![ids.clone()]);
let out = log(
&mut s,
"var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame) { f = f.nextFrame; n++; } \
vc.log(n); vc.log(f.story.textFrames.length); vc.log(d.stories.length);",
);
assert_eq!(out, vec![json!(120), json!(120), json!(1)]);
let before = state(&s, &ids);
let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[t.length - 1].nextFrame = t[0];");
assert!(m.contains("loop"), "{m}");
let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[0].previousFrame = t[t.length - 1];");
assert!(m.contains("loop"), "{m}");
let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[60].nextFrame = t[30];");
assert!(m.contains("loop"), "{m}");
unchanged(&s, &ids, &before);
}
/// A stored thread that lists a frame twice, as a file can, is a story that visits each frame
/// once, so a walk along `nextFrame` ends.
#[test]
fn a_thread_listing_a_frame_twice_is_walked_once() {
let mut s = new_doc();
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b, a]];
let out = log(
&mut s,
"var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame && n < 10) { f = f.nextFrame; n++; } \
vc.log(n); vc.log(d.stories[0].textFrames.length); vc.log(d.stories.length);",
);
assert_eq!(out, vec![json!(2), json!(2), json!(1)]);
let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": null})).unwrap();
assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]}));
assert!(threads(&s).is_empty());
}
/// When a frame is listed in two threads, a story read from a frame of the second thread reads
/// that thread's text, not the text of the story read before it from a shared frame.
#[test]
fn stories_of_threads_that_share_a_frame_keep_their_own_text() {
let mut s = new_doc();
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
let c = area(&mut s, 300.0, 120.0, 60.0, "Three!");
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b], vec![b, c]];
let out = log(&mut s, "var t = app.activeDocument.textFrames; vc.log(t[1].story.length); vc.log(t[0].story.length);");
let (ab, bc) = (story(&s, &[a, b]).encode_utf16().count(), story(&s, &[b, c]).encode_utf16().count());
assert_ne!(ab, bc);
assert_eq!(out, vec![json!(ab), json!(bc)]);
}
/// A story and its range keep the exact id of the frame they were read from, also past 2^53.
#[test]
fn a_story_read_from_a_frame_with_a_large_id_stays_with_that_frame() {
let mut s = new_doc();
// The second frame's id, 2^53 + 1, is not exact as a number.
let big = 1u64 << 53;
s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big));
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
assert_eq!((a.0, b.0), (big, big + 1));
s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap();
let out = log(
&mut s,
"var st = app.activeDocument.stories[0].textFrames[1].story, r = st.textRange; vc.log(r.contents);\
st.textFrames[0].nextFrame = null; vc.log(st.textFrames.length); vc.log(st.textFrames[0].contents); vc.log(st.typename);",
);
// The whole story flows into the first frame, so the second is empty once the link is broken.
assert_eq!(out, vec![json!("One.Two."), json!(1), json!(""), json!("Story")]);
}
#[test]
fn set_neighbor_links_and_breaks_frames_by_id_without_a_selection() {
let mut s = new_doc();
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
s.execute("select.none", &json!({})).unwrap();
let before = undo_steps(&s);
let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap();
assert_eq!(r, json!({"changed": true, "threads": [[a.0, b.0]]}));
let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": a.0})).unwrap();
assert_eq!(r["changed"], json!(false));
assert_eq!(undo_steps(&s), before + 1);
assert!(s.active().unwrap().selection.objects.is_empty());
let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap();
assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]}));
let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap();
assert_eq!(r["changed"], json!(false));
assert_eq!(undo_steps(&s), before + 2);
for bad in [
json!({"id": a.0, "side": "up", "neighbor": b.0}),
json!({"id": a.0, "side": "next"}),
json!({"id": a.0, "side": "next", "neighbor": 999_999}),
] {
assert!(s.execute("text.thread.setNeighbor", &bad).is_err(), "{bad}");
}
assert_eq!(undo_steps(&s), before + 2);
}
/// Breaking a link where a paragraph starts makes the frames after it a story whose numbered
/// paragraphs count from 1, also when that story keeps two frames.
#[test]
fn a_break_at_a_paragraph_start_numbers_the_later_story_from_one() {
let mut s = new_doc();
let items = (1..=12).map(|i| format!("Item {i}")).collect::<Vec<_>>().join("\n");
let ids = [area(&mut s, 10.0, 150.0, 60.0, &items), area(&mut s, 200.0, 150.0, 60.0, ""), area(&mut s, 400.0, 150.0, 200.0, "")];
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
s.execute("text.setFormat", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "list": "number"})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let numbers = |s: &Session, id: NodeId| {
let Some(NodeKind::Text(t)) = s.active().unwrap().doc.node(id).map(|n| &n.kind) else { panic!("text") };
assert!(!t.first_para_continues, "every frame starts a paragraph");
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>()
};
let first = numbers(&s, ids[0]);
assert!(!first.is_empty() && !numbers(&s, ids[1]).is_empty(), "the first two frames hold items");
assert_ne!(numbers(&s, ids[1]).first().map(String::as_str), Some("1."));
let r = s.execute("text.thread.setNeighbor", &json!({"id": ids[0].0, "side": "next", "neighbor": null})).unwrap();
assert_eq!(r, json!({"changed": true, "threads": [[ids[0].0], [ids[1].0, ids[2].0]]}));
let later = [numbers(&s, ids[1]), numbers(&s, ids[2])].concat();
let expected: Vec<String> = (1..=later.len()).map(|n| format!("{n}.")).collect();
assert_eq!(later, expected, "the later story counts from 1");
assert_eq!(numbers(&s, ids[0]), first);
}
+174
View File
@@ -217,4 +217,178 @@ fn set_option_sets_the_direction_and_refuses_bad_values() {
assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}");
}
assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(false));
// `join` starts off and `tangentSnap` on; both take only true or false.
assert_eq!(
(s.tool_options_of("threePointArc")["join"].clone(), s.tool_options_of("threePointArc")["tangentSnap"].clone()),
(json!(false), json!(true))
);
let set = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "values": {"join": true, "tangentSnap": false}})).unwrap();
assert_eq!((set["join"].clone(), set["tangentSnap"].clone()), (json!(true), json!(false)));
for key in ["join", "tangentSnap"] {
let e = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "key": key, "value": 1})).unwrap_err();
assert_eq!(e, format!("tool `threePointArc`: `{key}` must be true or false"));
}
}
/// An open path drawn from SVG path data, selected.
fn open_path(s: &mut Session, d: &str) -> NodeId {
id_of(&s.execute("path.create", &json!({ "d": d })).unwrap())
}
/// The anchors of the first subpath of `id`, and whether it is closed.
fn anchors(s: &Session, id: NodeId) -> (Vec<Point>, bool) {
let n = node(s, id);
let sp = &n.path_data().unwrap().subpaths[0];
(sp.anchors.iter().map(|a| a.p).collect(), sp.closed)
}
/// With `join`, an arc starting on the last anchor of an open path is added to that path: the path
/// keeps its id and direction and now ends where the arc ends, the anchor where they meet is not
/// doubled, and it is one undo step. An arc ending on a path's first anchor is added before it.
#[test]
fn join_adds_the_arc_to_the_open_path_it_starts_on() {
let mut s = session();
let id = open_path(&mut s, "M0 100 L100 100");
let (undo, count) = (undo_len(&s), object_count(&s));
let out = s.execute(C, &json!({"start": [100, 100], "end": [180, 100], "through": [140, 60], "join": true})).unwrap();
assert_eq!((id_of(&out), out["joined"].clone(), out["radius"].as_f64()), (id, json!(true), Some(40.0)), "{out}");
assert_eq!((undo_len(&s), object_count(&s)), (undo + 1, count));
let (pts, closed) = anchors(&s, id);
assert!(!closed);
assert_eq!((pts.first().copied(), pts.last().copied()), (Some(Point::new(0.0, 100.0)), Some(Point::new(180.0, 100.0))), "{pts:?}");
assert_eq!(pts.iter().filter(|p| **p == Point::new(100.0, 100.0)).count(), 1, "{pts:?}");
assert!(farthest_from_path(&s, id, &[Point::new(140.0, 60.0), Point::new(50.0, 100.0)]) < 1e-9);
assert_eq!(s.doc().unwrap().selection.objects, [id]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(anchors(&s, id).0, [Point::new(0.0, 100.0), Point::new(100.0, 100.0)]);
// The arc ends on the first anchor of a path running right: the path still runs right, from
// the arc's start.
let id = open_path(&mut s, "M300 100 L400 100");
let out = s.execute(C, &json!({"start": [220, 100], "end": [300, 100], "toward": [220, 60], "join": true})).unwrap();
assert_eq!(id_of(&out), id);
let (pts, _) = anchors(&s, id);
assert_eq!((pts.first().copied(), pts.last().copied()), (Some(Point::new(220.0, 100.0)), Some(Point::new(400.0, 100.0))), "{pts:?}");
assert!(farthest_from_path(&s, id, &[Point::new(260.0, 60.0)]) < 1e-9);
}
/// With both ends on ends of two open paths, the arc joins them into one path in one undo step;
/// with both ends on the two ends of one open path, the path closes.
#[test]
fn join_with_both_ends_on_open_paths_makes_one_path() {
let mut s = session();
let a = open_path(&mut s, "M0 100 L100 100");
let b = open_path(&mut s, "M180 100 L280 100");
let (undo, count) = (undo_len(&s), object_count(&s));
let out = s.execute(C, &json!({"start": [100, 100], "end": [180, 100], "through": [140, 60], "join": true})).unwrap();
assert_eq!(id_of(&out), a);
assert_eq!((undo_len(&s), object_count(&s)), (undo + 1, count - 1));
assert!(s.doc().unwrap().doc.node(b).is_none());
let (pts, closed) = anchors(&s, a);
assert!(!closed);
let ends = (pts.first().copied(), pts.last().copied());
assert!(
ends == (Some(Point::new(0.0, 100.0)), Some(Point::new(280.0, 100.0)))
|| ends == (Some(Point::new(280.0, 100.0)), Some(Point::new(0.0, 100.0))),
"{pts:?}"
);
for p in [Point::new(100.0, 100.0), Point::new(180.0, 100.0)] {
assert_eq!(pts.iter().filter(|q| **q == p).count(), 1, "{pts:?}");
}
assert!(farthest_from_path(&s, a, &[Point::new(140.0, 60.0), Point::new(230.0, 100.0)]) < 1e-9);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((object_count(&s), anchors(&s, b).0.len()), (count, 2));
// One path's two ends: it closes.
let id = open_path(&mut s, "M100 300 L180 300");
let out = s.execute(C, &json!({"start": [180, 300], "end": [100, 300], "through": [140, 340], "join": true})).unwrap();
assert_eq!(id_of(&out), id);
let (pts, closed) = anchors(&s, id);
assert!(closed, "{pts:?}");
assert_eq!(pts.iter().filter(|q| **q == Point::new(100.0, 300.0)).count(), 1, "{pts:?}");
assert!(farthest_from_path(&s, id, &[Point::new(140.0, 340.0), Point::new(140.0, 300.0)]) < 1e-9);
}
/// Of two open path ends at the arc's start, `join` takes the one in the selection, and with
/// neither selected the one in front.
#[test]
fn join_prefers_the_selected_path_then_the_front_one() {
let mut s = session();
let back = open_path(&mut s, "M0 100 L100 100");
let front = open_path(&mut s, "M100 200 L100 100");
for (selected, want) in [(Some(back), back), (None, front)] {
let ids: Vec<u64> = selected.iter().map(|id| id.0).collect();
s.execute("select.set", &json!({ "ids": ids })).unwrap();
let out = s.execute(C, &json!({"start": [100, 100], "end": [180, 100], "through": [140, 60], "join": true})).unwrap();
assert_eq!(id_of(&out), want, "{selected:?}");
s.execute("edit.undo", &json!({})).unwrap();
}
// In isolation mode, a path outside the isolated group is left alone.
s.execute("select.set", &json!({ "ids": [back.0] })).unwrap();
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("object.isolate", &json!({ "id": group })).unwrap();
s.execute("select.set", &json!({ "ids": [] })).unwrap();
let out = s.execute(C, &json!({"start": [100, 100], "end": [100, 20], "through": [60, 60], "join": true})).unwrap();
assert_eq!(id_of(&out), back, "{out}");
s.execute("edit.undo", &json!({})).unwrap();
let out = s.execute(C, &json!({"start": [100, 200], "end": [180, 200], "through": [140, 160], "join": true})).unwrap();
assert!(out.get("joined").is_none(), "{out}");
assert_eq!(anchors(&s, front).0.len(), 2);
}
/// Without `join`, away from open path ends, on a locked path, or on a closed path's anchor, the
/// arc is a new path; a `join` that is not true or false is an error and draws nothing.
#[test]
fn join_leaves_paths_it_cannot_join_alone() {
let mut s = session();
let line = open_path(&mut s, "M0 100 L100 100");
let rect = open_path(&mut s, "M200 200 L300 200 L300 300 Z");
let arc = |s: &mut Session, start: [f64; 2], end: [f64; 2], via: [f64; 2], join: Value| {
s.execute(C, &json!({"start": start, "end": end, "through": via, "join": join}))
};
for (start, end, via, join) in [
([100.0, 100.0], [180.0, 100.0], [140.0, 60.0], json!(false)),
([100.0, 120.0], [180.0, 120.0], [140.0, 80.0], json!(true)),
([200.0, 200.0], [120.0, 200.0], [160.0, 160.0], json!(true)),
] {
let count = object_count(&s);
let out = arc(&mut s, start, end, via, join.clone()).unwrap();
assert!(out.get("joined").is_none() && id_of(&out) != line && id_of(&out) != rect, "{join}: {out}");
assert_eq!(object_count(&s), count + 1);
}
assert_eq!(anchors(&s, line).0.len(), 2);
s.execute("select.set", &json!({"ids": [line.0]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
// On the line's other end, where none of the arcs above ends.
let out = arc(&mut s, [0.0, 100.0], [0.0, 180.0], [40.0, 140.0], json!(true)).unwrap();
assert!(out.get("joined").is_none(), "{out}");
assert_eq!(anchors(&s, line).0.len(), 2);
let count = object_count(&s);
let e = arc(&mut s, [100.0, 300.0], [180.0, 300.0], [140.0, 260.0], json!("yes")).unwrap_err().to_string();
assert!(e.contains("`join` must be true or false"), "{e}");
assert_eq!(object_count(&s), count);
}
/// With the tool's `join` option on, clicks near an open path's end place the arc's end on it and
/// the arc joins the path; with it off the arc is a path of its own, and J while the ends are
/// placed switches it on.
#[test]
fn the_tool_joins_the_arc_to_the_path_end_it_starts_near() {
let mut s = session();
let id = open_path(&mut s, "M0 100 L100 100");
s.execute("select.set", &json!({"ids": []})).unwrap();
s.select_tool("threePointArc", view()).unwrap();
let count = object_count(&s);
for p in [(100.0, 100.0), (180.0, 100.0), (140.0, 60.0)] {
click(&mut s, p.0, p.1);
}
assert_eq!((object_count(&s), anchors(&s, id).0.len()), (count + 1, 2), "off: a path of its own");
s.execute("edit.undo", &json!({})).unwrap();
// J after the first click, near the path's end, switches `join` on.
click(&mut s, 99.0, 100.5);
s.tool_key(ToolKey::Letter('j'), Mods::default(), view()).unwrap();
click(&mut s, 180.0, 100.0);
click(&mut s, 140.0, 60.0);
assert_eq!(object_count(&s), count);
let (pts, _) = anchors(&s, id);
assert_eq!((pts.len() > 2, pts.last().copied()), (true, Some(Point::new(180.0, 100.0))), "{pts:?}");
assert_eq!(s.tool_options_of("threePointArc")["join"], json!(true), "J keeps the option switched");
}
+2 -1
View File
@@ -1044,9 +1044,10 @@ fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() {
("object.cropImage", json!({})),
("imageTrace.make", json!({})),
("object.mesh.create", json!({})),
// Vector art has no pixels to put between the corners.
(
"file.place",
json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&crate::tests_links::png(2, 2, [0, 0, 255]))}),
json!({"replace": true, "name": "b.svg", "dataBase64": vectorcraft_format::base64_encode(b"<svg xmlns='http://www.w3.org/2000/svg' width='9' height='9'><rect width='9' height='9'/></svg>")}),
),
] {
let e = s.execute(cmd, &params).unwrap_err().to_string();
+54 -1
View File
@@ -6,7 +6,8 @@
//! of every kind with random contents) opened, placed or pasted, nor PICT pictures (damaged files,
//! opcodes with random contents) opened or placed, nor EPS and PostScript files
//! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of
//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor Affinity documents
//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor the widths a
//! `.ai`'s PDF part gives its fonts' characters (hostile font dictionaries), nor Affinity documents
//! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor
//! `.cdr` drawings (mutated and cut short, plain, compressed and packaged, opened and placed),
//! nor `.cmx` files (mutated, cut short and garbage after the header, opened and placed),
@@ -1171,6 +1172,58 @@ proptest! {
}
}
/// A font dictionary whose widths are hostile, for [`vectorcraft_pdf::Opened::page_widths`]: any
/// subtype, encoding and first code, widths that are huge, negative or not numbers, a composite
/// font's `W` of any shape, and the `ToUnicode` map of object 5.
fn arb_width_font() -> impl Strategy<Value = String> {
(
prop::sample::select(vec!["/TrueType", "/Type1", "/Type0", "/Type3", "/MMType1", "7"]),
prop::sample::select(vec!["/WinAnsiEncoding", "/Identity-H", "/Identity-V", "/MacRomanEncoding", "<< /Differences [65 /A] >>", "null"]),
prop::sample::select(vec!["0", "65", "-5", "255", "256", "4294967295", "1e30", "/X"]),
prop::collection::vec(prop::sample::select(vec!["500", "0", "-1", "1e40", "NaN", "null", "[1 2]", "/W"]), 0..12),
prop::collection::vec(prop::sample::select(vec!["1", "[500 600]", "65", "4294967295", "300", "-1", "[]", "1e9", "0 65535 7"]), 0..10),
prop::sample::select(vec!["/ABCDEF+Fuzz", "/Fuzz", "/ABCDEF+", "/+", "()", "/Fuzz-Identity-H"]),
any::<bool>(),
)
.prop_map(|(subtype, encoding, first, widths, w, name, mapped)| {
let map = if mapped { "/ToUnicode 5 0 R" } else { "" };
format!(
"<< /Type /Font /Subtype {subtype} /BaseFont {name} /Encoding {encoding} /FirstChar {first} /Widths [{}] {map} \
/DescendantFonts [<< /Subtype /CIDFontType2 /BaseFont {name} /W [{}] >>] >>",
widths.join(" "),
w.join(" ")
)
})
}
proptest! {
#![proptest_config(config())]
/// The widths a page's fonts give their characters (read for a `.ai`'s text document) are read
/// without a panic from hostile font dictionaries, `ToUnicode` maps of any text, and forms that
/// draw themselves.
#[test]
fn pdf_font_widths_never_panic(
fonts in prop::collection::vec(arb_width_font(), 1..4),
cmap in prop::collection::vec(prop::sample::select(vec![
"begincmap", "1 begincodespacerange", "<0000> <FFFF>", "<00> <FF>", "endcodespacerange", "2 beginbfchar", "<0001> <0041>",
"<0002> <D800>", "<41> <FFFD>", "1 beginbfrange", "<0000> <FFFF> <0000>", "<FFFF> <0000> <0041>", "<0001> <0003> [<0041> <0042>]",
"endbfrange", "endbfchar", "endcmap", "/Identity-H usecmap", "99999999999 beginbfchar",
]), 0..12),
) {
let list: Vec<String> = fonts.iter().enumerate().map(|(i, f)| format!("/F{i} {f}")).collect();
let map = cmap.join("\n");
let form = format!(
"<< /Type /XObject /Subtype /Form /BBox [0 0 1 1] /Resources << /Font << /F0 {} >> /XObject << /X0 6 0 R >> >> /Length 0 >>\nstream\n\nendstream",
fonts[0]
);
let more = [format!("<< /Length {} >>\nstream\n{map}\nendstream", map.len() + 1).into_bytes(), form.into_bytes()];
let pdf = handmade_pdf_with("", &format!("<< /Font << {} >> /XObject << /X0 6 0 R >> >>", list.join(" ")), "[0 0 100 100]", &more);
let read = catch_quiet(|| vectorcraft_pdf::open_pdf(&pdf, None).ok().map(|o| o.page_widths()));
prop_assert!(read.is_ok(), "{fonts:?} {cmap:?}: {read:?}");
}
}
/// A dictionary value: one the reader reads, or one it skips over but can't parse (a name with a
/// broken `#` escape, a number with a stray `-`).
fn arb_dict_value() -> impl Strategy<Value = &'static str> {
@@ -89,8 +89,9 @@ const INSIDE: &[(&str, &str)] = &[
("Application.", "prototype"),
(
"Application.prototype.",
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \
getIsFileOpen redraw selection selection= textFonts toString typename",
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
executeMenuCommand getIsFileOpen loadAction loadAction= redraw selection selection= textFonts toString typename \
unloadAction unloadAction=",
),
("DocumentPreset.", "prototype"),
(
@@ -107,7 +108,7 @@ const INSIDE: &[(&str, &str)] = &[
"Document.prototype.",
"activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \
groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \
rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames toString \
rulerUnits saveAs saveAs= selection selection= stories swatches swatches= symbols symbols= tags textFrames toString \
typename views width",
),
("Views.", "prototype"),
@@ -166,7 +167,7 @@ const INSIDE: &[(&str, &str)] = &[
contents contents= convertAreaObjectToPointObject convertPointObjectToAreaObject createOutline endTValue endTValue= \
insertionPoints insertionPoints= kind lines lines= matrix matrix= nextFrame nextFrame= opticalAlignment \
opticalAlignment= orientation orientation= paragraphs previousFrame previousFrame= rowCount rowCount= rowGutter \
rowGutter= startTValue startTValue= story story= textPath textPath= textRange textRanges textRanges= textSelection \
rowGutter= startTValue startTValue= story textPath textPath= textRange textRanges textRanges= textSelection \
textSelection= words",
),
("TextRange.", "prototype"),
@@ -179,7 +180,7 @@ const INSIDE: &[(&str, &str)] = &[
horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \
leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles paragraphStyles= \
paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \
spaceBefore spaceBefore= start start= story story= strikeThrough strikeThrough= textFont textFont= textRanges \
spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= textFont textFont= textRanges \
textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \
verticalScale= words",
),
@@ -209,6 +210,34 @@ const INSIDE: &[(&str, &str)] = &[
("Justification.", "CENTER FULLJUSTIFY FULLJUSTIFYLASTLINECENTER FULLJUSTIFYLASTLINELEFT FULLJUSTIFYLASTLINERIGHT LEFT RIGHT"),
("TextOrientation.", "HORIZONTAL VERTICAL"),
("TextType.", "AREATEXT PATHTEXT POINTTEXT"),
("", "Stories Story StoryCharacters StoryParagraphs StoryRange StoryWords"),
("Stories.", "prototype"),
("Stories.prototype.", "constructor index length parent typename"),
("Story.", "prototype"),
(
"Story.prototype.",
"characters constructor insertionPoints insertionPoints= length lines lines= paragraphs parent textFrames textRange \
textRanges textRanges= textSelection textSelection= typename words",
),
("StoryRange.", "prototype"),
(
"StoryRange.prototype.",
"autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes \
characterAttributes= characterOffset characterOffset= characterStyles characterStyles= characters constructor \
contents contents= deSelect deSelect= duplicate duplicate= end end= getLocalCharOverridesJSON \
getLocalCharOverridesJSON= getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength \
getTextRunLength= horizontalScale horizontalScale= insertionPoints insertionPoints= kerning kerning= leading leading= \
length length= lines lines= move move= paragraphAttributes paragraphAttributes= paragraphStyles paragraphStyles= \
paragraphs parent remove rotation rotation= select select= size size= start start= story strikeThrough \
strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \
underline underline= verticalScale verticalScale= words",
),
("StoryCharacters.", "prototype"),
("StoryCharacters.prototype.", "constructor length parent typename"),
("StoryWords.", "prototype"),
("StoryWords.prototype.", "constructor length parent typename"),
("StoryParagraphs.", "prototype"),
("StoryParagraphs.prototype.", "constructor length parent typename"),
// Variables and data sets. `importVariables` reads the library file it is given. `PageItem`'s
// `visibilityVariable` is in its row above.
("", "Dataset Datasets Variable VariableKind Variables"),
+20 -1
View File
@@ -1,7 +1,7 @@
//! Direct Selection picks several direction handles and drags them together (`path.moveHandles`).
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_engine::{Session, ViewInfo};
use vectorcraft_geom::{Anchor, AnchorKind, Point};
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
@@ -191,3 +191,22 @@ fn move_handles_checks_its_params() {
near(anchor(&s, id, 2).h_in, Point::new(305.0, 140.0));
assert_eq!(undo_len(&s), undo + 1);
}
/// A move by nothing that makes one path's smooth anchor a corner leaves a listed handle of a live
/// rectangle, which needs no change, alone: the rectangle stays live.
#[test]
fn a_move_by_nothing_leaves_a_live_shape_that_needs_no_change_live() {
let (mut s, id) = session();
let rect = s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 100, "height": 60})).unwrap();
let rect = NodeId(rect["id"].as_u64().unwrap());
let live = |s: &Session| matches!(&s.doc().unwrap().doc.node(rect).unwrap().kind, NodeKind::Path { live: Some(_), .. });
assert!(live(&s), "shape.rectangle makes a live rectangle");
let handles = json!([
{"id": id.0, "anchor": 1, "which": "in"},
{"id": id.0, "anchor": 1, "which": "out"},
{"id": rect.0, "anchor": 0, "which": "out"}
]);
s.execute("path.moveHandles", &json!({"handles": handles, "dx": 0, "dy": 0})).unwrap();
assert_eq!(anchor(&s, id, 1).kind, AnchorKind::Corner, "both handles listed make the smooth anchor a corner");
assert!(live(&s), "the rectangle's listed handle needed no change, so the rectangle stays live");
}
+2 -2
View File
@@ -634,7 +634,7 @@ fn font_name(st: &CharStyle) -> FontRecord {
.collect();
let name = face.postscript_name();
// The reader takes the face of a name alone as `postscript_face` finds it.
let by_name = crate::import::postscript_face(&name, None).is_some_and(|f| f.id() == face.id());
let by_name = crate::import::postscript_face(&name, None, None).is_some_and(|f| f.id() == face.id());
let version = if design.is_empty() && by_name { String::new() } else { face.version.clone() };
FontRecord { name, truetype: face.is_truetype(), design, version }
}
@@ -681,7 +681,7 @@ fn fixed(v: f32) -> i64 {
fn font_kept(st: &CharStyle) -> bool {
let record = font_name(st);
let version = crate::import::record_version(&record.version);
let (family, style, read) = crate::import::document_font(&record.name, version);
let (family, style, read) = crate::import::document_font(&record.name, version, None);
let db = vectorcraft_text::FontDb::global();
let face = |family: &str, style: &str, version: Option<&str>| db.face_version(family, style, version).map(|f| f.id());
family == st.font_family
+1 -1
View File
@@ -564,7 +564,7 @@ impl Reader<'_> {
st.cmap = cmap;
// The installed face of that PostScript name, as type from a text document
// takes it; else the name split into a family and style.
let text = super::super::super::text::named_font(name, None);
let text = super::super::super::text::named_font(name, None, None);
let (family, style, version) = text.unwrap_or_else(|| {
let (family, style) = super::super::super::text::family_style(name);
(family, style, None)
+4
View File
@@ -236,6 +236,10 @@ pub struct Structure {
/// placed in the document, or a color linked to its swatch at its tint (see
/// `ate::Texts::with_paints`).
pub text_paints: HashMap<String, Paint>,
/// The widths a `.ai`'s PDF part gives the characters of its fonts, which tell installed copies
/// of a font apart for type whose font record keeps no version (see
/// `ate::Texts::with_page_widths`): none until the importer sets them.
pub page_widths: vectorcraft_pdf::PageWidths,
/// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not.
pub canvas_scale: f64,
/// The data's symbols are at their own size, whatever its scale: VectorCraft wrote it (its
@@ -1481,6 +1481,7 @@ impl<'a> Reader<'a> {
},
styles_read,
text_paints,
page_widths: Default::default(),
canvas_scale: self.canvas_scale,
symbols_own_size: self.symbols_own_size,
xml_ids: self.xml_ids,
+60 -8
View File
@@ -23,6 +23,7 @@
//! a layout has its point type's anchor at its frame's point. See [`Story::place`].
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen};
use vectorcraft_color::{Color, Paint};
@@ -581,15 +582,20 @@ struct DocFont {
/// Key 5, when the record keeps it: the font's version string (name ID 5), which tells installed
/// copies of one font apart.
version: Option<String>,
/// [`Self::font`]'s answer, found once for every run that names the record.
font: std::sync::OnceLock<Font>,
/// The widths the file's page gives the font's characters, when it has them
/// ([`Texts::with_page_widths`]): without a version, they tell the copies apart. Every record
/// of the font shares them.
widths: Option<Arc<vectorcraft_pdf::FontWidths>>,
/// [`Self::font`]'s answer, found once for every run that names the record, and shared by the
/// records of the same name and version, which give the same answer.
font: Arc<std::sync::OnceLock<Font>>,
}
impl DocFont {
/// The font type set in this record's font takes: the installed copy it names
/// ([`super::text::document_font`]).
fn font(&self) -> &Font {
self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref()))
self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref(), self.widths.as_deref()))
}
}
@@ -639,6 +645,17 @@ impl Texts {
Texts { paints, ..self }
}
/// The text document with the widths `page` (the file's page, [`vectorcraft_pdf::PageWidths`])
/// gives the characters of its fonts, by each record's PostScript name: a record that keeps no
/// version is set in the installed copy of its font that sets them at those widths
/// ([`super::text::postscript_face`]).
pub(super) fn with_page_widths(mut self, page: &vectorcraft_pdf::PageWidths) -> Texts {
for f in &mut self.fonts {
f.widths = page.widths(super::text::bare_name(&f.name)).cloned();
}
self
}
/// The text document in the editing copy `data`, if it has one that can be read.
pub(super) fn read(data: &[u8]) -> Option<Texts> {
fn find(h: &[u8], n: &[u8], from: usize) -> Option<usize> {
@@ -666,6 +683,8 @@ impl Texts {
return None;
}
let doc = names::numbered(read(&bytes)?);
// Records of one name and version share their answer.
let mut answers: HashMap<(String, Option<String>), Arc<std::sync::OnceLock<Font>>> = HashMap::new();
let fonts = doc
.get("0")?
.get("1")?
@@ -675,11 +694,10 @@ impl Texts {
.map(|f| {
let record = f.get("0").and_then(|f| f.get("0"));
let text = |k: &str| record.and_then(|r| r.get(k)).and_then(Val::str);
DocFont {
name: text("0").unwrap_or_default().to_string(),
version: text("5").and_then(record_version).map(str::to_string),
font: std::sync::OnceLock::new(),
}
let name = text("0").unwrap_or_default().to_string();
let version = text("5").and_then(record_version).map(str::to_string);
let font = answers.entry((name.clone(), version.clone())).or_default().clone();
DocFont { name, version, widths: None, font }
})
.collect();
let main = doc.get("1")?;
@@ -1653,6 +1671,40 @@ fn art_scale(to_doc: Affine) -> f64 {
mod tests {
use super::*;
/// The records of a text document's font list that name one font share the widths the file's
/// page gives it and the face they resolve to, however many there are: 20,000 records of a font
/// whose page gives 4,096 characters hold one copy of those widths, and resolve once. A record
/// of another version is resolved apart.
#[test]
fn records_of_one_font_share_its_page_widths_and_answer() {
let n = 20_000;
let records = "<< /0 << /0 << /0 (Sharetest-Regular) >> >> >> ".repeat(n) + "<< /0 << /0 << /0 (Sharetest-Regular) /5 (2.0) >> >> >>";
let doc = format!("/0 << /1 << /0 [ {records} ] >> /8 << /0 [ ] >> >>\n/1 << /1 [ ] /2 << >> >>\n");
let data =
format!("%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n", crate::ps::ascii85(doc.as_bytes()));
let mut cmap = String::from("begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n16 beginbfrange\n");
for hi in 1..=16u32 {
cmap.push_str(&format!("<{hi:02X}00> <{hi:02X}FF> <{hi:02X}00>\n"));
}
cmap.push_str("endbfrange\nendcmap\n");
let extra = vectorcraft_testkit::pdf::first_extra(1);
let font = format!(
"/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+Sharetest-Regular /Encoding /Identity-H /ToUnicode {extra} 0 R \
/DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+Sharetest-Regular /W [256 4351 500] >>] >> >>"
);
let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") };
let pdf = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None);
let widths = vectorcraft_pdf::open_pdf(&pdf, None).unwrap().page_widths();
let shared = widths.widths("Sharetest-Regular").unwrap();
assert_eq!(shared.len(), 4096);
let texts = Texts::read(data.as_bytes()).unwrap().with_page_widths(&widths);
assert_eq!(texts.fonts.len(), n + 1);
assert!(texts.fonts.iter().all(|f| f.widths.as_ref().is_some_and(|w| Arc::ptr_eq(w, shared))));
let first = &texts.fonts[0].font;
assert!(texts.fonts[..n].iter().all(|f| Arc::ptr_eq(&f.font, first)));
assert!(texts.fonts.last().is_some_and(|f| !Arc::ptr_eq(&f.font, first)), "another version resolves apart");
}
#[test]
fn right_to_left_paragraphs_swap_left_and_right_alignment() {
let texts = Texts {
+17 -8
View File
@@ -178,17 +178,25 @@ impl ReadText {
self.frames.get_or_insert_with(|| ai::text_frames(data))
}
/// The text document of `data` ([`Texts::read`]), if it has one that can be read.
fn texts(&mut self, data: &[u8]) -> Option<&Texts> {
/// The text document of `data` ([`Texts::read`]), if it has one that can be read, with the widths
/// `page_widths` the file's page gives its fonts ([`Texts::with_page_widths`]). They are given
/// when it is first read, before any of its fonts is found: each is found once, with the widths
/// it has then. Every check and build of one open passes the same widths.
fn texts(&mut self, data: &[u8], page_widths: &vectorcraft_pdf::PageWidths) -> Option<&Texts> {
self.forget_in_tests();
self.texts.get_or_insert_with(|| Texts::read(data)).as_ref()
self.texts.get_or_insert_with(|| Texts::read(data).map(|t| t.with_page_widths(page_widths))).as_ref()
}
/// [`Self::texts`] with its characters painted by `paints` ([`Texts::with_paints`]).
fn texts_with(&mut self, data: &[u8], paints: std::collections::HashMap<String, vectorcraft_color::Paint>) -> Option<&Texts> {
fn texts_with(
&mut self,
data: &[u8],
paints: std::collections::HashMap<String, vectorcraft_color::Paint>,
page_widths: &vectorcraft_pdf::PageWidths,
) -> Option<&Texts> {
self.forget_in_tests();
let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_paints(paints));
self.texts.insert(texts).as_ref()
let read = self.texts.take().unwrap_or_else(|| Texts::read(data).map(|t| t.with_page_widths(page_widths)));
self.texts.insert(read.map(|t| t.with_paints(paints))).as_ref()
}
}
@@ -217,7 +225,7 @@ fn type_all_made(structure: &Structure, data: &[u8], text: &mut ReadText) -> boo
for info in &mut infos {
info.art_path = info.story.and_then(|s| frames.get(&(s, info.frame))).map(|p| PathData::from_bezpath(&(structure.to_doc * p.clone())));
}
let Some(texts) = text.texts(data) else { return false };
let Some(texts) = text.texts(data, &structure.page_widths) else { return false };
let mut read: std::collections::BTreeMap<u32, Option<Arc<Story>>> = Default::default();
let stories: Vec<Option<Arc<Story>>> = infos
.iter()
@@ -338,6 +346,7 @@ pub(super) fn build_weighing(
envelopes_drawn,
styles_read,
text_paints,
page_widths,
canvas_scale,
symbols_own_size,
xml_ids,
@@ -498,7 +507,7 @@ pub(super) fn build_weighing(
// The page's type that needs no text object of the layers: the layers' own legacy text, or
// placed files that show it.
let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?;
let texts = text.texts_with(data, text_paints);
let texts = text.texts_with(data, text_paints, &page_widths);
// Each story is read once, however many text objects name it.
let mut read: std::collections::BTreeMap<u32, Option<Arc<Story>>> = Default::default();
let stories: Vec<Option<Arc<Story>>> = infos
+56 -20
View File
@@ -149,7 +149,7 @@ pub fn layered_ai_from(
all.push(format!("{LAYERS_UNREAD} from its editing data ({why}): they come from its PDF part"));
all
};
let AiLayers { data, structure, alone, mut text } = layers;
let AiLayers { data, structure, alone, mut text, page_widths } = layers;
let data = match data {
Ok(data) => data,
Err(why) => return (visible, unread(warnings, &why), false),
@@ -189,10 +189,17 @@ pub fn layered_ai_from(
add_notes(&mut all, read.notes());
(visible, all, false)
};
// The layers read, with the widths the PDF part gives the characters of its fonts.
let read = || {
ai::read_over_page(&data, false, names).map(|mut structure| {
structure.page_widths = page_widths.clone();
structure
})
};
// The envelopes of type the page doesn't hold against layers that don't draw as it, and how many
// envelopes of type the layers had.
let (mut free, mut count) = (None, 0);
let built = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)).and_then(|structure| {
let built = structure.unwrap_or_else(|| read().map(Box::new)).and_then(|structure| {
count = structure.warped_type.envelope_count();
build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text)
});
@@ -205,7 +212,7 @@ pub fn layered_ai_from(
let live = free.is_none() && matches!(&built, Ok((done, _)) if holds_type_envelope(&done.layers));
if !live
&& let Some((mut done, notes)) = alone.and_then(|(pages, unit)| {
let mut structure = ai::read_over_page(&data, false, names).ok()?;
let mut structure = read().ok()?;
// With none free, nothing needs settling again: every envelope keeps its drawn art.
if let Some(free) = free.as_deref().filter(|free| !free.is_empty()) {
structure.warped_type.open_alone(free, count);
@@ -244,9 +251,17 @@ fn holds_type_envelope(nodes: &[Arc<Node>]) -> bool {
/// reading it, when the file's text document makes all of its type and nothing in its layers needs
/// the PDF part (see `build_without_page`). Nothing is compared with the PDF part. Else, as the
/// error, what was decoded and read of the editing copy, for [`layered_ai_from`] once the PDF part
/// is imported. `names`: the encoding of names that aren't UTF-8.
pub fn ai_layers_alone(private: &[u8], pages: &[(f64, f64)], unit: f64, names: ai::NameEncoding) -> Result<(Document, Vec<String>), AiLayers> {
ai_layers_alone_decoded(ai::decode_private(private), pages, unit, names)
/// is imported. `names`: the encoding of names that aren't UTF-8. `page_widths`: the widths the
/// PDF part gives the characters of its fonts, which tell installed copies of a font apart
/// ([`AiLayers::with_page_widths`]).
pub fn ai_layers_alone(
private: &[u8],
pages: &[(f64, f64)],
unit: f64,
names: ai::NameEncoding,
page_widths: vectorcraft_pdf::PageWidths,
) -> Result<(Document, Vec<String>), AiLayers> {
ai_layers_alone_decoded(ai::decode_private(private), pages, unit, names, page_widths)
}
/// [`ai_layers_alone`] of an editing copy already decoded (`decoded`, as [`decode_ai_private`]
@@ -256,31 +271,33 @@ pub fn ai_layers_alone_decoded(
pages: &[(f64, f64)],
unit: f64,
names: ai::NameEncoding,
page_widths: vectorcraft_pdf::PageWidths,
) -> Result<(Document, Vec<String>), AiLayers> {
let data = match decoded {
Ok(data) => data,
Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default() }),
Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default(), page_widths }),
};
if !has_layers(&data) {
return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default() });
return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default(), page_widths });
}
// An image past the hard limits is read as an unread box, which the PDF part's art replaces.
let structure = match ai::read_over_page(&data, false, names) {
let mut structure = match ai::read_over_page(&data, false, names) {
Ok(structure) => structure,
Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default() }),
Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default(), page_widths }),
};
structure.page_widths = page_widths.clone();
let mut text = Box::<ReadText>::default();
// An envelope of type opens live only where the layers with it draw as the page, as the other
// live envelopes do: the PDF part is imported to compare them with. Should none open live, the
// layers open alone as they would have, the envelopes keeping their drawn art ([`layered_ai_from`]).
if structure.warped_type.has_envelopes() && alone_scale(&structure, &data, pages, unit, &mut text).is_some() {
let alone = Some((pages.to_vec(), unit));
return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text });
return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text, page_widths });
}
match build_without_page(structure, &data, pages, unit, &mut text) {
Ok(Ok((doc, notes))) => Ok((doc, notes)),
Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text }),
Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text }),
Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text, page_widths }),
Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text, page_widths }),
}
}
@@ -297,6 +314,8 @@ pub struct AiLayers {
alone: Option<(Vec<(f64, f64)>, f64)>,
/// The text objects' frames and the text document of the editing copy, as far as they were read.
text: Box<ReadText>,
/// The widths the PDF part gives the characters of its fonts ([`Self::with_page_widths`]).
page_widths: vectorcraft_pdf::PageWidths,
}
impl AiLayers {
@@ -308,7 +327,20 @@ impl AiLayers {
/// An editing copy already decoded (`decoded`, as [`decode_ai_private`] gives it, or why it
/// can't be).
pub fn decoded(decoded: Result<Vec<u8>, String>) -> Self {
Self { data: decoded, structure: None, alone: None, text: Box::default() }
Self { data: decoded, structure: None, alone: None, text: Box::default(), page_widths: Default::default() }
}
/// The editing copy with `page_widths`, the widths the file's PDF part gives the characters of
/// its fonts ([`vectorcraft_pdf::Opened::page_widths`]): type whose font record keeps no
/// version is set in the installed copy of its font that sets them at those widths, where
/// several copies answer to its name. The layers read before take them too, and a text document
/// read before is read again with them, since its fonts are found once, with the widths they had
/// then.
pub fn with_page_widths(mut self, page_widths: vectorcraft_pdf::PageWidths) -> Self {
if let Some(Ok(structure)) = &mut self.structure {
structure.page_widths = page_widths.clone();
}
Self { page_widths, text: Box::default(), ..self }
}
}
@@ -610,17 +642,21 @@ fn place_art(layer: &mut Node, pages: &[Rect], moves: &[Vec2]) {
/// Editing data written on a large canvas comes in at its declared scale: no page holds the size.
/// Names that aren't UTF-8 are read as Windows-1252 ([`ai_alone_with`]).
pub fn ai_alone(private: &[u8]) -> Result<(Document, Vec<String>), String> {
ai_alone_with(private, ai::NameEncoding::default())
ai_alone_with(private, ai::NameEncoding::default(), Default::default())
}
/// [`ai_alone`], with the names that aren't UTF-8 read in `names`.
pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding) -> Result<(Document, Vec<String>), String> {
ai_alone_decoded(&ai::decode_private(private)?, names)
/// [`ai_alone`], with the names that aren't UTF-8 read in `names`, and `page_widths`, the widths the
/// file's PDF part gives the characters of its fonts when it has one that holds the art
/// ([`AiLayers::with_page_widths`]).
pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding, page_widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec<String>), String> {
ai_alone_decoded(&ai::decode_private(private)?, names, page_widths)
}
/// [`ai_alone_with`] of an editing copy already decoded (`data`, as [`decode_ai_private`] gives it).
pub fn ai_alone_decoded(data: &[u8], names: ai::NameEncoding) -> Result<(Document, Vec<String>), String> {
build_from(ai::read_in(data, true, names)?, data, None, Page::Artboard, false, false, 1.0)
pub fn ai_alone_decoded(data: &[u8], names: ai::NameEncoding, page_widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec<String>), String> {
let mut structure = ai::read_in(data, true, names)?;
structure.page_widths = page_widths;
build_from(structure, data, None, Page::Artboard, false, false, 1.0)
}
/// [`ai_alone`] for a `.ai` whose PDF part can't be read, its first page `page` (width and height)
+108 -9
View File
@@ -3452,6 +3452,105 @@ fn type_from_the_text_document_takes_the_version_its_font_record_keeps() {
assert_eq!(version("/0 (VertestInk-Regular) /VersionString (1.1)"), "1.1");
}
/// The widths a `.ai`'s PDF part gives the characters of `text` in its font `name` (a subset of
/// it, a TrueType font in `WinAnsiEncoding`): those `width` gives each, in thousandths of an em.
fn page_widths(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths {
let widths: Vec<String> = (32u8..=126).map(char::from).map(|c| if text.contains(c) { width(c).to_string() } else { "0".into() }).collect();
let font = format!(
"/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>",
widths.join(" ")
);
let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") };
vectorcraft_pdf::open_pdf(&vectorcraft_testkit::pdf::pdf_with(&[page], &[], None), None).unwrap().page_widths()
}
/// [`page_widths`] of a composite font (`Identity-H`, a TrueType CIDFont) whose `ToUnicode` map gives
/// CID 1 the first character of `text`, CID 2 the next and so on, `W` their widths.
fn page_widths_cid(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths {
let chars: Vec<char> = text.chars().collect();
let pairs: Vec<String> = chars.iter().enumerate().map(|(i, c)| format!("<{:04X}> <{:04X}>", i + 1, u32::from(*c))).collect();
let cmap = format!(
"begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n{} beginbfchar\n{}\nendbfchar\nendcmap\n",
pairs.len(),
pairs.join("\n")
);
let w: Vec<String> = chars.iter().map(|c| width(*c).to_string()).collect();
let extra = vectorcraft_testkit::pdf::first_extra(1);
let font = format!(
"/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+{name}-Identity-H /Encoding /Identity-H /ToUnicode {extra} 0 R \
/DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+{name} /W [1 [{}]] >>] >> >>",
w.join(" ")
);
let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") };
let file = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None);
vectorcraft_pdf::open_pdf(&file, None).unwrap().page_widths()
}
/// The advance of `c` in installed `face`, in thousandths of an em.
fn advance(face: &vectorcraft_text::FontFace, c: char) -> f64 {
face.advance(face.glyph_for(c)) * 1000.0 / face.units_per_em()
}
/// The version of the face that type from the text document of a `.ai` whose font record is
/// `record` (in place of `/0 (Helvetica)`) is set in, its layers read alone with `widths`, the
/// widths its PDF part gives the characters of its fonts.
fn version_on_page(record: &str, widths: vectorcraft_pdf::PageWidths) -> String {
let doc = text_document(&[("Hamburg\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]).replacen("/0 (Helvetica)", record, 1);
let file = private(&native_with_text(&layer("Art", true, &text_object(0)), &doc));
let names = crate::NameEncoding::default();
let Ok((d, notes)) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, widths) else { panic!("{record}: opened with the page") };
let texts = text_of(&d.layers[0]);
assert_eq!(texts.len(), 1, "{record}: {notes:?}");
vectorcraft_text::FontDb::global().style_face(&texts[0].runs[0].style).unwrap().version.clone()
}
/// Two installed copies of one font can share its PostScript name, family and style, and differ
/// in their glyphs' widths alone. Type from the text document of a `.ai` whose font record keeps no
/// version is set in the copy that sets the characters its PDF part draws at the widths the PDF
/// part gives them, also when the record spells the name with other punctuation. Without those
/// widths, or when no copy sets the characters at them, it takes the copy it took before (the first
/// loaded); a version the record keeps decides first. The widths of a simple font in
/// `WinAnsiEncoding` and of a composite font with a `ToUnicode` map both tell the copies apart.
#[test]
fn type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths() {
install(&[(true, ("Widtest Ink", "Regular", "1.0", "WidtestInk-Regular")), (false, ("Widtest Ink", "Regular", "1.1", "WidtestInk-Regular"))]);
let copies = vectorcraft_text::FontDb::global().postscript_faces("WidtestInk-Regular");
let copy = |version: &str| copies.iter().find(|f| f.version == version).unwrap().clone();
let (old, new) = (copy("1.0"), copy("1.1"));
assert!((advance(&old, 'H') - advance(&new, 'H')).abs() > 10.0, "the copies set the type at other widths");
let on = |name: &str, face: &vectorcraft_text::FontFace| page_widths(name, "Hamburg", |c| advance(face, c));
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", Default::default()), "1.0");
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &new)), "1.1");
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &old)), "1.0");
// Widths a file rounds are within 1/1000 em of the advances; farther off, they aren't the copy's.
let off = |by: f64| page_widths("WidtestInk-Regular", "Hamburg", |c| advance(&new, c) + by);
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(0.9)), "1.1");
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(-0.9)), "1.1");
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(2.0)), "1.0");
// A record whose name differs from the copies' in punctuation alone, as its PDF part's font.
assert_eq!(version_on_page("/0 (Widtest-Ink-Regular)", on("Widtest-Ink-Regular", &new)), "1.1");
// Widths of another font, or no copy setting the characters at the PDF part's widths.
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("OtherInk-Regular", &new)), "1.0");
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths("WidtestInk-Regular", "Hamburg", |_| 1000.0)), "1.0");
// A version the record keeps picks the copy, and one that isn't installed gives the copy it gave.
assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (1.0)", on("WidtestInk-Regular", &new)), "1.0");
assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (9.9)", on("WidtestInk-Regular", &new)), "1.0");
// The widths of a composite font.
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&new, c))), "1.1");
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&old, c))), "1.0");
// A font installed once is set in that copy whatever the widths.
install(&[(true, ("Onewtest Ink", "Regular", "1.0", "OnewtestInk-Regular"))]);
assert_eq!(version_on_page("/0 (OnewtestInk-Regular)", on("OnewtestInk-Regular", &new)), "1.0");
// Of several copies that set the characters at the widths, the first in the order the faces
// are found (the first loaded).
install(&[
(true, ("Firstwtest Ink", "Regular", "1.0", "FirstwtestInk-Regular")),
(false, ("Firstwtest Ink", "Regular", "1.1", "FirstwtestInk-Regular")),
(false, ("Firstwtest Ink", "Regular", "1.2", "FirstwtestInk-Regular")),
]);
assert_eq!(version_on_page("/0 (FirstwtestInk-Regular)", on("FirstwtestInk-Regular", &new)), "1.1");
}
/// A story with no runs, and a run or paragraph that names no style, is set in `[Normal Character
/// Style]` and `[Normal Paragraph Style]` before the text document's base attributes. A Large
/// Canvas copy (1:10) writes the styles at the art's scale (1.2 for 12 points, 0.6 for a 6-point
@@ -6490,7 +6589,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() {
let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn));
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
let names = crate::NameEncoding::default();
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
// A PDF part the layers don't draw as.
let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, false, 1.0, names);
assert!(read, "{notes:?}");
@@ -6499,7 +6598,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() {
assert_eq!(loose, [("Note".to_string(), true), ("FLUX".to_string(), false)], "{notes:?}");
assert!(notes.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{notes:?}");
// A PDF part that draws as those layers, with the drawn art: the envelope opens live.
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
let (d, notes, read) = crate::layered_ai_from(layers, d, vec![], false, false, 1.0, names);
assert!(read, "{notes:?}");
let (envelopes, loose) = envelopes_and_type(&d);
@@ -6527,7 +6626,7 @@ fn layers_that_open_alone_read_their_text_once() {
let doc = unsplit_text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Mid\r", 2, (8191.5, 8191.5), (0.0, 0.0), -10.0)]);
let art = layer("Art", true, &format!("{}\n{}{}", square(10, 10), text_object(0), text_object(1)));
let file = private(&native_with_text(&art, &doc));
let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default()).ok();
let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default(), Default::default()).ok();
let (opened, texts, frames) = text_reads(false, open);
let Some((d, notes)) = opened else { panic!("didn't open without the page") };
assert_eq!((texts, frames), (1, 1), "{notes:?}");
@@ -6546,7 +6645,7 @@ fn layers_whose_text_document_cannot_be_read_read_it_once_with_the_page() {
let file = private(&native_with_text(&art, "not a text document"));
let names = crate::NameEncoding::default();
let open = || {
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
crate::layered_ai_from(layers, pdf_part(10.0, 86.0), vec![], false, false, 1.0, names)
};
let (opened, texts, frames) = text_reads(false, open);
@@ -6573,7 +6672,7 @@ fn an_envelope_of_type_waiting_on_the_page_reads_the_text_once() {
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
let names = crate::NameEncoding::default();
let open = |page: Document| {
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names)
};
// A PDF part the layers don't draw as: they open alone, after a build with the page and one without.
@@ -6657,7 +6756,7 @@ fn trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_dr
let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn));
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
let names = crate::NameEncoding::default();
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, true, 1.0, names);
assert!(read, "{notes:?}");
let (envelopes, loose) = envelopes_and_type(&d);
@@ -6751,7 +6850,7 @@ fn layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_di
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
let names = crate::NameEncoding::default();
let open = |page: Document| {
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names)
};
// The layers alone, with the envelope's drawn art: what the page draws.
@@ -6794,7 +6893,7 @@ fn trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
let names = crate::NameEncoding::default();
let open = |page: Document, trust: bool| {
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
crate::layered_ai_from(layers, page, vec![], false, trust, 1.0, names)
};
let (mut page, _, _) = open(pdf_part(80.0, 80.0), false);
@@ -6833,7 +6932,7 @@ fn layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_do
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
let names = crate::NameEncoding::default();
let open = |page: Document| {
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names)
};
// The layers alone, with the drawn art of both envelopes, but the first's: the page draws
+51 -18
View File
@@ -44,7 +44,7 @@ fn style_word(w: &str) -> String {
/// A font's PostScript name without a subset prefix (`ABCDEF+`) or the `*1` of a re-encoded copy
/// (`ABCDEF+RollerBabyBV*1` is `RollerBabyBV`).
fn bare_name(name: &str) -> &str {
pub(super) fn bare_name(name: &str) -> &str {
let name = match name.split_once('+') {
Some((prefix, rest)) if prefix.len() == 6 && prefix.bytes().all(|b| b.is_ascii_uppercase()) => rest,
_ => name,
@@ -56,14 +56,15 @@ fn bare_name(name: &str) -> &str {
}
/// The font of type that a text document's font record names: by `name`, its PostScript name, and
/// `version`, the version string (name ID 5) the record keeps, if any. An installed face of that
/// name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`]) and the
/// family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is
/// `version`, the version string (name ID 5) the record keeps, if any; `widths`, the widths the
/// file's page gives the font's characters, if it has them ([`postscript_face`]). An installed face
/// of that name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`])
/// and the family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is
/// Microsoft YaHei). → (family, style, version).
///
/// [`FontDb::find_family`]: vectorcraft_text::FontDb::find_family
pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, String, Option<String>) {
named_font(name, version).unwrap_or_else(|| {
pub(crate) fn document_font(name: &str, version: Option<&str>, widths: Option<&vectorcraft_pdf::FontWidths>) -> (String, String, Option<String>) {
named_font(name, version, widths).unwrap_or_else(|| {
let (family, style) = family_style(name);
let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family);
(family, style, None)
@@ -71,37 +72,69 @@ pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, Strin
}
/// The font of type set in the installed face of PostScript name `name` (a subset prefix and a
/// re-encoded copy's `*1` aside) in `version` ([`postscript_face`]): that face's own family and
/// style, and its version when the family and style alone resolve to another installed copy of
/// the font. A library can keep two copies under one family and style that differ in their
/// PostScript names or their versions, and draw the same text at different widths. → (family,
/// style, version); `None` when no installed face has the name.
pub(crate) fn named_font(name: &str, version: Option<&str>) -> Option<(String, String, Option<String>)> {
let face = postscript_face(bare_name(name), version)?;
/// re-encoded copy's `*1` aside) in `version`, or that sets the characters at `widths`
/// ([`postscript_face`]): that face's own family and style, and its version when the family and
/// style alone resolve to another installed copy of the font. A library can keep two copies under
/// one family and style that differ in their PostScript names or their versions, and draw the same
/// text at different widths. → (family, style, version); `None` when no installed face has the name.
pub(crate) fn named_font(
name: &str,
version: Option<&str>,
widths: Option<&vectorcraft_pdf::FontWidths>,
) -> Option<(String, String, Option<String>)> {
let face = postscript_face(bare_name(name), version, widths)?;
// As the PDF import names a version: only one that the family and style don't resolve to.
let default = vectorcraft_text::FontDb::global().face(&face.family, &face.style);
let version = default.filter(|d| d.version != face.version).map(|_| face.version.clone());
Some((face.family.clone(), face.style.clone(), version))
}
/// How far an installed face's advance may be from the width a page gives a character, in
/// thousandths of an em, for the face to set it at that width: files write widths rounded.
const PAGE_WIDTH_SLACK: f64 = 1.0;
/// The most characters of a page's font [`sets_page_widths`] compares.
const MAX_WIDTHS_COMPARED: usize = 512;
/// Does installed `face` set the characters of `widths` (a page's, [`vectorcraft_pdf::FontWidths`])
/// at their widths, each within [`PAGE_WIDTH_SLACK`]? The first [`MAX_WIDTHS_COMPARED`] characters
/// in code-point order are compared; a character the face has no glyph for isn't set at its width.
fn sets_page_widths(face: &vectorcraft_text::FontFace, widths: &vectorcraft_pdf::FontWidths) -> bool {
let k = 1000.0 / face.units_per_em();
widths.iter().take(MAX_WIDTHS_COMPARED).all(|(c, w)| {
let gid = face.glyph_for(*c);
gid != 0 && (face.advance(gid) * k - f64::from(*w)).abs() <= PAGE_WIDTH_SLACK
})
}
/// The installed face of PostScript name `name` (without a subset prefix), among the installed
/// faces that answer to it ([`FontDb::postscript_faces`]): those of exactly that name when there
/// are any (PostScript names are case-sensitive, so `SampleSans` isn't the face named
/// `SAMPLESANS`, and `SampleSerif-Bold` isn't `SampleSerifBold`), and of those the one in
/// `version` when it is installed, else the first. `None` when no installed face has the name.
/// `version` when it is installed. Without a version, copies whose names, family and style are all
/// one can still set the type at other widths: of those, the first that sets the characters of
/// `widths` (the file's page's, when it has them) at their widths ([`sets_page_widths`], which
/// compares the first 512 characters). Else the first. `None` when no installed face has the name.
///
/// [`FontDb::postscript_faces`]: vectorcraft_text::FontDb::postscript_faces
pub(crate) fn postscript_face(name: &str, version: Option<&str>) -> Option<Arc<vectorcraft_text::FontFace>> {
pub(crate) fn postscript_face(
name: &str,
version: Option<&str>,
widths: Option<&vectorcraft_pdf::FontWidths>,
) -> Option<Arc<vectorcraft_text::FontFace>> {
let db = vectorcraft_text::FontDb::global();
let found = db.find_postscript(name)?;
if found.postscript_name() == name && version.is_none_or(|v| v == found.version) {
let widths = widths.filter(|_| version.is_none());
let on_page = |f: &vectorcraft_text::FontFace| widths.is_none_or(|w| sets_page_widths(f, w));
if found.postscript_name() == name && version.is_none_or(|v| v == found.version) && on_page(&found) {
return Some(found);
}
let faces = db.postscript_faces(name);
let named: Vec<_> = faces.iter().filter(|f| f.postscript_name() == name).cloned().collect();
let pool = if named.is_empty() { faces } else { named };
let in_version = version.and_then(|v| pool.iter().find(|f| f.version == v).cloned());
Some(in_version.or_else(|| pool.into_iter().next()).unwrap_or(found))
let by_widths = || pool.iter().find(|f| on_page(f)).cloned();
Some(in_version.or_else(by_widths).or_else(|| pool.into_iter().next()).unwrap_or(found))
}
/// A font's family and style from its PostScript name, without a subset prefix (`ABCDEF+`) or the
@@ -620,7 +653,7 @@ impl Interp<'_> {
}
// The installed face of that PostScript name, as type from a text document takes it; else
// the available family's own spelling: `MicrosoftYaHei` is Microsoft YaHei, not "Microsoft Ya Hei".
let (font_family, font_style, font_version) = document_font(&name, None);
let (font_family, font_style, font_version) = document_font(&name, None, None);
let fill = if self.g.paint.is_none() { Paint::solid(vectorcraft_color::Color::BLACK) } else { self.g.paint.clone() };
let style = CharStyle { font_family, font_style, font_version, size, fill, stroke: Paint::None, ..CharStyle::default() };
let mut t = TextObject::point(Point::ZERO, text, style);
+62 -64
View File
@@ -15,12 +15,13 @@
//! every buffer's bytes are checked against the heap before they are allocated. Every element
//! a method visits takes a unit of fuel, and a sort's comparisons take one each.
//!
//! The language has no iterators yet, so constructing from an object reads an array or an object
//! with a `length`, by index, and `%TypedArray%.from` reads those or a string, by code point. A
//! constructor given a primitive string reads it as a length.
//! Constructing from an object that is not a buffer or a typed array, and `%TypedArray%.from`,
//! read a source with an `@@iterator` method through its iterator (a string by code point), and
//! any other source as an array-like object, by index. `%TypedArray%.prototype[@@iterator]` is
//! `values`. A constructor given a primitive string reads it as a length.
use super::collections::{for_each_item, getter, length_of, new_iter, new_proto};
use super::{arg, array, data, method, native, require_callable, to_integer};
use super::collections::{getter, length_of, new_iter, new_proto};
use super::{arg, array, data, method, native, new_array, require_callable, to_integer};
use crate::heap::{Class, Elem, HIDDEN, IterKind, IterSource, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, VIEW_BYTES, View, key};
use crate::interp::{Abrupt, Desc, ErrorType, Interp, JsResult};
use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint32};
@@ -28,9 +29,6 @@ use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint3
/// The longest buffer, in bytes.
const MAX_BUFFER: u64 = u32::MAX as u64;
/// The bytes each item a method gathers before it writes them is charged.
const ITEM_BYTES: usize = 16;
pub(super) fn install(interp: &mut Interp) -> JsResult<()> {
install_array_buffer(interp)?;
install_data_view(interp)?;
@@ -124,6 +122,11 @@ fn install_typed_arrays(interp: &mut Interp) -> JsResult<()> {
for (name, f, length) in methods {
method(interp, proto, name, f, length)?;
}
// `%TypedArray%.prototype[@@iterator]` is `values` (section 22.2.3.30).
if let Some(iterator) = interp.well_known(|w| &w.iterator) {
let values = interp.get_from(proto, &key("values"), &Value::Object(proto))?;
interp.define_sym(proto, iterator, crate::heap::Prop::Data { value: values, flags: HIDDEN })?;
}
// `%TypedArray%.prototype.toString` is `Array.prototype.toString` (section 22.2.3.28).
let array_proto = interp.intrinsics.array_proto;
let to_string = interp.get_from(array_proto, &key("toString"), &Value::Object(array_proto))?;
@@ -645,21 +648,59 @@ fn typed_ctor(interp: &mut Interp, args: &[Value], constructing: bool, elem: Ele
}
return Ok(Value::Object(ta));
}
let len = length_of(interp, o)?;
let ta = new_typed(interp, elem, len)?;
interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, &first, len))?;
Ok(Value::Object(ta))
// Any other object is read as TypedArrayFrom reads it (section 22.2.1.4).
typed_array_from(interp, &first, None, |interp, len| new_typed(interp, elem, len))
}
/// Writes the elements `0` to `len - 1` of the array-like object `src` to the typed array `ta`,
/// each converted with ToNumber.
fn fill_from(interp: &mut Interp, ta: ObjId, src: &Value, len: u64) -> JsResult<()> {
let Value::Object(o) = src else { return Ok(()) };
/// TypedArrayFrom (section 22.2.2.1.1): a typed array with the values of `items`, made by `make`
/// once their number is known, each value mapped with `map` (the function and its `this`) when
/// one is given and converted with ToNumber. An `items` with an `@@iterator` method is read
/// through its iterator to the end before the typed array is made. Any other value is read as
/// an array-like object, each element read, mapped and written before the next is read.
fn typed_array_from(
interp: &mut Interp,
items: &Value,
map: Option<(&Value, &Value)>,
make: impl FnOnce(&mut Interp, u64) -> JsResult<ObjId>,
) -> JsResult<Value> {
let using_iterator = match interp.well_known(|w| &w.iterator) {
Some(iterator) => interp.get_value_sym(items, &iterator)?,
None => Value::Undefined,
};
let src = if using_iterator.is_nullish() {
interp.to_object(items)?
} else {
let rec = interp.get_iterator_with(items, &using_iterator)?;
interp.rooted(&[Value::Object(rec)], |interp| {
let list = new_array(interp, 0)?;
interp.rooted(&[Value::Object(list)], |interp| interp.append_values(rec, list))?;
Ok(list)
})?
};
let src_value = Value::Object(src);
interp.rooted(std::slice::from_ref(&src_value), |interp| {
let len = length_of(interp, src)?;
let ta = make(interp, len)?;
interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, src, len, map))?;
Ok(Value::Object(ta))
})
}
/// Writes the elements `0` to `len - 1` of the object `src` to the typed array `ta`, each mapped
/// with `map` when one is given and converted with ToNumber. Each element is read just before it
/// is mapped and written.
fn fill_from(interp: &mut Interp, ta: ObjId, src: ObjId, len: u64, map: Option<(&Value, &Value)>) -> JsResult<()> {
let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?;
let src_value = Value::Object(src);
for i in 0..len {
interp.use_fuel()?;
#[allow(clippy::cast_precision_loss)]
let v = interp.get_from(*o, &super::key_of(i as f64), src)?;
let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?;
#[allow(clippy::cast_precision_loss)]
let v = match map {
Some((f, this_arg)) => interp.call(f, this_arg, &[item, Value::Number(i as f64)])?,
None => item,
};
let n = interp.to_number(&v)?;
write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n);
}
@@ -741,54 +782,11 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe
require_callable(interp, &map_fn, "the map function")?;
}
let this_arg = arg(args, 2);
let source = arg(args, 0);
if !matches!(source, Value::String(_)) {
// An array-like source: each element is read, mapped and written before the next is read.
let src = interp.to_object(&source)?;
let src_value = Value::Object(src);
let len = length_of(interp, src)?;
let map = mapping.then_some((&map_fn, &this_arg));
typed_array_from(interp, &arg(args, 0), map, |interp, len| {
let elem = ctor_elem(interp, &this, "from")?;
let ta = interp.rooted(std::slice::from_ref(&src_value), |interp| new_typed(interp, elem, len))?;
let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?;
return interp.rooted(&[Value::Object(ta), src_value.clone()], |interp| {
for i in 0..len {
interp.use_fuel()?;
#[allow(clippy::cast_precision_loss)]
let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?;
#[allow(clippy::cast_precision_loss)]
let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item };
let n = interp.to_number(&v)?;
write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n);
}
Ok(Value::Object(ta))
});
}
// A string is read by code point first, as an iterable source is, and then mapped.
let mark = interp.temp_roots.len();
let mut held = crate::interp::HeldBytes::new(interp);
let gathered = for_each_item(interp, &source, false, |interp, item| {
held.add(interp, ITEM_BYTES)?;
interp.temp_roots.push(item);
Ok(())
});
let result = gathered.and_then(|()| {
let items: Vec<Value> = interp.temp_roots.get(mark..).map(<[Value]>::to_vec).unwrap_or_default();
let elem = ctor_elem(interp, &this, "from")?;
let ta = new_typed(interp, elem, items.len() as u64)?;
interp.temp_roots.push(Value::Object(ta));
let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?;
for (i, item) in items.into_iter().enumerate() {
interp.use_fuel()?;
#[allow(clippy::cast_precision_loss)]
let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item };
let n = interp.to_number(&v)?;
write(interp, &view, i, n);
}
Ok(Value::Object(ta))
});
interp.temp_roots.truncate(mark);
drop(held);
result
new_typed(interp, elem, len)
})
}
/// `%TypedArray%.of(...items)` (section 22.2.2.2).
+26 -58
View File
@@ -8,18 +8,20 @@
//! entries hold their key weakly: the collector removes an entry once its key is reachable only
//! through it ([`crate::heap::Heap::collect`]), and they have no size and cannot be listed.
//!
//! The language has no iterators yet, so the constructors read their argument by index: an
//! array or an object with a `length`, or a string by code point. Every entry added is checked
//! against the heap limit before it is added, and every entry visited takes a unit of fuel.
//! The constructors read their argument through its `@@iterator` method (GetIterator, section
//! 7.4.1), and close the iterator when adding an entry throws (IteratorClose, section 7.4.6).
//! `Map.prototype[@@iterator]` is `entries`, `Set.prototype[@@iterator]` is `values`, and the
//! iterators inherit from `%IteratorPrototype%`. Every entry added is checked against the heap
//! limit before it is added, and every entry visited takes a unit of fuel.
use super::{arg, constructor, create_at, key_of, method, native, new_array, require_callable};
use super::{arg, constructor, create_at, method, native, new_array, require_callable};
use crate::heap::{
COLL_ENTRY_BYTES, CONFIGURABLE, Class, Coll, CollKey, IterKind, IterSource, IterState, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object,
PROP_BYTES, Prop, VIEW_BYTES, WEAK_ENTRY_BYTES, WeakColl, key, string_bytes,
};
use crate::interp::{Abrupt, Interp, JsResult};
use crate::string_builtins::flat_charged;
use crate::value::{Str, Value};
use crate::value::Value;
/// The ECMAScript 2015 intrinsics the built-ins make their objects with, whatever a script does
/// to the globals.
@@ -137,7 +139,14 @@ pub(super) fn install(interp: &mut Interp) -> JsResult<()> {
getter(interp, set_proto, "get size", set_size)?;
// `Set.prototype.keys` is the same function object as `values` (section 23.2.3.8).
let values = interp.get_from(set_proto, &key("values"), &Value::Object(set_proto))?;
interp.define(set_proto, key("keys"), Prop::Data { value: values, flags: crate::heap::HIDDEN })?;
interp.define(set_proto, key("keys"), Prop::Data { value: values.clone(), flags: crate::heap::HIDDEN })?;
// `Map.prototype[@@iterator]` is `entries` and `Set.prototype[@@iterator]` is `values`
// (sections 23.1.3.12 and 23.2.3.11).
if let Some(iterator) = interp.well_known(|w| &w.iterator) {
let entries = interp.get_from(map_proto, &key("entries"), &Value::Object(map_proto))?;
interp.define_sym(map_proto, iterator.clone(), Prop::Data { value: entries, flags: crate::heap::HIDDEN })?;
interp.define_sym(set_proto, iterator, Prop::Data { value: values, flags: crate::heap::HIDDEN })?;
}
let weak_map_proto = new_proto(interp, object_proto);
interp.intrinsics.es2015.weak_map_proto = weak_map_proto;
@@ -158,8 +167,12 @@ pub(super) fn install(interp: &mut Interp) -> JsResult<()> {
method(interp, weak_set_proto, name, f, length)?;
}
// The iterators' prototypes inherit from `%IteratorPrototype%` (sections 23.1.5.2, 23.2.5.2
// and 22.1.5.2), whose `@@iterator` gives the iterator itself.
let iterator_proto =
interp.symbols.objects.and_then(|o| interp.heap.object(o.array_iterator_proto).and_then(|p| p.proto)).unwrap_or(object_proto);
for source in [IterSource::Map, IterSource::Set, IterSource::Array] {
let proto = new_proto(interp, object_proto);
let proto = new_proto(interp, iterator_proto);
let next: NativeFn = match source {
IterSource::Map => map_iterator_next,
IterSource::Set => set_iterator_next,
@@ -209,56 +222,10 @@ pub(crate) fn length_of(interp: &mut Interp, o: ObjId) -> JsResult<u64> {
Ok(if n <= 0.0 { 0 } else { n.min(9_007_199_254_740_991.0) as u64 })
}
/// Calls `f` with each item of `list`, read by index: an object's elements up to its `length`,
/// or a string's code points. Any other value is a `TypeError`, and so is an object without a
/// `length` when `need_length` is true. Each item takes a unit of fuel.
pub(crate) fn for_each_item(
interp: &mut Interp,
list: &Value,
need_length: bool,
mut f: impl FnMut(&mut Interp, Value) -> JsResult<()>,
) -> JsResult<()> {
match list {
Value::Object(o) => {
if need_length && !interp.has_property(*o, &key("length"))? {
return Err(interp.type_error("the value is not an array, a string or an object with a length"));
}
let len = length_of(interp, *o)?;
let mut i = 0u64;
while i < len {
interp.use_fuel()?;
#[allow(clippy::cast_precision_loss)]
let item = interp.get_from(*o, &key_of(i as f64), list)?;
f(interp, item)?;
i += 1;
}
Ok(())
}
Value::String(s) => {
let units = flat_charged(interp, s)?;
let mut i = 0;
while i < units.len() {
interp.use_fuel()?;
let width = match (units.get(i), units.get(i + 1)) {
(Some(hi), Some(lo)) if (0xD800..0xDC00).contains(hi) && (0xDC00..0xE000).contains(lo) => 2,
_ => 1,
};
let piece = units.get(i..i + width).unwrap_or_default().to_vec();
let bytes = string_bytes(piece.len());
interp.reserve_heap(bytes)?;
interp.heap.bytes = interp.heap.bytes.saturating_add(bytes);
f(interp, Value::String(Str::from_units(piece)))?;
i += width;
}
Ok(())
}
_ => Err(interp.type_error("the value is not an array, a string or an object with a length")),
}
}
/// Adds the items of `list` to the new collection `target` with its `adder` method, as the
/// constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs` reads each item
/// as a `[key, value]` entry.
/// Adds the values the iterator of `list` gives to the new collection `target` with its `adder`
/// method, as the constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs`
/// reads each value as a `[key, value]` entry, which must be an object. When reading an entry
/// or adding it throws, the iterator is closed.
fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bool) -> JsResult<()> {
if list.is_nullish() {
return Ok(());
@@ -268,7 +235,8 @@ fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bo
let add = interp.get_from(target, &key(adder), &this)?;
require_callable(interp, &add, adder)?;
interp.rooted(std::slice::from_ref(&add), |interp| {
for_each_item(interp, list, true, |interp, item| {
let rec = interp.get_iterator(list)?;
interp.for_each_value(rec, |interp, item| {
if !pairs {
return interp.call(&add, &this, &[item]).map(drop);
}
+88 -4
View File
@@ -131,10 +131,11 @@ fn iterators_step_through_live_entries() {
}
#[test]
fn constructors_read_arrays_strings_and_array_likes() {
fn constructors_read_arrays_and_strings() {
truth("var m = new Map([[1, 'a'], [2, 'b']]); m.size === 2 && m.get(2) === 'b'");
truth("new Set('ab\u{1F600}b').size === 3");
truth("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'}).size === 2");
// An object without `@@iterator` is not iterable, whatever its `length` (section 23.2.1.1).
throws("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'})", "TypeError");
truth("new Map(null).size === 0 && new Set(undefined).size === 0");
truth("Object.prototype.toString.call(new Set()) === '[object Set]' && Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]'");
throws("Map()", "TypeError");
@@ -146,7 +147,8 @@ fn constructors_read_arrays_strings_and_array_likes() {
truth("Uint8Array.from({}).length === 0 && new Uint8Array({}).length === 0 && DataView.length === 1 && Uint8Array.length === 3");
// `from` reads each element of an array-like source just before mapping it (section 22.2.2.1).
truth("var src = {length: 2, 0: 1, 1: 1}; Uint8Array.from(src, function (v, i) { src[1] = 7; return v; }).join() === '1,7'");
truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,14'");
// An iterable source is read to the end before the first value is mapped (section 22.2.2.1.1).
truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,2'");
truth("Uint8Array.from('ab', function (v) { return v.charCodeAt(0); }).join() === '97,98'");
throws("Map.prototype.get.call({}, 1)", "TypeError");
throws("Object.getOwnPropertyDescriptor(Map.prototype, 'size').get.call(new Set())", "TypeError");
@@ -158,6 +160,86 @@ fn constructors_read_arrays_strings_and_array_likes() {
truth("JSON.stringify(new Map([[1, 2]])) === '{}' && JSON.stringify(new Set([1])) === '{}'");
}
/// An iterable that gives `values` and counts the calls of its `return` method in `closed`.
const CLOSING: &str = "var closed = 0; function closing(values) { var i = 0; return { [Symbol.iterator]: function () { return this; }, \
next: function () { return i < values.length ? { value: values[i++], done: false } : { done: true }; }, \
return: function () { closed++; return {}; } }; }";
#[test]
fn constructors_read_their_argument_through_its_iterator() {
// GetIterator and IteratorStep (sections 23.1.1.1, 23.2.1.1, 23.3.1.1, 23.4.1.1 and 22.2.1.4).
truth("function* g() { yield 1; yield 2; yield 1; } var s = new Set(g()); s.size === 2 && s.has(2)");
truth("function* g() { yield ['a', 1]; yield ['b', 2]; } new Map(g()).get('b') === 2");
truth("function* g() { yield 3; yield 4; } new Uint8Array(g()).join() === '3,4' && Int16Array.from(g()).join() === '3,4'");
truth(&format!("{CLOSING} var s = new Set(closing(['x', 'y'])); s.size === 2 && s.has('y') && closed === 0"));
truth(&format!(
"{CLOSING} var k = {{}}; var w = new WeakMap(closing([[k, 5]])); var ws = new WeakSet(closing([k])); w.get(k) === 5 && ws.has(k)"
));
truth(&format!("{CLOSING} new Float64Array(closing([1.5, 2])).join() === '1.5,2' && closed === 0"));
// A string is read by code point, as its iterator reads it.
truth("new Set('\\uD83D\\uDE00\\uD83D\\uDE00').size === 1 && new Set('\\uD83D\\uDE00x').has('\\uD83D\\uDE00')");
truth("var m = new Map([[1, 'a']]); Array.prototype.join.call(Uint8Array.from(m.keys())) === '1'");
// An array is read through its `@@iterator`, not by index.
truth("var a = [1, 2]; a[Symbol.iterator] = function () { return [9][Symbol.iterator](); }; var s = new Set(a); s.has(9) && !s.has(1)");
truth("var a = [1, 2]; a[Symbol.iterator] = function () { return [9][Symbol.iterator](); }; new Uint8Array(a).join() === '9'");
// An object without `@@iterator` is still read by index by the typed array constructors.
truth("new Uint8Array({length: 2, 0: 1, 1: 2}).join() === '1,2'");
throws("new Set({ [Symbol.iterator]: 1 })", "TypeError");
throws("new Uint8Array({ [Symbol.iterator]: 1 })", "TypeError");
}
#[test]
fn collections_and_typed_arrays_are_iterable() {
// Sections 23.1.3.12, 23.2.3.11 and 22.2.3.30.
truth("Map.prototype[Symbol.iterator] === Map.prototype.entries && Set.prototype[Symbol.iterator] === Set.prototype.values");
truth("var p = Object.getPrototypeOf(Int8Array.prototype); p[Symbol.iterator] === p.values");
truth("var m = new Map([[1, 'a'], [2, 'b']]); var out = []; for (var e of m) out.push(e.join(':')); out.join() === '1:a,2:b'");
truth("var out = []; for (var v of new Set([3, 4])) out.push(v); for (var v of new Int8Array([5])) out.push(v); out.join() === '3,4,5'");
truth("var m = new Map([[1, 2]]); new Map(m).get(1) === 2 && new Set(new Set([7])).has(7) && new Set(new Uint8Array([8])).has(8)");
// The iterators inherit `%IteratorPrototype%[@@iterator]` (sections 23.1.5.2, 23.2.5.2 and 22.1.5.2).
truth("var it = new Map().keys(); it[Symbol.iterator]() === it && new Set([1]).values()[Symbol.iterator]().next().value === 1");
truth("var it = new Int8Array([6]).values(); it[Symbol.iterator]() === it && [...new Set([1, 2]).keys()].join() === '1,2'");
}
#[test]
fn a_map_entry_that_is_not_an_object_closes_the_iterator() {
// Section 23.1.1.1, step 10.d.
truth(&format!("{CLOSING} var caught; try {{ new Map(closing([1])); }} catch (e) {{ caught = e instanceof TypeError; }} caught && closed === 1"));
truth(&format!(
"{CLOSING} var caught; try {{ new WeakMap(closing(['k'])); }} catch (e) {{ caught = e instanceof TypeError; }} caught && closed === 1"
));
}
#[test]
fn an_iterator_whose_next_throws_is_not_closed() {
let src = "var closed = 0; var it = { [Symbol.iterator]: function () { return this; }, \
next: function () { throw new RangeError('next'); }, return: function () { closed++; return {}; } };";
for make in ["new Set(it)", "new Map(it)", "new WeakSet(it)", "new Uint8Array(it)", "Uint8Array.from(it)"] {
truth(&format!(
"{src} var caught; try {{ {make}; }} catch (e) {{ caught = e instanceof RangeError && e.message === 'next'; }} caught && closed === 0"
));
}
}
#[test]
fn a_throwing_adder_closes_the_iterator() {
// IteratorClose (section 7.4.6) keeps the adder's exception, even when `return` throws too.
for (ctor, adder) in [("Set", "add"), ("Map", "set"), ("WeakSet", "add"), ("WeakMap", "set")] {
let src = format!(
"{CLOSING} var o = {{}}; {ctor}.prototype.{adder} = function () {{ throw new RangeError('adder'); }}; var caught; \
try {{ new {ctor}(closing([[o, 1], [o, 2]])); }} catch (e) {{ caught = e instanceof RangeError && e.message === 'adder'; }}"
);
truth(&format!("{src} caught && closed === 1"));
let throwing = src.replace("closed++; return {};", "closed++; throw new TypeError('return');");
truth(&format!("{throwing} caught && closed === 1"));
}
// A Map entry whose `0` getter throws closes the iterator as well.
truth(&format!(
"{CLOSING} var bad = {{ get 0() {{ throw new RangeError('key'); }} }}; var caught; \
try {{ new Map(closing([bad])); }} catch (e) {{ caught = e.message === 'key'; }} caught && closed === 1"
));
}
// ---- WeakMap and WeakSet ----
#[test]
@@ -220,7 +302,9 @@ fn collections_of_millions_end_at_the_limits() {
assert_eq!(limit(&heap, "var m = new Map(); for (var i = 0; ; i++) m.set(i, i);"), LimitKind::Heap);
assert_eq!(limit(&heap, "var s = new Set(); for (var i = 0; ; i++) s.add('k' + i);"), LimitKind::Heap);
let fuel = Limits { fuel: 100_000, ..Limits::default() };
assert_eq!(limit(&fuel, "new Set({length: 1e15})"), LimitKind::Fuel);
let endless = "{ [Symbol.iterator]: function () { return { next: function () { return { value: 1, done: false }; } }; } }";
assert_eq!(limit(&fuel, &format!("new Set({endless})")), LimitKind::Fuel);
assert_eq!(limit(&fuel, &format!("new Uint8Array({endless})")), LimitKind::Fuel);
let m = "var m = new Map(); for (var i = 0; i < 1000; i++) m.set(i, i); m.forEach(function () { for (;;) {} });";
assert_eq!(limit(&fuel, m), LimitKind::Fuel);
}
+45 -4
View File
@@ -59,7 +59,12 @@ impl Interp {
Some(_) => Value::Undefined,
None => return self.walk_record(v),
};
if !self.is_callable(&method) {
self.get_iterator_with(v, &method)
}
/// GetIterator (section 7.4.1) with `method`, the `@@iterator` method already read from `v`.
pub(crate) fn get_iterator_with(&mut self, v: &Value, method: &Value) -> JsResult<ObjId> {
if !self.is_callable(method) {
let what = match v {
Value::Undefined => "undefined",
Value::Null => "null",
@@ -67,7 +72,7 @@ impl Interp {
};
return Err(self.type_error(&format!("{what} is not iterable")));
}
let iterator = self.call(&method, v, &[])?;
let iterator = self.call(method, v, &[])?;
if !matches!(iterator, Value::Object(_)) {
return Err(self.type_error("the iterator is not an object"));
}
@@ -187,6 +192,41 @@ impl Interp {
})
}
/// Calls `f` with each value the iterator of `rec` gives, until it is done. When `f` throws,
/// the iterator is closed ([`Interp::iter_close_after_throw`]) and the exception is thrown
/// again; when a step throws, the iterator is not closed. `rec` and each value are kept
/// reachable while `f` runs.
pub(crate) fn for_each_value(&mut self, rec: ObjId, mut f: impl FnMut(&mut Self, Value) -> JsResult<()>) -> JsResult<()> {
self.rooted(&[Value::Object(rec)], |i| {
while let Some(v) = i.iter_next(rec)? {
match i.rooted(std::slice::from_ref(&v), |i| f(i, v.clone())) {
Ok(()) => {}
Err(Abrupt::Throw(reason)) => return Err(i.iter_close_after_throw(rec, reason)),
Err(other) => return Err(other),
}
}
Ok(())
})
}
/// IteratorClose (section 7.4.6) with the exception `reason`: closes the iterator of `rec`
/// unless it is done, and gives back `reason` to throw, with the position it was thrown from.
/// What closing it throws is dropped, the lookup of `return` included (ECMA-262 2023 section
/// 7.4.8, steps 4 to 6); running out of fuel, heap or time is not.
pub(crate) fn iter_close_after_throw(&mut self, rec: ObjId, reason: Value) -> Abrupt {
let site = self.throw_site.clone();
let mark = self.thrown_mark;
match self.rooted(std::slice::from_ref(&reason), |i| i.iter_close(rec)) {
Ok(()) | Err(Abrupt::Throw(_)) => {
self.throw_site = site;
self.thrown_mark = mark;
self.passing = reason.clone();
Abrupt::Throw(reason)
}
Err(other) => other,
}
}
/// `value` → `record`.
pub(crate) fn op_get_iterator(&mut self) -> JsResult<()> {
let v = self.peek(0)?;
@@ -227,8 +267,9 @@ impl Interp {
self.append_values(rec, a)
}
/// Appends the values the iterator of `rec` gives to the array `a`; both are on the stack.
fn append_values(&mut self, rec: ObjId, a: ObjId) -> JsResult<()> {
/// Appends the values the iterator of `rec` gives to the array `a`; both are on the stack or
/// otherwise kept reachable.
pub(crate) fn append_values(&mut self, rec: ObjId, a: ObjId) -> JsResult<()> {
while let Some(v) = self.iter_next(rec)? {
let Class::Array { length, .. } = &self.object(a)?.class else { return internal("not an array") };
let i = *length;
+7 -4
View File
@@ -103,10 +103,13 @@
//! entries added while it runs; `WeakMap` and `WeakSet` (23.3 and 23.4), whose entries the
//! collector removes once their keys are unreachable; and `ArrayBuffer`, `DataView` and the nine
//! typed arrays (24.1, 24.2 and 22.2). `keys`, `values` and `entries` give iterator objects with
//! a `next` method. Until the language has iterators, the collection constructors and
//! `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by
//! index. A typed array constructor reads an array or an object with a `length` the same way, and
//! converts a first argument that is not an object to a length. A buffer longer than the heap
//! a `next` method, and `Map`, `Set` and the typed arrays are iterable. The collection
//! constructors read their argument through its `@@iterator` method (sections 23.1.1.1 to
//! 23.4.1.1), so an object without one is a `TypeError`, and a `Map` entry that is not an object
//! is a `TypeError` too. A typed array constructor given an object that is not a buffer or a typed
//! array, and `%TypedArray%.from`, read a source with an `@@iterator` method through its iterator
//! and any other source as an array-like object, by index (sections 22.2.1.4 and 22.2.2.1). A
//! typed array constructor converts a first argument that is not an object to a length. A buffer longer than the heap
//! limit is a `RangeError`, and its bytes are checked against the heap before they are allocated.
#![forbid(unsafe_code)]
+12
View File
@@ -568,6 +568,18 @@ fn a_hidden_or_disabled_ok_button_is_not_the_default_found_by_its_text() {
assert_eq!(field(&seen.borrow().descriptions[0], "defaultElement"), &Data::Number(3.0), "the OK button that can be clicked is the default");
}
#[test]
fn an_ok_button_in_a_hidden_or_disabled_group_is_not_the_default_found_by_its_text() {
let (mut r, seen, _) = realm(vec![close()]);
let source = "var w = new Window('dialog'); var off = w.add('group'); off.enabled = false; off.add('button', undefined, 'OK'); \
var hid = w.add('group'); hid.visible = false; hid.add('group').add('button', undefined, 'Cancel'); \
w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel'); w.show()";
assert_eq!(r.run(source).unwrap(), JsValue::Number(0.0));
let described = &seen.borrow().descriptions[0];
assert_eq!(field(described, "defaultElement"), &Data::Number(6.0), "the OK button outside the disabled group is the default");
assert_eq!(field(described, "cancelElement"), &Data::Number(7.0), "the Cancel button outside the hidden group is the cancel element");
}
#[test]
fn an_ok_or_cancel_button_in_a_hidden_or_disabled_group_is_not_found_by_its_text() {
let (mut r, seen, _) = realm(vec![close()]);
+1 -1
View File
@@ -1132,7 +1132,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.brushOptions",
"Brush Options…",
"",
"{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°, saturationJitter 0..100%, brightnessJitter 0..100%), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, scaleMax %, scaleMode: fixed|pressure|tilt|bearing|rotation|stylusWheel, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options",
"{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°, saturationJitter 0..100%, brightnessJitter 0..100%), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, scaleMax %, scaleMode: fixed|pressure|tilt|bearing|rotation|stylusWheel, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options only when its name or options changed; unchanged approval preserves the brush and adds no Undo",
),
(
"ui.brushObjectOptions",
+1
View File
@@ -38,6 +38,7 @@ mod entry;
mod reshaped;
mod state;
pub(crate) use cid::replacement;
#[cfg(test)]
pub(crate) use cid::{CidText, font_chars, identify_glyph, unify_radical};
pub use entry::{
+1 -5
View File
@@ -1184,11 +1184,7 @@ impl<'p> Builder<'p> {
let data = o.font_data();
let name = self.fonts.get(&key).map(|f| f.name.clone()).or_else(|| data.as_ref().and_then(|d| d.postscript_name.clone()));
let (weight, italic) = data.as_ref().map_or((None, false), |d| (d.weight, d.is_italic));
// A subset's six-letter tag.
let ps = name.as_deref().map(|n| match n.split_once('+') {
Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest.to_string(),
_ => n.to_string(),
});
let ps = name.as_deref().map(|n| crate::import_scan::without_subset_tag(n).to_string());
let installed = ps.as_deref().and_then(|ps| vectorcraft_text::FontDb::global().find_postscript(ps));
let n = match (installed, name) {
(Some(face), _) => FontInfo { family: face.family.clone(), style: face.style.clone(), face: Some(face) },
+1 -1
View File
@@ -70,7 +70,7 @@ impl CidText {
}
/// A ToUnicode value that names no character: U+FFFD alone (#708).
pub(super) fn replacement(u: &craft::pdf::interpret::hayro_cmap::BfString) -> bool {
pub(crate) fn replacement(u: &craft::pdf::interpret::hayro_cmap::BfString) -> bool {
use craft::pdf::interpret::hayro_cmap::BfString;
match u {
BfString::Char(c) => *c == char::REPLACEMENT_CHARACTER,
+22 -6
View File
@@ -1020,19 +1020,26 @@ pub(crate) fn vertical_metrics(f: &Dict<'_>, embedded: bool) -> Option<Vertical>
/// Each CID a `W` or `W2` array (`per` numbers a CID) gives values for, and its values: `c [v…]`
/// gives CIDs from c on their values in turn, `c_first c_last v…` the same values to each of the
/// range. At most [`MAX_CIDS`] CIDs are read.
fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) {
/// range. At most [`MAX_CIDS`] CIDs are read, and a list's values only as far as they take; `per`
/// is 1 or 3.
pub(crate) fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) {
let mut it = a.flex_iter();
let mut read = 0;
loop {
if let Some((first, list)) = it.next::<(u32, Array<'_>)>() {
let values: Vec<f64> = list.iter::<f64>().collect();
for (cid, v) in (first..=u32::MAX).zip(values.chunks_exact(per)) {
// Read as they are given, no more than the CIDs read take.
let mut values = list.iter::<f64>();
let mut v = [0.0; 3];
for cid in first..=u32::MAX {
let Some(group) = v.get_mut(..per) else { return };
if group.iter_mut().any(|slot| values.next().map(|x| *slot = x).is_none()) {
break;
}
read += 1;
if read > MAX_CIDS {
return;
}
each(cid, v);
each(cid, group);
}
} else if per == 1
&& let Some((first, last, w)) = it.next::<(u32, u32, f64)>()
@@ -1060,11 +1067,20 @@ fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) {
}
}
/// A font's PostScript name without its subset's six-letter tag (`ABCDEF+Name` is `Name`, ISO
/// 32000-1 §9.6.4).
pub(crate) fn without_subset_tag(name: &str) -> &str {
match name.split_once('+') {
Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest,
_ => name,
}
}
/// The PostScript name of font `f`: its `BaseFont`. A composite (Type 0) font's `BaseFont` is its
/// CIDFont's name, a hyphen and its CMap's (`Name-Identity-H`, ISO 32000-1 §9.7.6.1), so its
/// descendant CIDFont's `BaseFont` is taken, the font program's own name (§9.7.4.1); without one,
/// the `BaseFont` without the CMap's name on its end.
fn font_name(f: &Dict<'_>) -> Option<String> {
pub(crate) fn font_name(f: &Dict<'_>) -> Option<String> {
if f.get::<Name<'_>>(b"Subtype").is_some_and(|s| s.as_ref() == b"Type3") {
if let Some(base) = f.get::<Name<'_>>(b"BaseFont") {
return Some(String::from_utf8_lossy(base.as_ref()).into_owned());
+1 -5
View File
@@ -1570,11 +1570,7 @@ impl Families {
/// The family and style of a font with base (PostScript) name `name`, or of weight `weight`
/// and slant `italic` when the name has no style; whether the family is available.
pub fn resolve(&self, name: &str, weight: Option<u32>, italic: bool) -> (String, String, bool) {
// A subset's six-letter tag.
let name = match name.split_once('+') {
Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest,
_ => name,
};
let name = crate::import_scan::without_subset_tag(name);
// An installed face of that exact PostScript name: its own family and style.
if let Some((family, style)) = vectorcraft_text::FontDb::global().by_postscript_name(name) {
return (family, style, true);
+2
View File
@@ -62,6 +62,7 @@ mod lab_spot;
mod linearize;
mod marks;
mod output;
mod page_widths;
mod pages;
mod patch;
mod pdfx;
@@ -88,6 +89,7 @@ pub use import_scan::form_content_limit;
pub use import_shading::function_evaluation_limit;
pub use marks::{leaves_out_bleed, page_bleed, printer_marks};
pub use output::ActiveProfiles;
pub use page_widths::{FontWidths, PageWidths};
#[cfg(any(test, feature = "read-count"))]
pub use pages::reads_of;
pub use pages::{
+814
View File
@@ -0,0 +1,814 @@
//! The widths a PDF's pages give the characters of the fonts they set type in, read from the font
//! dictionaries alone (no page is drawn): a simple font's `Widths` from its `FirstChar`, or a
//! composite font's descendant's `W`, each code's character from the font's `ToUnicode` map, or for
//! a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding (ISO 32000-1
//! §9.6.2, §9.6.6, §9.7.4.3, §9.10.3, Annex D.2).
use std::collections::{BTreeMap, HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;
use craft::pdf::interpret::hayro_cmap::{BfString, CMap};
use craft::pdf::syntax::object::{Array, Dict, Name, ObjRef, ObjectIdentifier, Stream};
use craft::pdf::syntax::page::Resources;
use crate::import::replacement;
use crate::import_scan::{cid_ranges, font_name, without_subset_tag};
/// The most fonts read.
const MAX_FONTS: usize = 256;
/// The most form XObjects looked into, and how deep they may nest.
const MAX_FORMS: usize = 4096;
const MAX_FORM_DEPTH: u32 = 16;
/// The most entries of font and XObject resource dictionaries looked at, all pages and forms of the
/// file together (one budget for the whole file, not one a page).
const MAX_KEYS: usize = 1 << 16;
/// The most bytes of width arrays (`Widths`, `W`) read, all fonts together; an array that fonts
/// share by reference is read once. A subset's array is a few kilobytes.
const MAX_WIDTH_TEXT: usize = 4 << 20;
/// The most characters of a font kept.
const MAX_CHARS: usize = 4096;
/// The largest `ToUnicode` map read, decoded: a subset's map names a few hundred codes. A longer one
/// is left unread.
const MAX_TO_UNICODE: usize = 256 << 10;
/// The most bytes of `ToUnicode` maps decoded, all fonts together.
const MAX_TO_UNICODE_TOTAL: usize = 4 << 20;
/// The longest string a `ToUnicode` map read may hold, decoded, in bytes: a destination is a
/// character or a short run of them (a ligature's), and each lookup of a code in a range copies its
/// range's whole destination. A map with a longer one is left unread.
const MAX_DESTINATION: usize = 128;
/// The most codes of a composite font whose characters are looked up (its first, in `W` order):
/// [`MAX_CHARS`] bounds the characters kept, not the codes looked at to find them.
const MAX_LOOKUPS: usize = 4 * MAX_CHARS;
/// How far apart two widths a file gives one character of one font may be and still be one width,
/// in thousandths of an em: files write widths rounded.
const SAME_WIDTH: f32 = 1.0;
/// The widths a page gives the characters of one font, in thousandths of an em, by character.
pub type FontWidths = BTreeMap<char, f32>;
/// The advance widths, in thousandths of an em, that a PDF's pages give the characters of the fonts
/// they set type in, by each font's PostScript name (its `BaseFont` without a subset prefix): what
/// the copy of the font the file was set in draws them at. A `.ai`'s PDF part has them for the type
/// its text document holds, so they tell installed copies of one font apart. A font whose subsets
/// give one character two widths gives none. Cloning it, or a font's widths, shares them.
#[derive(Clone, Debug, Default)]
pub struct PageWidths {
fonts: Arc<HashMap<String, Arc<FontWidths>>>,
}
impl PageWidths {
/// Each character the pages set in the font of PostScript name `name` (exactly, without a
/// subset prefix) and its width (at most 4096 characters): `None` when the pages set none in
/// that font, or its subsets give a character two widths.
pub fn widths(&self, name: &str) -> Option<&Arc<FontWidths>> {
self.fonts.get(name)
}
}
/// Which dictionary `d` is, to look at it once: where its text lies in the file as read. One
/// dictionary that pages or forms share is read from the same place each time (one in an object
/// stream lies in that stream's decoded data, which the reader keeps); telling it by its contents
/// would hash it again for each of them.
fn dict_key(d: &Dict<'_>) -> (usize, usize) {
let text = d.data();
(text.as_ptr() as usize, text.len())
}
/// Each CID a composite font's `W` gives a width, and that width.
type CidWidths = Rc<[(u32, f32)]>;
/// What [`page_widths`] has read so far.
#[derive(Default)]
struct Walk {
/// Each font's characters and widths; `None` when two subsets disagree.
fonts: HashMap<String, Option<FontWidths>>,
/// The narrowest and widest width given each character of each font so far.
bounds: HashMap<String, BTreeMap<char, (f32, f32)>>,
/// The font dictionaries, form XObjects and resource dictionaries already looked at.
seen_fonts: HashSet<(usize, usize)>,
seen_forms: HashSet<ObjectIdentifier>,
walked: HashSet<(usize, usize)>,
/// The `ToUnicode` maps parsed, by their stream: `None` for one that can't be read.
maps: HashMap<ObjectIdentifier, Option<Rc<CMap>>>,
/// The width arrays that fonts name by reference, read: a simple font's `Widths` (its first 256
/// numbers) and a composite font's `W` (each CID and its width).
simple_widths: HashMap<ObjRef, Option<Rc<[f32]>>>,
cid_widths: HashMap<ObjRef, Option<CidWidths>>,
/// How many entries of resource dictionaries have been looked at.
looked: usize,
/// How many bytes of `ToUnicode` maps have been decoded.
decoded: usize,
/// How many width arrays have been read, and how many bytes of them.
arrays_read: usize,
width_text: usize,
}
impl Walk {
/// Note `widths`, characters of the font of PostScript name `name` and their widths. All the
/// widths given one character, by this and the other subsets, must be the same: no two more
/// than [`SAME_WIDTH`] apart.
fn add(&mut self, name: String, widths: Vec<(char, f32)>) {
let slot = self.fonts.entry(name.clone()).or_insert_with(|| Some(BTreeMap::new()));
let Some(have) = slot else { return };
let bounds = self.bounds.entry(name).or_default();
for (c, w) in widths {
if let Some((lo, hi)) = bounds.get_mut(&c) {
(*lo, *hi) = (lo.min(w), hi.max(w));
if *hi - *lo > SAME_WIDTH {
*slot = None;
return;
}
} else if have.len() < MAX_CHARS {
have.insert(c, w);
bounds.insert(c, (w, w));
}
}
}
/// Look at one more entry of a resource dictionary: `false` once [`MAX_KEYS`] have been.
fn look(&mut self) -> bool {
self.looked += 1;
self.looked <= MAX_KEYS
}
/// The `ToUnicode` map `s`, parsed once however many fonts name it: `None` when it decodes to
/// more than [`MAX_TO_UNICODE`] bytes, when the maps decoded so far reach
/// [`MAX_TO_UNICODE_TOTAL`], when it holds a string longer than [`MAX_DESTINATION`], or when it
/// can't be read. A map is charged what was decoded of it,
/// at most the limit: a stream written plain comes back whole without being decoded.
fn character_map(&mut self, s: &Stream<'_>) -> Option<Rc<CMap>> {
let id = s.obj_id();
if !self.maps.contains_key(&id) {
let left = MAX_TO_UNICODE_TOTAL.saturating_sub(self.decoded).min(MAX_TO_UNICODE + 1);
let data = s.decoded_within(left).ok();
self.decoded += data.as_ref().map_or(left, |d| d.len().min(left));
let map = data
.filter(|d| d.len() < left && d.len() <= MAX_TO_UNICODE && !d.starts_with(b"bcmap") && longest_string(d) <= MAX_DESTINATION)
.and_then(|d| CMap::parse(&d, |_| None));
self.maps.insert(id, map.map(Rc::new));
}
self.maps.get(&id)?.clone()
}
/// Count `array`'s text against [`MAX_WIDTH_TEXT`]: `None` once the width arrays read reach it.
fn width_array<'a>(&mut self, array: Option<Array<'a>>) -> Option<Array<'a>> {
let array = array.filter(|_| self.width_text < MAX_WIDTH_TEXT)?;
self.arrays_read += 1;
self.width_text += array.data().len();
Some(array)
}
/// The first 256 numbers of simple font `f`'s `Widths`, read once for all the fonts that name
/// the same array.
fn simple_widths(&mut self, f: &Dict<'_>) -> Option<Rc<[f32]>> {
let read = |w: &mut Self| w.width_array(f.get::<Array<'_>>(b"Widths")).map(|a| a.iter::<f32>().take(256).collect::<Rc<[f32]>>());
let Some(r) = f.get_ref(b"Widths") else { return read(self) };
if let Some(have) = self.simple_widths.get(&r) {
return have.clone();
}
let got = read(self);
self.simple_widths.insert(r, got.clone());
got
}
/// Each CID that composite font descendant `d`'s `W` gives a width, and the width, read once for all
/// the fonts that name the same array.
fn cid_widths(&mut self, d: &Dict<'_>) -> Option<CidWidths> {
let read = |w: &mut Self| {
let a = w.width_array(d.get::<Array<'_>>(b"W"))?;
let mut out = Vec::new();
cid_ranges(&a, 1, |cid, v| {
if let [w0] = v {
out.push((cid, *w0 as f32));
}
});
Some(out.into())
};
let Some(r) = d.get_ref(b"W") else { return read(self) };
if let Some(have) = self.cid_widths.get(&r) {
return have.clone();
}
let got = read(self);
self.cid_widths.insert(r, got.clone());
got
}
}
/// [`PageWidths`] of the fonts of `pages` (each page's resources) and of the forms they draw.
pub(crate) fn page_widths<'a>(pages: impl IntoIterator<Item = &'a Resources<'a>>) -> PageWidths {
let walk = walk(pages);
let fonts = walk.fonts.into_iter().filter_map(|(name, w)| Some((name, Arc::new(w.filter(|w| !w.is_empty())?)))).collect();
PageWidths { fonts: Arc::new(fonts) }
}
/// Read the fonts of `pages` and of the forms they draw. Each resource dictionary is walked once,
/// though pages and forms share it; a form without resources of its own takes those of what draws
/// it, which are walked already. At most [`MAX_KEYS`] entries are looked at.
fn walk<'a>(pages: impl IntoIterator<Item = &'a Resources<'a>>) -> Walk {
let mut w = Walk::default();
let mut stack: Vec<(Resources<'a>, u32)> = pages.into_iter().map(|r| (r.clone(), 0)).collect();
while let Some((res, depth)) = stack.pop() {
if w.walked.insert(dict_key(&res.fonts)) {
for key in res.fonts.keys() {
if w.seen_fonts.len() >= MAX_FONTS || !w.look() {
break;
}
let Some(f) = res.fonts.get::<Dict<'_>>(key.as_ref()) else { continue };
if w.seen_fonts.insert(dict_key(&f))
&& let Some((name, widths)) = font_widths(&f, &mut w)
{
w.add(name, widths);
}
}
}
if depth >= MAX_FORM_DEPTH || !w.walked.insert(dict_key(&res.x_objects)) {
continue;
}
for key in res.x_objects.keys() {
if w.seen_forms.len() >= MAX_FORMS || !w.look() {
break;
}
let Some(s) = res.x_objects.get::<Stream<'_>>(key.as_ref()) else { continue };
let d = s.dict();
let form = d.get::<Name<'_>>(b"Subtype").is_some_and(|t| t.as_ref() == b"Form");
if let (true, Some(own)) = (form, d.get::<Dict<'_>>(b"Resources"))
&& w.seen_forms.insert(s.obj_id())
{
stack.push((Resources::from_scope(Some(own), res.clone()), depth + 1));
}
}
}
w
}
/// The PostScript name of font `f` (its `BaseFont` without a subset prefix) and the width of each
/// character it names, at most [`MAX_CHARS`] (of a composite font, among its first [`MAX_LOOKUPS`]
/// codes with a width). A code's character comes from the font's `ToUnicode`
/// map or, for a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding;
/// a composite font's codes are its CIDs, so only under an `Identity-H` or `Identity-V` CMap. A
/// width of 0 is a code the subset doesn't use, and is left out. `None` for a Type 3 font (its
/// widths are in its own glyph space) and a font whose codes' characters can't be told.
fn font_widths(f: &Dict<'_>, walk: &mut Walk) -> Option<(String, Vec<(char, f32)>)> {
let subtype = f.get::<Name<'_>>(b"Subtype")?;
if subtype.as_ref() == b"Type3" {
return None;
}
let name = without_subset_tag(&font_name(f)?).to_string();
let composite = subtype.as_ref() == b"Type0";
let encoding = f.get::<Name<'_>>(b"Encoding");
// Only a font without a `ToUnicode` map falls back to its encoding: one whose map can't be
// read gives none.
let to_unicode = match f.get::<Stream<'_>>(b"ToUnicode") {
Some(s) => Some(walk.character_map(&s)?),
None if f.contains_key(b"ToUnicode") => return None,
None => None,
};
let win_ansi = !composite && encoding.as_ref().is_some_and(|e| e.as_ref() == b"WinAnsiEncoding");
if to_unicode.is_none() && !win_ansi {
return None;
}
let char_of = |code: u32| match &to_unicode {
Some(map) => match map.lookup_bf_string(code).filter(|u| !replacement(u)) {
Some(BfString::Char(c)) => Some(c),
_ => None,
},
None => win_ansi_char(code),
};
let width = |w: f32| (w.is_finite() && w > 0.0 && w < 1e5).then_some(w);
let mut widths = Vec::new();
if composite {
if !encoding.is_some_and(|e| matches!(e.as_ref(), b"Identity-H" | b"Identity-V")) {
return None;
}
let d = f.get::<Array<'_>>(b"DescendantFonts").and_then(|a| a.iter::<Dict<'_>>().next())?;
let mut looked = 0;
for (cid, w) in walk.cid_widths(&d)?.iter() {
if widths.len() >= MAX_CHARS || looked >= MAX_LOOKUPS {
break;
}
let Some(w) = width(*w) else { continue };
looked += 1;
if let Some(c) = char_of(*cid) {
widths.push((c, w));
}
}
} else {
let first = f.get::<u32>(b"FirstChar")?;
// A simple font's codes are bytes.
for (code, w) in (first..256).zip(walk.simple_widths(f)?.iter()) {
let Some(w) = width(*w) else { continue };
if let Some(c) = char_of(code) {
widths.push((c, w));
}
}
}
Some((name, widths))
}
/// The decoded length, in bytes, of the longest string in CMap text `data`: a hex string's digits
/// halved, or a literal string's bytes (escapes counted as written, so at least its length). A `<<`
/// opens a dictionary, not a string, and a `%` outside a string starts a comment. An ASCII85
/// string (`<~`), which no `ToUnicode` map writes and whose `z` stands for four bytes, counts as
/// longer than any.
fn longest_string(data: &[u8]) -> usize {
let mut longest = 0;
let mut i = 0;
while let Some(&b) = data.get(i) {
i += 1;
let len = match b {
b'%' => {
while data.get(i).is_some_and(|b| !matches!(b, b'\n' | b'\r')) {
i += 1;
}
continue;
}
b'<' if data.get(i) == Some(&b'~') => return usize::MAX,
b'<' if data.get(i) == Some(&b'<') => {
i += 1;
continue;
}
b'<' => {
let mut digits = 0;
while let Some(&b) = data.get(i) {
i += 1;
if b == b'>' {
break;
}
digits += usize::from(b.is_ascii_hexdigit());
}
digits.div_ceil(2)
}
b'(' => {
let (mut depth, mut len) = (1usize, 0);
while let Some(&b) = data.get(i) {
i += 1;
match b {
b'\\' => i += 1,
b'(' => depth += 1,
b')' => depth -= 1,
_ => {}
}
if depth == 0 {
break;
}
len += 1;
}
len
}
_ => continue,
};
longest = longest.max(len);
}
longest
}
/// The character of code `code` in `WinAnsiEncoding` (ISO 32000-1 Annex D.2), which is Windows-1252
/// but for the codes it leaves unused: `None` for those, for the controls, and for 160 and 173, which
/// it gives the space and the hyphen a second time.
fn win_ansi_char(code: u32) -> Option<char> {
/// Codes 128 to 159; `\0` where the encoding has no character.
const HIGH: [char; 32] = [
'\u{20AC}', '\0', '\u{201A}', '\u{192}', '\u{201E}', '\u{2026}', '\u{2020}', '\u{2021}', '\u{2C6}', '\u{2030}', '\u{160}', '\u{2039}',
'\u{152}', '\0', '\u{17D}', '\0', '\0', '\u{2018}', '\u{2019}', '\u{201C}', '\u{201D}', '\u{2022}', '\u{2013}', '\u{2014}', '\u{2DC}',
'\u{2122}', '\u{161}', '\u{203A}', '\u{153}', '\0', '\u{17E}', '\u{178}',
];
match code {
0x20..=0x7E | 0xA1..=0xAC | 0xAE..=0xFF => char::from_u32(code),
0x80..=0x9F => HIGH.get(usize::try_from(code - 0x80).ok()?).copied().filter(|c| *c != '\0'),
_ => None,
}
}
#[cfg(test)]
mod tests {
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with};
/// A simple font named `name`, in `encoding`, whose widths from code `first` on are `widths`.
fn simple(subtype: &str, name: &str, encoding: &str, first: u32, widths: &str) -> String {
format!("<< /Type /Font /Subtype /{subtype} /BaseFont /{name} /Encoding /{encoding} /FirstChar {first} /Widths [{widths}] >>")
}
/// The pages' fonts are read from their resources and from the forms they draw, a subset's
/// prefix aside: a simple font's characters from `WinAnsiEncoding` (a code 0 wide is left out)
/// or its `ToUnicode` map, a composite font's from its `ToUnicode` map, by CID. The subsets of one
/// font come together; a font whose subsets give a character two widths, a font in another
/// encoding without a `ToUnicode` map, and a Type 3 font give none.
#[test]
fn the_pages_give_each_font_the_widths_of_its_characters() {
let extra = first_extra(2);
let fonts = [
simple("TrueType", "ABCDEF+Sample-Regular", "WinAnsiEncoding", 65, "600 0 520.5"),
simple("Type1", "GHIJKL+Sample-Regular", "WinAnsiEncoding", 128, "700"),
format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /MNOPQR+Wide-Bold-Identity-H /Encoding /Identity-H /ToUnicode {extra} 0 R \
/DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /MNOPQR+Wide-Bold /W [3 [250 610]] >>] >>"
),
simple("Type1", "Roman-Mac", "MacRomanEncoding", 65, "500"),
format!(
"<< /Type /Font /Subtype /Type1 /BaseFont /Mapped /Encoding /MacRomanEncoding /FirstChar 3 /Widths [333] /ToUnicode {extra} 0 R >>"
),
"<< /Type /Font /Subtype /Type3 /BaseFont /Drawn /Encoding /WinAnsiEncoding /FirstChar 65 /Widths [1] /FontMatrix [1 0 0 1 0 0] >>"
.to_string(),
simple("TrueType", "STUVWX+Clash", "WinAnsiEncoding", 65, "640"),
];
let resources = |fonts: &[String], more: &str| {
let list: Vec<String> = fonts.iter().enumerate().map(|(i, f)| format!("/F{i} {f}")).collect();
format!("/Font << {} >> {more}", list.join(" "))
};
let first = PdfPage { resources: resources(&fonts, &format!("/XObject << /Fm0 {} 0 R >>", extra + 1)), ..PdfPage::new(100.0, 100.0, "") };
let second = PdfPage {
resources: resources(&[simple("TrueType", "YZABCD+Clash", "WinAnsiEncoding", 65, "600")], ""),
..PdfPage::new(100.0, 100.0, "")
};
let cmap =
"begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n2 beginbfchar\n<0003> <0020>\n<0004> <03A9>\nendbfchar\nendcmap\n";
let form_font = simple("TrueType", "EFGHIJ+Formed", "WinAnsiEncoding", 97, "480");
let file = pdf_with(
&[first, second],
&[
&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len()),
&format!(
"<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] /Resources << /Font << /F0 {form_font} >> >> /Length 0 >>\nstream\n\nendstream"
),
],
None,
);
let widths = crate::open_pdf(&file, None).unwrap().page_widths();
let got = |name: &str| widths.widths(name).map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::<Vec<_>>());
assert_eq!(got("Sample-Regular"), Some(vec![('A', 600.0), ('C', 520.5), ('€', 700.0)]));
assert_eq!(got("Wide-Bold"), Some(vec![(' ', 250.0), ('Ω', 610.0)]));
assert_eq!(got("Mapped"), Some(vec![(' ', 333.0)]));
assert_eq!(got("Formed"), Some(vec![('a', 480.0)]));
for none in ["ABCDEF+Sample-Regular", "Roman-Mac", "Drawn", "Clash", "Missing"] {
assert_eq!(got(none), None, "{none}");
}
}
/// [`super::walk`] of the pages of `file`.
fn walked(file: &[u8]) -> super::Walk {
let o = crate::open_pdf(file, None).unwrap();
let pages = o.pdf.pages();
super::walk(pages.iter().map(|p| p.resources()))
}
/// Each resource dictionary is walked once: forms without resources of their own (which take
/// those of what draws them), forms that share one, and pages that share one look at each
/// entry once, so a file of thousands of them reads in time in proportion to it.
#[test]
fn shared_resources_are_walked_once() {
let n = 4000;
let extra = first_extra(1);
let font = simple("TrueType", "Shared", "WinAnsiEncoding", 65, "500");
// Forms without resources, then forms that share one resource dictionary (the last object).
let shared = extra + 2 * n;
let forms: Vec<String> = (0..2 * n)
.map(|i| {
let own = if i < n { String::new() } else { format!("/Resources {shared} 0 R ") };
format!("<< /Type /XObject /Subtype /Form /BBox [0 0 1 {i}] {own}/Length 0 >>\nstream\n\nendstream")
})
.chain(std::iter::once(format!("<< /Font << /F0 {} >> >>", simple("TrueType", "Formed", "WinAnsiEncoding", 66, "600"))))
.collect();
let names: Vec<String> = (0..2 * n).map(|i| format!("/X{i} {} 0 R", extra + i)).collect();
let page = PdfPage { resources: format!("/Font << /F0 {font} >> /XObject << {} >>", names.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
let refs: Vec<&str> = forms.iter().map(String::as_str).collect();
let w = walked(&pdf_with(&[page], &refs, None));
assert!(w.fonts.contains_key("Shared") && w.fonts.contains_key("Formed"));
// The page's font and forms, and the shared dictionary's font.
assert!(w.looked <= 1 + 2 * n + 1, "{} entries looked at", w.looked);
// A thousand pages that share one font dictionary of 4000 entries.
let pages_n = 1000;
let extra = first_extra(pages_n);
let entries: Vec<String> = (0..n).map(|i| format!("/F{i} {} 0 R", extra + 1 + i % 50)).collect();
let objects: Vec<String> = std::iter::once(format!("<< {} >>", entries.join(" ")))
.chain((0..50).map(|i| simple("TrueType", &format!("S{i}"), "WinAnsiEncoding", 65, "500")))
.collect();
let pages: Vec<PdfPage> =
(0..pages_n).map(|_| PdfPage { resources: format!("/Font {extra} 0 R"), ..PdfPage::new(100.0, 100.0, "") }).collect();
let refs: Vec<&str> = objects.iter().map(String::as_str).collect();
let w = walked(&pdf_with(&pages, &refs, None));
assert_eq!(w.fonts.len(), 50);
assert!(w.looked <= n, "{} entries looked at", w.looked);
}
/// Past [`super::MAX_FONTS`] fonts no more entries are looked at.
#[test]
fn fonts_past_the_most_read_are_not_looked_at() {
let fonts: Vec<String> =
(0..super::MAX_FONTS + 100).map(|i| format!("/F{i} {}", simple("TrueType", &format!("N{i}"), "WinAnsiEncoding", 65, "500"))).collect();
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
let w = walked(&pdf_with(&[page], &[], None));
assert_eq!(w.fonts.len(), super::MAX_FONTS);
assert!(w.looked <= super::MAX_FONTS + 1, "{} entries looked at", w.looked);
}
/// Past [`super::MAX_KEYS`] entries of resource dictionaries, none are looked at: a font
/// dictionary of more entries than that, all naming one font, is looked at that far.
#[test]
fn entries_past_the_most_looked_at_are_left() {
let extra = first_extra(1);
let entries: Vec<String> = (0..super::MAX_KEYS + 1000).map(|i| format!("/F{i} {extra} 0 R")).collect();
let page = PdfPage { resources: format!("/Font << {} >>", entries.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
let w = walked(&pdf_with(&[page], &[&simple("TrueType", "Many", "WinAnsiEncoding", 65, "500")], None));
assert_eq!(w.fonts.len(), 1);
assert!(w.looked <= super::MAX_KEYS + 1, "{} entries looked at", w.looked);
}
/// A width array that fonts share by reference is read once for all of them: 128 composite
/// fonts naming one `W` and 128 simple fonts naming one `Widths`, each of 100,000 numbers.
#[test]
fn a_width_array_fonts_share_is_read_once() {
let numbers = 100_000;
let big: String = std::iter::repeat_n("500 ", numbers).collect();
let extra = first_extra(1);
let cmap = "begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n1 beginbfrange\n<0000> <00FF> <0041>\nendbfrange\nendcmap\n";
let fonts: Vec<String> = (0..256)
.map(|i| {
if i % 2 == 0 {
format!(
"/F{i} << /Type /Font /Subtype /Type0 /BaseFont /W{i} /Encoding /Identity-H /ToUnicode {} 0 R \
/DescendantFonts [<< /Subtype /CIDFontType2 /W {extra} 0 R >>] >>",
extra + 1
)
} else {
format!(
"/F{i} << /Type /Font /Subtype /TrueType /BaseFont /S{i} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths {} 0 R >>",
extra + 2
)
}
})
.collect();
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
let file = pdf_with(
&[page],
&[&format!("[0 [{big}]]"), &format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len()), &format!("[{big}]")],
None,
);
let w = walked(&file);
assert_eq!(w.arrays_read, 2);
assert!(w.width_text <= 2 * (big.len() + 10), "{} bytes of width arrays read", w.width_text);
assert_eq!(w.fonts.len(), 256);
assert!(w.fonts.values().all(|f| f.as_ref().is_some_and(|f| f.get(&'A') == Some(&500.0))));
}
/// Past [`super::MAX_WIDTH_TEXT`] bytes of width arrays no more are read: of six fonts each with
/// an array of a million bytes, the sixth gives no widths.
#[test]
fn width_arrays_past_the_most_read_are_left() {
let big: String = std::iter::repeat_n("500 ", 250_000).collect();
let extra = first_extra(1);
let fonts: Vec<String> = (0..6)
.map(|i| {
format!(
"/F{i} << /Type /Font /Subtype /TrueType /BaseFont /M{i} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths {} 0 R >>",
extra + i
)
})
.collect();
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
let arrays: Vec<String> = (0..6).map(|_| format!("[{big}]")).collect();
let refs: Vec<&str> = arrays.iter().map(String::as_str).collect();
let w = walked(&pdf_with(&[page], &refs, None));
assert_eq!(w.arrays_read, 5);
assert_eq!(w.fonts.values().filter(|f| f.as_ref().is_some_and(|f| !f.is_empty())).count(), 5);
}
/// Widths that drift past [`super::SAME_WIDTH`] over several subsets are two widths, though
/// each lies within it of the one read before: subsets giving `A` 600, 600.8 and 601.6 give the
/// font none, as do subsets giving `B` 501.5, 500.6 and 500. Two within it still give one. Each
/// subset is on a page of its own, so they are read in turn (a font dictionary's entries come in
/// no set order).
#[test]
fn widths_that_drift_apart_over_several_subsets_give_none() {
let tags = ["AAAAAA", "BBBBBB", "CCCCCC"];
let pages: Vec<PdfPage> = (0..3)
.map(|i| {
let mut fonts = vec![
format!("/D {}", simple("TrueType", &format!("{}+Drift", tags[i]), "WinAnsiEncoding", 65, ["600", "600.8", "601.6"][i])),
format!("/B {}", simple("TrueType", &format!("{}+Back", tags[i]), "WinAnsiEncoding", 65, ["0 501.5", "0 500.6", "0 500"][i])),
];
if i < 2 {
fonts.push(format!("/S {}", simple("TrueType", &format!("{}+Steady", tags[i]), "WinAnsiEncoding", 65, ["600", "600.8"][i])));
}
PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }
})
.collect();
let widths = crate::open_pdf(&pdf_with(&pages, &[], None), None).unwrap().page_widths();
assert!(widths.widths("Drift").is_none());
assert!(widths.widths("Back").is_none());
assert!(widths.widths("Steady").is_some_and(|w| w.contains_key(&'A')));
}
/// Only a simple font without a `ToUnicode` map takes its characters from `WinAnsiEncoding`:
/// one whose map is left unread (longer than [`super::MAX_TO_UNICODE`]) or isn't a stream gives
/// no widths.
#[test]
fn a_to_unicode_map_that_cant_be_read_gives_no_widths() {
let mut big = String::from("begincmap\n1 begincodespacerange\n<00> <FF>\nendcodespacerange\n");
while big.len() <= super::MAX_TO_UNICODE {
big.push_str("1 beginbfchar\n<41> <0042>\nendbfchar\n");
}
big.push_str("endcmap\n");
let extra = first_extra(1);
let font = |name: &str, to_unicode: &str| {
format!("<< /Type /Font /Subtype /TrueType /BaseFont /{name} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths [600]{to_unicode} >>")
};
let page = PdfPage {
resources: format!(
"/Font << /F0 {} /F1 {} /F2 {} >>",
font("Unread", &format!(" /ToUnicode {extra} 0 R")),
font("Named", " /ToUnicode /Identity-H"),
font("Plain", "")
),
..PdfPage::new(100.0, 100.0, "")
};
let file = pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{big}endstream", big.len())], None);
let widths = crate::open_pdf(&file, None).unwrap().page_widths();
assert!(widths.widths("Unread").is_none());
assert!(widths.widths("Named").is_none());
assert_eq!(widths.widths("Plain").map(|w| w.get(&'A').copied()), Some(Some(600.0)));
}
/// A `ToUnicode` map with a destination longer than [`super::MAX_DESTINATION`] is left unread,
/// though the whole map is under [`super::MAX_TO_UNICODE`]: each lookup of a code in its range
/// would copy the whole destination. A hex destination of 60,000 characters, a literal one of
/// 600, and ASCII85 ones (`z` stands for four bytes, and one can hide the rest of its line
/// behind a `%` the pre-scan would take for a comment) are all left unread. A map with a long
/// name in a dictionary (`<<`) and a comment with an unclosed `(`, more than the limit before
/// the map's end, is still read.
#[test]
fn a_to_unicode_map_with_a_long_destination_is_left_unread() {
let head = "begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n1 beginbfchar\n<0001> <0041>\nendbfchar\n";
let range = |dst: &str| format!("{head}1 beginbfrange\n<0100> <01FF> {dst}\nendbfrange\nendcmap\n");
let hex = range(&format!("<{}>", "0042".repeat(60_000)));
let literal = range(&format!("({})", "B".repeat(600)));
let zeros = range(&format!("<~{}~>", "z".repeat(1_000)));
let hidden = format!("{head}<~>%~> 1 beginbfrange <0100> <01FF> <{}> endbfrange\nendcmap\n", "0042".repeat(300));
let padding = "1 beginbfchar\n<0002> <0042>\nendbfchar\n".repeat(10);
let short = format!(
"/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 /{} 1 >> def\n% (an unclosed comment\n{head}{padding}endcmap\n",
"A".repeat(600)
);
assert!(hex.len() < super::MAX_TO_UNICODE);
let extra = first_extra(1);
let names = ["Hex", "Literal", "Zeros", "Hidden", "Short"];
let fonts: Vec<String> = names
.iter()
.enumerate()
.map(|(i, name)| {
format!(
"/{name} << /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R \
/DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500] 256 511 500] >>] >>",
extra + i
)
})
.collect();
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
let maps: Vec<String> =
[hex, literal, zeros, hidden, short].iter().map(|m| format!("<< /Length {} >>\nstream\n{m}endstream", m.len())).collect();
let refs: Vec<&str> = maps.iter().map(String::as_str).collect();
let file = pdf_with(&[page], &refs, None);
let widths = crate::open_pdf(&file, None).unwrap().page_widths();
for unread in ["Hex", "Literal", "Zeros", "Hidden"] {
assert!(widths.widths(unread).is_none(), "{unread}");
}
let short = widths.widths("Short").map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::<Vec<_>>());
assert_eq!(short, Some(vec![('A', 500.0)]));
}
/// Past [`super::MAX_LOOKUPS`] codes of a composite font, no more are looked up, though few of
/// them gave a character: of two fonts whose `W` gives all 65,536 CIDs a width, the one whose
/// map gives CID 1 a character gives its width, and the one whose map only gives CID 20,000 one
/// gives none.
#[test]
fn codes_past_the_most_looked_up_are_left() {
let cmap = |code: &str| {
format!("begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n1 beginbfchar\n<{code}> <0041>\nendbfchar\nendcmap\n")
};
const { assert!(20_000 > super::MAX_LOOKUPS) };
let extra = first_extra(1);
let font = |name: &str, map: usize| {
format!(
"/{name} << /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R \
/DescendantFonts [<< /Subtype /CIDFontType2 /W {} 0 R >>] >>",
extra + map,
extra + 2
)
};
let page = PdfPage { resources: format!("/Font << {} {} >>", font("Near", 0), font("Far", 1)), ..PdfPage::new(100.0, 100.0, "") };
let maps: Vec<String> =
["0001", "4E20"].iter().map(|c| cmap(c)).map(|m| format!("<< /Length {} >>\nstream\n{m}endstream", m.len())).collect();
let file = pdf_with(&[page], &[&maps[0], &maps[1], "[0 65535 500]"], None);
let widths = crate::open_pdf(&file, None).unwrap().page_widths();
assert_eq!(widths.widths("Near").map(|w| w.get(&'A').copied()), Some(Some(500.0)));
assert!(widths.widths("Far").is_none());
}
/// [`crate::import_scan::cid_ranges`] gives each CID of a `W` its values, a list's in turn (an
/// incomplete last group left out) and a range's to each, and reads no more of a long list than
/// the CIDs it takes.
#[test]
fn cid_ranges_give_each_cid_its_values() {
let extra = first_extra(1);
let long: String = std::iter::repeat_n("7 ", 70_000).collect();
let arrays = ["[1 [10 20 30] 100 102 7]".to_string(), "[1 [1 2 3 4 5 6 7]]".to_string(), format!("[0 [{long}]]")];
let page = PdfPage {
resources: format!("/Properties << /A {extra} 0 R /B {} 0 R /C {} 0 R >>", extra + 1, extra + 2),
..PdfPage::new(10.0, 10.0, "")
};
let refs: Vec<&str> = arrays.iter().map(String::as_str).collect();
let file = pdf_with(&[page], &refs, None);
let o = crate::open_pdf(&file, None).unwrap();
let pages = o.pdf.pages();
let props = &pages.iter().next().unwrap().resources().properties;
let ranges = |key: &str, per: usize| {
let mut out = vec![];
crate::import_scan::cid_ranges(&props.get::<craft::pdf::syntax::object::Array<'_>>(key).unwrap(), per, |cid, v| {
out.push((cid, v.to_vec()))
});
out
};
let one = |v: &[(u32, f64)]| v.iter().map(|(c, w)| (*c, vec![*w])).collect::<Vec<_>>();
assert_eq!(ranges("A", 1), one(&[(1, 10.0), (2, 20.0), (3, 30.0), (100, 7.0), (101, 7.0), (102, 7.0)]));
assert_eq!(ranges("B", 3), [(1, vec![1.0, 2.0, 3.0]), (2, vec![4.0, 5.0, 6.0])]);
assert_eq!(ranges("C", 1).len(), 65_536);
}
/// A `ToUnicode` map written plain and longer than the limits is charged no more than a
/// decoded one could be: the small maps of the other fonts are still read.
#[test]
fn a_long_plain_map_leaves_the_others_read() {
let mut big = String::from("begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n");
while big.len() <= super::MAX_TO_UNICODE_TOTAL + 1000 {
big.push_str("1 beginbfchar\n<0001> <0041>\nendbfchar\n");
}
big.push_str("endcmap\n");
let small = "begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n1 beginbfchar\n<0001> <0042>\nendbfchar\nendcmap\n";
let extra = first_extra(1);
let cid = |name: &str, map: usize| {
format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R /DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500]] >>] >>",
extra + map
)
};
let n = 40;
let fonts: Vec<String> =
std::iter::once(format!("/A {}", cid("Big", 0))).chain((0..n).map(|i| format!("/F{i} {}", cid(&format!("Small{i}"), 1 + i)))).collect();
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
let objects: Vec<String> = std::iter::once(format!("<< /Length {} >>\nstream\n{big}endstream", big.len()))
.chain((0..n).map(|_| format!("<< /Length {} >>\nstream\n{small}endstream", small.len())))
.collect();
let refs: Vec<&str> = objects.iter().map(String::as_str).collect();
let w = walked(&pdf_with(&[page], &refs, None));
assert!(w.fonts.get("Big").is_some_and(Option::is_none) || !w.fonts.contains_key("Big"));
assert_eq!((0..n).filter(|i| w.fonts.get(&format!("Small{i}")).is_some_and(|f| f.as_ref().is_some_and(|m| !m.is_empty()))).count(), n);
assert!(w.decoded <= super::MAX_TO_UNICODE + 1 + n * small.len(), "{} bytes charged", w.decoded);
}
/// A `ToUnicode` map is parsed once however many fonts name it, and one longer than
/// [`super::MAX_TO_UNICODE`] decoded is left unread, whether its stream is written plain or
/// compressed: its fonts give no widths.
#[test]
fn a_to_unicode_map_is_read_once_and_only_up_to_its_limit() {
use std::io::Write as _;
let small =
"begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n1 beginbfchar\n<0001> <0041>\nendbfchar\nendcmap\n".to_string();
let mut big = String::from("begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n");
while big.len() <= super::MAX_TO_UNICODE {
big.push_str("1 beginbfchar\n<0001> <0041>\nendbfchar\n");
}
big.push_str("endcmap\n");
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
z.write_all(big.as_bytes()).unwrap();
let hex: String = z.finish().unwrap().iter().map(|b| format!("{b:02X}")).collect();
let extra = first_extra(1);
let cid = |name: &str, map: usize| {
format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R \
/DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500]] >>] >>",
extra + map
)
};
let fonts: Vec<String> = (0..64).map(|i| format!("/F{i} {}", cid(&format!("U{i}"), i % 3))).collect();
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
let file = pdf_with(
&[page],
&[
&format!("<< /Length {} >>\nstream\n{small}endstream", small.len()),
&format!("<< /Length {} >>\nstream\n{big}endstream", big.len()),
&format!("<< /Length {} /Filter [/ASCIIHexDecode /FlateDecode] >>\nstream\n{hex}>\nendstream", hex.len() + 1),
],
None,
);
let w = walked(&file);
assert_eq!(w.maps.len(), 3, "each map parsed once");
// Each long one charged up to just past the limit.
assert!(w.decoded <= small.len() + 2 * (super::MAX_TO_UNICODE + 1), "{} bytes charged", w.decoded);
assert_eq!(w.maps.values().filter(|m| m.is_some()).count(), 1, "the long ones left unread");
let widths = crate::open_pdf(&file, None).unwrap().page_widths();
assert_eq!(widths.widths("U0").map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::<Vec<_>>()), Some(vec![('A', 500.0)]));
assert!(widths.widths("U1").is_none() && widths.widths("U2").is_none());
// Every font of the name shares one map of its widths.
assert!(std::sync::Arc::ptr_eq(widths.widths("U0").unwrap(), widths.clone().widths("U0").unwrap()));
}
}
+7
View File
@@ -296,6 +296,13 @@ impl Opened {
crate::file_info::file_info_in(&self.pdf)
}
/// The widths the pages give the characters of the fonts they set type in, from the fonts'
/// dictionaries ([`crate::PageWidths`]), without importing any page's art.
pub fn page_widths(&self) -> crate::PageWidths {
let pages = self.pdf.pages();
crate::page_widths::page_widths(pages.iter().map(|p| p.resources()))
}
/// How many pages the PDF has, as [`info`] lists them.
pub fn page_count(&self) -> usize {
self.pdf.pages().len()
+13 -10
View File
@@ -843,12 +843,13 @@ pub(crate) fn with_own_raster_reach(symbols: &SymbolBoxes, n: &Node, b: Rect) ->
b.inflate(o, o)
}
/// `n`'s own box, type's grown to hold its glyphs ([`glyphs_box`]) and a blend's to hold its
/// spine-placed keys and steps: what it draws when its object effects leave it as it is
/// (Revolve builds no art from type).
/// `n`'s own box, type's grown to hold its glyphs ([`glyphs_box`]), a blend's to hold its
/// spine-placed keys and steps and a radial or mirror repeat's to hold its placed copies: what it
/// draws when its object effects leave it as it is (Revolve builds no art from type).
fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
let b = match &n.kind {
NodeKind::Blend { .. } => vectorcraft_geom::union_opt(n.reach_bounds_with(symbols), placed_live_effect_bounds(symbols, n)),
NodeKind::Repeat(_) => vectorcraft_geom::union_opt(n.visual_bounds_with(symbols), placed_live_effect_bounds(symbols, n)),
_ => n.visual_bounds_with(symbols),
}?;
Some(match &n.kind {
@@ -860,7 +861,8 @@ fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
/// A radial or mirror repeat's copies or a spine-aligned blend's steps, measured after they are
/// rotated or reflected. Geometry effects run on the placed shapes, so their reach on the source
/// need not cover what they paint.
/// Without effects, the renderer keeps the quick bounds without evaluating the copies or steps.
/// Without effects inside it, the renderer keeps the quick bounds without evaluating the copies or
/// steps; `n`'s own effects run on the placed whole and are measured by the caller.
fn placed_live_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
match &n.kind {
NodeKind::Blend { spec, .. } if spec.orientation == vectorcraft_doc::BlendOrientation::AlignToPath => {}
@@ -869,12 +871,13 @@ fn placed_live_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
}
let mut has_effects = false;
n.walk(&mut |c| {
has_effects |= has_fx(c)
|| has_object_fx(c)
|| match &c.kind {
NodeKind::SymbolInstance { symbol, .. } => symbols.has_effects(symbol),
_ => false,
};
has_effects |= !std::ptr::eq(c, n)
&& (has_fx(c)
|| has_object_fx(c)
|| match &c.kind {
NodeKind::SymbolInstance { symbol, .. } => symbols.has_effects(symbol),
_ => false,
});
});
if !has_effects {
return None;
+33
View File
@@ -227,6 +227,39 @@ fn moving_a_slanted_mirror_repeat_redraws_the_effects_on_its_reflected_copy() {
}
}
#[test]
fn moving_a_shadowed_radial_or_mirror_repeat_redraws_the_effects_on_its_copies() {
for radial in [true, false] {
let mut old = Document::new(110.0, 80.0);
let source_id = old.alloc_id();
let mut source = Node::path(
source_id,
shapes::rectangle(Rect::new(47.0, 25.0, 49.0, 45.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
source.appearance.effects.push(vectorcraft_doc::Effect {
id: "distort.transform".into(),
params: serde_json::json!({"scaleH": 400, "scaleV": 100, "reference": 4}),
visible: true,
});
let repeat = if radial {
vectorcraft_doc::RepeatSpec::radial(vec![Arc::new(source)], 4, Some(12.0))
} else {
vectorcraft_doc::RepeatSpec::mirror(vec![Arc::new(source)], 45.0, 6.0)
};
let id = old.alloc_id();
let mut node = Node::new(id, vectorcraft_doc::NodeKind::Repeat(repeat));
// The repeat's own effect sends its bounds through the object-effects branch.
node.appearance.effects.push(shadow());
old.insert(Some(old.layers[0].id), 0, node).unwrap();
let mut moved = old.clone();
moved.node_mut(id).unwrap().transform(Affine::translate((3.0, 4.0)), false);
// A partial redraw must reproduce the whole frame, both on the move and on Undo.
area(redraw(&old, &moved));
area(redraw(&moved, &old));
}
}
#[test]
fn adding_removing_and_restacking_change_those_objects() {
let (old, [loose, _, _, _, other]) = document();
+1 -1
View File
@@ -51,7 +51,7 @@ const ROWS: &[Row] = &[
(&["mirrorCut"], None, &["axis", "keep"]),
(&["puppetWarp"], None, &["showMesh", "expand"]),
(&["arc"], None, &["closed", "lengthX", "lengthY", "reference", "baseAlong", "slope", "fillArc"]),
(&[crate::three_point_arc::ID], None, &["direction"]),
(&[crate::three_point_arc::ID], None, &["direction", "join", "tangentSnap"]),
(&["spiral"], None, &["decay", "segments", "clockwise"]),
// The grids' Tool Options: the dividers and switches the drag uses, the Default Size and
// Reference Point a click's dialog opens with.
+207 -21
View File
@@ -8,6 +8,11 @@
//! the second end along the line from that end to the point, and Shift keeps the line at 45°
//! steps). `direction` is set in the tool's Tool Options and kept with the preferences; `]` (with
//! or without Shift) switches it while the ends are placed. Every point snaps to Smart Guides.
//! With the `join` option on (Tool Options, or J while the ends are placed), an end placed within
//! reach of an end of an open path lands on it, and the arc is joined to that path. With
//! `tangentSnap` on (the default), in direction mode, when the direction line starts at an end of
//! an open path, the third point snaps onto the line along which the arc carries on the path, the
//! same way or turned back, and the tool shows that line dashed.
//! Until the third point is placed, the tool shows the arc as a dashed outline with its ends, its
//! center as a small cross, the direction line in direction mode and, with Measurement Labels on,
//! the radius by the pointer. Where no arc fits (the third point lies on the line through the
@@ -17,9 +22,9 @@
//! the ends; a second click on the first end (a double-click) places nothing.
use serde_json::{Value, json};
use vectorcraft_doc::MAX_COORD;
use vectorcraft_doc::{MAX_COORD, NodeKind};
use vectorcraft_geom::shapes::CircularArc;
use vectorcraft_geom::{PathData, Point, Vec2};
use vectorcraft_geom::{PathData, Point, SubPath, Vec2};
use crate::guides::{DrawSnap, Leave};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
@@ -34,6 +39,12 @@ const CROSS_PX: f64 = 4.0;
const REACH_PX: f64 = 3.0;
/// The label the tool shows by the pointer where no arc fits.
pub const TOO_LARGE: &str = "Arc too large";
/// How near (screen points) an end of an open path an end of the arc counts as on it, the Pen's
/// reach for the path ends it joins.
const END_PX: f64 = 5.0;
/// How near (screen points) the line along which the arc carries on an open path the third point
/// snaps onto it.
const TANGENT_PX: f64 = 5.0;
/// The press in progress.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -47,16 +58,82 @@ enum Press {
Third,
}
#[derive(Default)]
/// An end of an open path under an end of the arc: where it is, and the direction a path carrying
/// on from it heads in (none for a path of one anchor).
#[derive(Clone, Copy, Debug, PartialEq)]
struct OpenEnd {
at: Point,
out: Option<Vec2>,
}
/// The end of an open subpath of an editable path (not a guide) within reach of `p`.
fn open_end(cx: &ToolContext, p: Point) -> Option<OpenEnd> {
let tol = cx.tol(END_PX).max(cx.point_tol());
let editable = cx.doc.editable();
// The nearest end; among ends equally near, as `shape.threePointArc`'s `join` picks among the
// ends at a point: one in the selection first, then the last in paint order, and of one
// subpath's two ends its last anchor.
let mut best: Option<(OpenEnd, f64, bool)> = None;
cx.doc.walk(|n| {
let NodeKind::Path { path, guide: false, .. } = &n.kind else { return };
if !editable(n.id) {
return;
}
// In isolation mode, only art inside the isolated node.
let chain = cx.doc.ancestry(n.id).unwrap_or_default();
if cx.isolation.is_some_and(|s| !chain.contains(&s)) {
return;
}
let chosen = chain.iter().any(|id| cx.selection.objects.contains(id));
for sp in path.subpaths.iter().filter(|sp| !sp.closed) {
let ends = [false, true].map(|at_first| end_of(sp, at_first));
let near = match ends {
[Some(last), Some(first)] => Some(if last.at.distance(p) <= first.at.distance(p) { last } else { first }),
[last, first] => last.or(first),
};
let Some(e) = near else { continue };
let d = e.at.distance(p);
if d <= tol && best.is_none_or(|(_, bd, was)| d < bd || (d == bd && (chosen || !was))) {
best = Some((e, d, chosen));
}
}
});
best.map(|(e, _, _)| e)
}
/// The end of the open subpath `sp` (its first anchor when `at_first`), with the direction a path
/// carrying on from it heads in.
fn end_of(sp: &SubPath, at_first: bool) -> Option<OpenEnd> {
let n = sp.anchors.len();
let (end, next) =
if at_first { (sp.anchors.first()?, sp.anchors.get(1)) } else { (sp.anchors.last()?, n.checked_sub(2).and_then(|i| sp.anchors.get(i))) };
// The path reaches the end along the first of its control points that is off the end.
let mut back = vec![if at_first { end.h_out } else { end.h_in }];
if let Some(q) = next {
back.extend([if at_first { q.h_in } else { q.h_out }, q.p]);
}
let out = back.into_iter().map(|q| end.p - q).find(|v| v.hypot() > 0.0).map(|v| v / v.hypot());
Some(OpenEnd { at: end.p, out })
}
pub struct ThreePointArcTool {
snap: DrawSnap,
/// The third point gives the arc's direction at an end instead of a point it passes through.
direction: bool,
/// An end of the arc on an end of an open path joins the arc to that path.
join: bool,
/// In direction mode, the third point snaps to where the arc carries on the open path its
/// direction line starts at, the same way or turned back.
tangent_snap: bool,
start: Option<Point>,
end: Option<Point>,
/// The open path ends found under the first and the second end as each was placed.
open: [Option<OpenEnd>; 2],
press: Option<Press>,
/// Where the pointer is, snapped: the point the next press or release places.
pointer: Option<Point>,
/// The line the third point snapped to: the end it runs through and its direction.
tangent: Option<(Point, Vec2)>,
/// Alt was held at the last pointer event: in direction mode, the direction is at the second end.
at_end: bool,
/// Where the pointer was at its last event, pressed or hovering, before snapping, and the keys
@@ -64,6 +141,25 @@ pub struct ThreePointArcTool {
raw: Option<(Point, Mods)>,
}
impl Default for ThreePointArcTool {
fn default() -> Self {
Self {
snap: DrawSnap::default(),
direction: false,
join: false,
tangent_snap: true,
start: None,
end: None,
open: [None; 2],
press: None,
pointer: None,
tangent: None,
at_end: false,
raw: None,
}
}
}
/// The arc from `start` to `end` shaped by `third`, as `shape.threePointArc` draws it: through
/// `third`, or with `direction`, heading toward `third` from `start` (or, with `at_end`, arriving
/// at `end` along the line from `end` to `third`). None where no arc fits or the arc would reach
@@ -81,14 +177,18 @@ pub fn arc_of(start: Point, end: Point, third: Point, direction: bool, at_end: b
on_canvas.then_some((arc, path))
}
/// The command the tool runs for the arc from `start` to `end` shaped by `third`.
fn command(start: Point, end: Point, third: Point, direction: bool, at_end: bool) -> (String, Value) {
/// The command the tool runs for the arc from `start` to `end` shaped by `third`, joined to the
/// open paths at its ends with `join`.
fn command(start: Point, end: Point, third: Point, direction: bool, at_end: bool, join: bool) -> (String, Value) {
let pair = |p: Point| json!([p.x, p.y]);
let params = if direction {
let mut params = if direction {
json!({ "start": pair(start), "end": pair(end), "toward": pair(third), "at": if at_end { "end" } else { "start" } })
} else {
json!({ "start": pair(start), "end": pair(end), "through": pair(third) })
};
if join {
params["join"] = json!(true);
}
("shape.threePointArc".into(), params)
}
@@ -96,11 +196,37 @@ impl ThreePointArcTool {
fn clear(&mut self) {
self.start = None;
self.end = None;
self.open = [None; 2];
self.press = None;
self.pointer = None;
self.tangent = None;
self.snap.clear();
}
/// The end `which` (0 the first, 1 the second) placed at `p`: the open path end under it is
/// noted, and with `join` on the end lands on it.
fn place(&mut self, cx: &ToolContext, which: usize, p: Point) -> Point {
let found = open_end(cx, p);
if let Some(slot) = self.open.get_mut(which) {
*slot = found;
}
match found {
Some(e) if self.join => e.at,
_ => p,
}
}
/// The second end let go at `b`, with the first at `a`: placed, unless landing on an open path
/// end puts it on the first end, which leaves it to another try.
fn place_end(&mut self, cx: &ToolContext, a: Point, b: Point) {
let at = self.place(cx, 1, b);
if at.distance(a) > cx.tol(REACH_PX) {
self.end = Some(at);
} else {
self.open[1] = None;
}
}
/// How the point being placed keeps to the points before it: the second end to the first, and
/// in direction mode the third point to the end its direction line starts from.
fn leave(&self, cx: &ToolContext, mods: Mods) -> Option<Leave> {
@@ -111,6 +237,28 @@ impl ThreePointArcTool {
}
}
/// The third point at `q`, snapped: in direction mode with `tangentSnap` on, near the line
/// along which the arc carries on the open path its direction line starts at, it moves onto
/// that line. Shift keeps the line at 45° steps instead.
fn third(&mut self, cx: &ToolContext, q: Point, mods: Mods) -> Point {
self.tangent = None;
let (Some(a), Some(b)) = (self.start, self.end) else { return q };
if !self.direction || !self.tangent_snap || mods.shift {
return q;
}
let (o, end) = if self.at_end { (b, self.open[1]) } else { (a, self.open[0]) };
// The direction line starts on the path's end itself, so the arc carries the path on.
let Some(OpenEnd { at, out: Some(t) }) = end.filter(|e| e.at == o) else { return q };
let k = (q - at).dot(t);
let foot = at + t * k;
if k != 0.0 && q.distance(foot) <= cx.tol(TANGENT_PX) {
self.tangent = Some((at, t));
foot
} else {
q
}
}
/// The pressed pointer moved to `ev`, or Shift or Alt changed: the point being placed follows
/// it. A change of keys alone does not make the press a drag.
fn follow(&mut self, cx: &ToolContext, ev: &PointerEvent) {
@@ -122,10 +270,15 @@ impl ThreePointArcTool {
let leave = Leave::segment(cx, *at, ev.mods.shift);
self.pointer = Some(self.snap.drag(cx, ev.pos, Some(&leave)));
}
Some(Press::End | Press::Third) => {
Some(Press::End) => {
let leave = self.leave(cx, ev.mods);
self.pointer = Some(self.snap.drag(cx, ev.pos, leave.as_ref()));
}
Some(Press::Third) => {
let leave = self.leave(cx, ev.mods);
let q = self.snap.drag(cx, ev.pos, leave.as_ref());
self.pointer = Some(self.third(cx, q, ev.mods));
}
None => {}
}
}
@@ -153,7 +306,8 @@ impl Tool for ThreePointArcTool {
PointerKind::Move => {
self.raw = Some((ev.pos, ev.mods));
let leave = self.leave(cx, ev.mods);
self.pointer = Some(self.snap.hover(cx, ev.pos, &[], leave.as_ref()));
let q = self.snap.hover(cx, ev.pos, &[], leave.as_ref());
self.pointer = Some(self.third(cx, q, ev.mods));
vec![]
}
PointerKind::Down => {
@@ -161,7 +315,8 @@ impl Tool for ThreePointArcTool {
let leave = self.leave(cx, ev.mods);
match (self.start, self.end) {
(None, _) => {
let at = self.snap.press(cx, ev.pos, &[], None);
let snapped = self.snap.press(cx, ev.pos, &[], None);
let at = self.place(cx, 0, snapped);
self.start = Some(at);
self.press = Some(Press::Start { at, from: ev.pos, dragged: false });
self.pointer = Some(at);
@@ -177,7 +332,8 @@ impl Tool for ThreePointArcTool {
self.pointer = Some(at);
}
(Some(_), Some(_)) => {
self.pointer = Some(self.snap.press(cx, ev.pos, &[], leave.as_ref()));
let q = self.snap.press(cx, ev.pos, &[], leave.as_ref());
self.pointer = Some(self.third(cx, q, ev.mods));
self.press = Some(Press::Third);
}
}
@@ -195,8 +351,8 @@ impl Tool for ThreePointArcTool {
self.follow(cx, ev);
}
match (self.press.take(), self.start, self.pointer) {
(Some(Press::Start { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.end = Some(b),
(Some(Press::End), Some(a), Some(b)) if b.distance(a) > cx.tol(REACH_PX) => self.end = Some(b),
(Some(Press::Start { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.place_end(cx, at, b),
(Some(Press::End), Some(a), Some(b)) if b.distance(a) > cx.tol(REACH_PX) => self.place_end(cx, a, b),
(Some(Press::Third), Some(a), Some(c)) => {
let Some(b) = self.end else { return vec![] };
// Where no arc fits, nothing is drawn and the ends stay for another try.
@@ -204,7 +360,7 @@ impl Tool for ThreePointArcTool {
self.snap.clear();
return vec![];
}
let (name, params) = command(a, b, c, self.direction, self.at_end);
let (name, params) = command(a, b, c, self.direction, self.at_end, self.join);
self.clear();
return vec![Action::Exec(name, params)];
}
@@ -229,18 +385,40 @@ impl Tool for ThreePointArcTool {
(Some(_), Some((p, mods))) => self.follow(cx, &PointerEvent::new(PointerKind::Drag, p.x, p.y).with_mods(mods)),
(None, Some((p, mods))) if self.end.is_some() && self.pointer.is_some() => {
let leave = self.leave(cx, mods);
self.pointer = Some(self.snap.hover(cx, p, &[], leave.as_ref()));
let q = self.snap.hover(cx, p, &[], leave.as_ref());
self.pointer = Some(self.third(cx, q, mods));
}
_ => {}
}
}
ToolKey::Letter('j') if self.start.is_some() => {
self.join = !self.join;
// Switched on: the ends placed on open path ends land on them, unless that would
// put one end on the other.
if self.join {
let reach = cx.tol(REACH_PX);
if let Some(e) = self.open[0]
&& self.end.is_none_or(|b| b.distance(e.at) > reach)
{
self.start = Some(e.at);
if let Some(Press::Start { at, .. }) = &mut self.press {
*at = e.at;
}
}
if let (Some(a), Some(_), Some(e)) = (self.start, self.end, self.open[1])
&& a.distance(e.at) > reach
{
self.end = Some(e.at);
}
}
}
_ => {}
}
vec![]
}
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
matches!(key, ToolKey::Escape | ToolKey::BracketRight) && self.start.is_some()
matches!(key, ToolKey::Escape | ToolKey::BracketRight | ToolKey::Letter('j')) && self.start.is_some()
}
/// An end placed: Escape drops it.
@@ -266,6 +444,7 @@ impl Tool for ThreePointArcTool {
fn hover_ended(&mut self, _cx: &ToolContext) {
if self.press.is_none() {
self.pointer = None;
self.tangent = None;
self.snap.clear();
}
}
@@ -285,6 +464,11 @@ impl Tool for ThreePointArcTool {
if self.direction {
o.push(Overlay::Line { a: if self.at_end { b } else { a }, b: p, color, dashed: false });
}
// The line the third point snapped to, as far past its end as the pointer is.
if let Some((at, t)) = self.tangent {
let reach = t * p.distance(at);
o.push(Overlay::Line { a: at - reach, b: at + reach, color, dashed: true });
}
match self.arc() {
Some((arc, path)) => {
o.push(Overlay::Path { path: path.to_bezpath(), color, width: 1.0, dashed: true });
@@ -313,21 +497,23 @@ impl Tool for ThreePointArcTool {
}
fn options(&self) -> Value {
json!({ "direction": self.direction })
json!({ "direction": self.direction, "join": self.join, "tangentSnap": self.tangent_snap })
}
fn set_option(&mut self, key: &str, value: &Value) {
if key == "direction"
&& let Some(on) = value.as_bool()
{
self.direction = on;
let Some(on) = value.as_bool() else { return };
match key {
"direction" => self.direction = on,
"join" => self.join = on,
"tangentSnap" => self.tangent_snap = on,
_ => {}
}
}
fn check_option(&self, key: &str, v: &Value) -> Result<(), String> {
use crate::option_check as c;
match key {
"direction" => c::boolean(key, v),
"direction" | "join" | "tangentSnap" => c::boolean(key, v),
_ => Err(c::unknown(key)),
}
}
+118 -4
View File
@@ -166,11 +166,11 @@ fn in_direction_mode_the_third_point_sets_the_tangent_at_an_end() {
let mut t = ThreePointArcTool::default();
assert!(!t.claims_key(&cx, ToolKey::BracketRight), "no ends: ] is left to the app");
t.key(&cx, ToolKey::BracketRight, Mods::default());
assert_eq!(t.options(), json!({ "direction": false }));
assert_eq!(t.options()["direction"], json!(false));
drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default());
assert!(t.claims_key(&cx, ToolKey::BracketRight));
t.key(&cx, ToolKey::BracketRight, Mods::default());
assert_eq!(t.options(), json!({ "direction": true }));
assert_eq!(t.options()["direction"], json!(true));
// Straight up the page from (300, 300): the upper half circle about (340, 300).
hover(&mut t, &cx, (300.0, 250.0), Mods::default());
let o = t.overlays(&cx);
@@ -201,10 +201,10 @@ fn the_direction_option_takes_a_bool() {
t.set_option("direction", &json!(true));
for v in [json!("false"), json!(0), json!(null)] {
t.set_option("direction", &v);
assert_eq!(t.options(), json!({ "direction": true }), "{v}");
assert_eq!(t.options()["direction"], json!(true), "{v}");
}
t.set_option("direction", &json!(false));
assert_eq!(t.options(), json!({ "direction": false }));
assert_eq!(t.options(), json!({ "direction": false, "join": false, "tangentSnap": true }));
}
/// `]` pressed while the third point is held down places the point as the new mode keeps it: the
@@ -373,6 +373,120 @@ fn escape_history_and_a_double_click_drop_or_keep_the_ends() {
assert!(!t.busy() && t.overlays(&cx).is_empty());
}
/// A document holding an open straight path from (100, 100) to (200, 100), unselected.
fn doc_with_open_line() -> vectorcraft_doc::Document {
let mut d = vectorcraft_doc::Document::new(500.0, 500.0);
let (l, id) = (d.layers[0].id, d.alloc_id());
let path = vectorcraft_geom::shapes::line(Point::new(100.0, 100.0), Point::new(200.0, 100.0));
d.insert(Some(l), 0, vectorcraft_doc::Node::path(id, path, vectorcraft_doc::Appearance::default_art())).unwrap();
d
}
/// The arc command's params in `acts`, its only action.
fn params_of(acts: &[Action]) -> Value {
let [Action::Exec(name, params)] = acts else { panic!("{acts:?}") };
assert_eq!(name, "shape.threePointArc");
params.clone()
}
/// With `join` on, an end placed near an open path's end lands on it and the command asks for the
/// join; with it off, the end stays where it was placed and the command asks for none. J while
/// the ends are placed switches `join`, moving a placed end onto the path's end.
#[test]
fn with_join_an_end_near_an_open_path_end_lands_on_it() {
let d = doc_with_open_line();
let (s, p) = (Selection::default(), paint());
// Snap to Point off, so only `join` moves an end onto the path's end.
let isolated = ToolContext { smart_guides: false, snap_to_point: false, isolation: Some(vectorcraft_doc::NodeId(u64::MAX)), ..cx(&d, &s, &p) };
let cx = ToolContext { smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) };
let mut t = ThreePointArcTool::default();
assert!(!t.claims_key(&cx, ToolKey::Letter('j')), "no ends: J is left to the app");
click(&mut t, &cx, (198.5, 100.5));
click(&mut t, &cx, (280.0, 180.0));
let off = params_of(&click(&mut t, &cx, (280.0, 100.0)));
assert_eq!((off["start"].clone(), off.get("join")), (json!([198.5, 100.5]), None), "{off}");
t.set_option("join", &json!(true));
click(&mut t, &cx, (198.5, 100.5));
click(&mut t, &cx, (280.0, 180.0));
let on = params_of(&click(&mut t, &cx, (280.0, 100.0)));
assert_eq!((on["start"].clone(), on["join"].clone()), (json!([200.0, 100.0]), json!(true)), "{on}");
// The second end lands on the path's first end.
click(&mut t, &cx, (20.0, 180.0));
click(&mut t, &cx, (101.5, 100.5));
let on = params_of(&click(&mut t, &cx, (20.0, 100.0)));
assert_eq!(on["end"], json!([100.0, 100.0]), "{on}");
// In isolation mode, a path outside the isolated node is left alone.
click(&mut t, &isolated, (198.5, 100.5));
assert_eq!(t.start, Some(Point::new(198.5, 100.5)));
t.key(&cx, ToolKey::Escape, Mods::default());
// Past the path's end, off its stroke, but within reach of the end.
click(&mut t, &cx, (203.5, 102.0));
assert_eq!(t.start, Some(Point::new(200.0, 100.0)));
t.key(&cx, ToolKey::Escape, Mods::default());
// A second end that would land on the first end is not placed, by a click or by a drag.
click(&mut t, &cx, (200.0, 100.0));
click(&mut t, &cx, (196.0, 100.0));
assert_eq!((t.start, t.end), (Some(Point::new(200.0, 100.0)), None));
t.key(&cx, ToolKey::Escape, Mods::default());
drag(&mut t, &cx, (200.0, 100.0), &[(196.0, 100.0)], Mods::default());
assert_eq!((t.start, t.end), (Some(Point::new(200.0, 100.0)), None));
t.key(&cx, ToolKey::Escape, Mods::default());
// J switches `join` off and on again while the ends are placed.
t.set_option("join", &json!(false));
click(&mut t, &cx, (198.5, 100.5));
assert!(t.claims_key(&cx, ToolKey::Letter('j')));
t.key(&cx, ToolKey::Letter('j'), Mods::default());
assert_eq!((t.options()["join"].clone(), t.start), (json!(true), Some(Point::new(200.0, 100.0))));
click(&mut t, &cx, (280.0, 180.0));
let on = params_of(&click(&mut t, &cx, (280.0, 100.0)));
assert_eq!((on["start"].clone(), on["join"].clone()), (json!([200.0, 100.0]), json!(true)), "{on}");
}
/// In direction mode, with the first end on an open path's end, a third point near the line along
/// which the arc carries the path on (here the line y = 100) snaps onto it, the same way or turned
/// back, and the tool shows the line dashed; farther away, with Shift, with `tangentSnap` off, or
/// away from a path's end, the point stays where it is.
#[test]
fn in_direction_mode_the_third_point_snaps_to_carry_the_path_on() {
let d = doc_with_open_line();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = ThreePointArcTool::default();
t.set_option("direction", &json!(true));
let dashed_through = |o: &[Overlay]| {
o.iter().any(|o| matches!(o, Overlay::Line { a, b, dashed: true, .. } if (a.y - 100.0).abs() < 1e-9 && (b.y - 100.0).abs() < 1e-9 && a.midpoint(*b) == Point::new(200.0, 100.0)))
};
for (third, want) in [((260.0, 103.0), (260.0, 100.0)), ((140.0, 97.0), (140.0, 100.0)), ((260.0, 120.0), (260.0, 120.0))] {
click(&mut t, &cx, (200.0, 100.0));
click(&mut t, &cx, (200.0, 200.0));
hover(&mut t, &cx, third, Mods::default());
assert_eq!(dashed_through(&t.overlays(&cx)), third != want, "{third:?}");
assert_eq!(params_of(&click(&mut t, &cx, third))["toward"], json!([want.0, want.1]), "{third:?}");
}
// Shift keeps the line at 45° steps instead: the pointer just off 45° goes onto 45°.
click(&mut t, &cx, (200.0, 100.0));
click(&mut t, &cx, (200.0, 200.0));
let shift = Mods { shift: true, ..Mods::default() };
let toward = params_of(&click_with(&mut t, &cx, (240.0, 63.0), shift))["toward"].clone();
assert!((toward[0].as_f64().unwrap() - 200.0 + toward[1].as_f64().unwrap() - 100.0).abs() < 1e-9, "{toward}");
// From an end away from the path, or with the snap off, no snap.
for (first, snap) in [((200.0, 140.0), true), ((200.0, 100.0), false)] {
t.set_option("tangentSnap", &json!(snap));
click(&mut t, &cx, first);
click(&mut t, &cx, (200.0, 220.0));
let toward = params_of(&click(&mut t, &cx, (260.0, first.1 + 3.0)))["toward"].clone();
assert_eq!(toward, json!([260.0, first.1 + 3.0]), "{first:?}");
}
// With Alt, the line from the second end, on the path's first end, carries the path on to the
// left.
t.set_option("tangentSnap", &json!(true));
click(&mut t, &cx, (100.0, 200.0));
click(&mut t, &cx, (100.0, 100.0));
let alt = Mods { alt: true, ..Mods::default() };
let acts = click_with(&mut t, &cx, (40.0, 98.0), alt);
assert_eq!((params_of(&acts)["toward"].clone(), params_of(&acts)["at"].clone()), (json!([40.0, 100.0]), json!("end")));
}
/// The catalog lists the tool in the Line Segment tool's group, after the Arc tool, with no
/// default shortcut, and `create` makes it.
#[test]
+18 -5
View File
@@ -42,13 +42,24 @@ pub(crate) struct AddonDialogs {
struct Open {
id: DialogId,
spec: &'static Spec,
document: Option<u64>,
/// The opening document's uid and revert count: File › Revert keeps the uid but replaces the drawing.
document: Option<(u64, u64)>,
}
impl Open {
fn on_document(self, app: &VectorcraftApp) -> bool {
self.document == app.session.active().map(|state| state.uid)
self.document == active_document(app)
}
/// Whether the active document is the opening one, reverted since the dialog opened.
fn reverted(self, app: &VectorcraftApp) -> bool {
matches!((self.document, active_document(app)), (Some((uid, reverts)), Some((now, again))) if uid == now && reverts != again)
}
}
/// The active document's uid and revert count.
fn active_document(app: &VectorcraftApp) -> Option<(u64, u64)> {
app.session.active().map(|state| (state.uid, state.reverts))
}
/// Closes the open add-on dialog without an answer and rolls its preview back.
@@ -81,7 +92,7 @@ pub(crate) fn open(
close_open(app);
let id = dialog.id();
host.with(|h| h.open(dialog));
app.addon_dialogs.open = Some(Open { id, spec, document: app.session.active().map(|state| state.uid) });
app.addon_dialogs.open = Some(Open { id, spec, document: active_document(app) });
Ok(json!({ "dialog": spec.command }))
}
@@ -141,8 +152,10 @@ fn pump_commit(app: &mut VectorcraftApp) {
app.addon_dialogs.open = None;
let preview = mem::take(&mut app.addon_dialogs.preview);
// The dialog is closed already, so a refusal can only go to the status line.
if !on_document {
app.status(tl!("The add-on settings apply only to the drawing where the dialog opened.").to_owned());
if open.reverted(app) {
app.status("The document was reverted. Reopen this dialog to continue.");
} else if !on_document {
app.status("The add-on settings apply only to the drawing where the dialog opened.");
} else if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) {
app.status(error);
}
@@ -340,6 +340,40 @@ fn an_add_on_confirmation_does_not_edit_another_drawing_before_the_pump() {
assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, source_undo));
}
/// Saves the two rectangles of [`two_rects`] to a file in the returned directory, so File › Revert has a copy to restore.
fn two_saved_rects(tag: &str) -> (VectorcraftApp, vectorcraft_testkit::TempDir) {
let mut app = two_rects();
let dir = vectorcraft_testkit::TempDir::new(tag);
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
(app, dir)
}
#[test]
fn an_add_on_draft_from_before_file_revert_leaves_the_restored_drawing_alone() {
let (mut app, _dir) = two_saved_rects("addon-revert");
open_item(&mut app, "Arrange Tools", "Arrange in Grid…");
let id = dialog_id(&app);
set(&app, id, "layout", json!("row"));
set(&app, id, "preview", json!(true));
frame(&mut app);
assert_eq!(x0(&app, 1), 30.0, "previewed before the revert");
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.all", json!({})).unwrap();
let restored = app.session.doc().unwrap().doc.clone();
let undo = undo_len(&app);
frame(&mut app);
assert_eq!(app.session.doc().unwrap().doc, restored, "the draft does not preview on the restored drawing");
assert!(!app.session.in_interaction());
assert!(confirm(&app, id));
frame(&mut app);
assert_eq!(app.session.doc().unwrap().doc, restored, "OK leaves the restored drawing unchanged");
assert_eq!(undo_len(&app), undo, "OK records no undo step");
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
}
#[test]
fn an_add_on_cancel_leaves_the_other_drawings_interaction_running() {
let mut app = two_drawings();
@@ -562,13 +562,13 @@ fn toolbar(ui: &mut Ui, words: &FoldPreviewWords, doc: &vectorcraft_engine::doc:
.collect();
Row::new().wrap(true).show(ui, |ui, _| {
let current = set.view().map_or("", |v| v.1);
if let Some(&id) = Select::new(words.view.clone(), Bind::given(current), &views).show(ui).value()
if let Some(&id) = Select::new(words.view.clone(), Bind::given(current), &views).show(ui).events.committed()
&& let Some(&(_, _, x, y)) = VIEWS.iter().find(|v| v.1 == id)
{
(set.rotate_x, set.rotate_y, set.pan) = (x, y, [0.0; 2]);
}
let inside = Select::new(words.inside.clone(), Bind::given(set.inside.clone()), &insides).placeholder(set.inside.clone()).show(ui);
if let Some(name) = inside.value() {
if let Some(name) = inside.events.committed() {
set.inside.clone_from(name);
}
Checkbox::new(Bind::bound(&mut set.show_fold_lines)).label(words.show_fold_lines.clone()).show(ui);
@@ -565,3 +565,37 @@ fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() {
// With no fold there is the one line that says why.
assert_eq!(status(0, None, false).len(), 1);
}
/// View and Inside: an entry highlighted with the arrow keys changes no setting, Escape leaves the settings as they
/// were, and Enter applies the entry.
#[test]
fn a_highlighted_view_or_inside_applies_only_once_it_is_chosen() {
use craft::ui::contract::Role;
use crate::tests::panel_harness::Panel;
crate::i18n::set_current(crate::i18n::Lang::EN);
let (mut app, _) = app();
app.run("ui.foldPreview", json!({"view": "front", "inside": ""})).unwrap();
let mut panel = Panel::new(app, show);
panel.room(vec2(520.0, 440.0));
let settings = |panel: &Panel| panel.app().ui.fold_preview.clone();
for name in ["View", "Inside"] {
let before = settings(&panel);
panel.click_role(name, Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
panel.frame();
assert_eq!(settings(&panel), before, "a highlighted {name} entry changes no setting");
panel.key(Key::Escape, Modifiers::NONE);
panel.frame();
assert_eq!(settings(&panel), before, "Escape leaves the {name} setting as it was");
panel.click_role(name, Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
panel.key(Key::Enter, Modifiers::NONE);
panel.frame();
assert_ne!(settings(&panel), before, "Enter applies the {name} entry");
}
let set = settings(&panel);
assert_eq!((set.rotate_x, set.rotate_y), (0.0, 180.0), "the entry after Front is Back");
assert!(!set.inside.is_empty(), "the entry after White is a swatch");
}
+1
View File
@@ -149,6 +149,7 @@ impl VectorcraftApp {
plugin_keys: Default::default(),
placed_keys: Default::default(),
view_moved: None,
hover_cursor: None,
hover_object: None,
grab: None,
carry_target: None,
+2
View File
@@ -166,6 +166,8 @@ impl VectorcraftApp {
}
let mut params = params;
self.add_active_artboard(id, &mut params);
// A script's `app.doScript` plays the Actions panel's actions.
panels::actions::add_script_actions(self, id, &mut params);
// Edit Symbol from the Symbols panel in a document without artboards centers the symbol's
// art in the view, whose center the app passes as `viewCenter`, to a batch's symbol.edit
// steps too.
+3
View File
@@ -103,6 +103,9 @@ pub struct CanvasCache {
/// The view the canvas last drew and when it last changed (egui's input time): while it moves,
/// the canvas doesn't hit-test the art under the pointer ([`canvas::hover_wait`], #2452).
pub view_moved: Option<(canvas::ViewKey, f64)>,
/// The cursor the active tool last gave over the canvas, with the tool and the modifier keys
/// it was for: kept while the view moves.
pub hover_cursor: Option<(&'static str, vectorcraft_tools::Mods, vectorcraft_tools::Cursor)>,
/// The object the Eyedropper's click at the pointer would act on, which Object Highlighting
/// outlines, with what it was found for: finding it again, which can sample a color, waits
/// until one of those changes.
+44
View File
@@ -6739,3 +6739,47 @@ fn the_canvas_measures_the_document_once_per_revision() {
}
assert_eq!(measures() - before, 1, "the new document is measured once, and the first keeps its measure");
}
/// While the wheel pans the view under a resting pointer, the canvas keeps the tool's last cursor instead of asking the
/// tool for it in every frame, which hit-tests the art under the pointer each time (#2452). Once the view has been
/// still for `HOVER_STILL_SECS`, the tool is asked again.
#[test]
fn a_wheel_pan_under_a_resting_pointer_keeps_the_tool_cursor() {
let asks = || super::tool_adapter::CURSOR_ASKS.with(std::cell::Cell::get);
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
for i in 0..20 {
let x = f64::from(i) * 15.0;
app.session.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 10, "height": 10})).unwrap();
}
app.select_tool("selection");
let ctx = crate::testing::ui_context();
for _ in 0..3 {
app_step(&mut app, &ctx, vec![]);
}
let at = app.canvas_view().unwrap().rect.center();
// The pointer comes in and rests, and the view is still: the tool gives its cursor.
for _ in 0..12 {
app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
}
assert!(asks() > 0, "the tool gives the cursor over a still view");
let wheel = |dy: f32| egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Line,
delta: vec2(0.0, dy),
phase: egui::TouchPhase::Move,
modifiers: egui::Modifiers::default(),
source: egui::MouseWheelSource::Unknown,
};
let before = (asks(), app.canvas_view().unwrap().center);
for i in 0..10 {
app_step(&mut app, &ctx, vec![wheel(if i % 2 == 0 { -2.0 } else { 3.0 })]);
}
assert_ne!(app.canvas_view().unwrap().center, before.1, "the wheel pans the view");
assert_eq!(asks() - before.0, 0, "no frame of the pan asks the tool for its cursor");
// Still for longer than HOVER_STILL_SECS (egui steps 1/60 s per frame here): the tool is asked again.
let before = asks();
for _ in 0..20 {
app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
}
assert!(asks() > before, "once the view is still, the tool gives the cursor again");
}
+28 -1
View File
@@ -18,6 +18,12 @@ use vectorcraft_tools::{Mods, PenPose, PointerEvent, PointerKind, ToolKey as Eng
use super::{Ui, VectorcraftApp};
use crate::cursors::tool_cursor;
#[cfg(test)]
thread_local! {
/// How many times [`SessionTool`] asked the session for the tool's cursor on this thread.
pub(crate) static CURSOR_ASKS: Cell<usize> = const { Cell::new(0) };
}
/// The tools that change only the view: they neither autoscroll nor take the document's presses under a modal.
const VIEW_TOOLS: [&str; 3] = ["hand", "zoom", "rotateView"];
@@ -548,10 +554,31 @@ impl CanvasTool for SessionTool<'_> {
// The document's overlays are shown by `overlays::show` after the host, in one list.
}
/// While the view moves under the pointer, the cursor the tool last gave for the same tool and keys stays: asking
/// the tool again would hit-test the art under the pointer in every frame of a pan or zoom (#2452).
fn cursor(&self, cx: &ToolContext<'_>) -> Cursor {
let Some(space) = cx.space() else { return tool_cursor(vectorcraft_tools::Cursor::Arrow) };
let at = cx.pointer.map_or(Point::ZERO, |p| space.view.to_doc(p.pos));
let c = self.app().session.cursor(at, tool_mods(cx.mods, cx.held(Key::Space)), self.view);
let mods = tool_mods(cx.mods, cx.held(Key::Space));
let mut app = self.app();
let wait =
super::cursor::hover_wait(&mut app.canvas.view_moved, super::ViewKey::of(&space.view), craft::ui::runtime::frame::clock(&self.ctx));
let id = app.session.tool_id();
let kept = app.canvas.hover_cursor.filter(|&(was, with, _)| wait.is_some() && (was, with) == (id, mods)).map(|(.., c)| c);
let c = match kept {
Some(c) => c,
None => {
#[cfg(test)]
CURSOR_ASKS.with(|n| n.set(n.get() + 1));
let c = app.session.cursor(at, mods, self.view);
app.canvas.hover_cursor = Some((id, mods, c));
c
}
};
// Once the view has been still long enough, the next pass asks the tool again.
if let Some(secs) = wait {
self.ctx.request_repaint_after_secs(secs as f32);
}
// PLAN: assumed the engine's own precise step is dropped (canvas-w25); the canvas's Caps Lock/preference state arrives as `cx.precise()`.
tool_cursor(if cx.precise() { c.precise() } else { c })
}
+13 -2
View File
@@ -3,8 +3,9 @@
//! Tilt, Bearing or Rotation with its Variation, over live previews of the nib and of a stroke
//! (light, heavy, light pressure). Bristle Brush Options: Name (a new bristle brush name that is too
//! long is refused at OK), Shape and the bristle sliders. Scatter, Art and Pattern Brush Options: see
//! [`super::brush_art_options`]. OK runs `brush.options` (strokes painted with the brush update);
//! a name another brush has, or a new bristle brush name that is too long, keeps the dialog open.
//! [`super::brush_art_options`]. A changed OK runs `brush.options` (strokes painted with the brush update);
//! accepting unchanged settings closes without an Undo step.
//! A name another brush has, or a new bristle brush name that is too long, keeps the dialog open.
//!
//! Fields: `__brush` (the brush's name), `__type` (`calligraphic` | `bristle` | `scatter` | `art` |
//! `pattern`), `name`.
@@ -183,6 +184,7 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map<String, Value>, object_keys: Op
initial.set(OPENED, FieldValue::Json(Value::Object(opened)));
initial.set(KEYS, FieldValue::Json(json!(keys)));
}
let unchanged = (!object && !flag(&initial, CREATE)).then(|| (string(&initial, "name"), string(&initial, "__brush"), params(&initial)));
// The canvas of the current window: the Key Color dropper samples there while the dialog is open.
let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id);
let dialog = HostedParamDialog::new(&ctx, KIND, initial, move |fields| {
@@ -202,6 +204,15 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map<String, Value>, object_keys: Op
None if !object => return Err(tl!("Return to the original drawing to edit its brush").into()),
_ => {}
}
if let Some((opened_name, brush, opened_params)) = &unchanged {
let name = string(&result.fields, "name");
// The command ignores an empty name and trims a supplied rename.
let same_name = name == *opened_name || name.trim().is_empty() || name.trim() == brush;
if same_name && params(&result.fields) == *opened_params {
// A deleted brush still reports its normal error instead of accepting a stale dialog.
return app.run("brush.get", json!({"name": brush})).map(|_| ());
}
}
ok(app, result)
})
.ok_or("no window")?,
@@ -9,6 +9,102 @@ fn app() -> VectorcraftApp {
app
}
#[test]
fn unchanged_normal_brush_approval_keeps_the_document_and_undo_history_exact() {
use crate::tests::panel_harness::Panel;
for name in ["6 pt. Flat", "Bristle Round", "Confetti", "Arrow", "Diamonds"] {
let mut app = app();
let params = if name == "Arrow" { json!({"width": 100.25}) } else { json!({}) };
// Establish a saved library before testing a normal approval of an existing brush.
app.run("brush.options", json!({"name": name, "params": params})).unwrap();
let brush = app.run("brush.get", json!({"name": name})).unwrap();
let document = app.session.active().unwrap().doc.clone();
let revision = app.session.active().unwrap().revision;
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(vec2(1200.0, 1200.0));
panel.app().run("ui.brushOptions", json!({"name": name})).unwrap();
panel.frame();
panel.click("OK");
panel.frame();
panel.frame();
assert!(!is_open(&panel.app()), "the unchanged {name} dialog closes normally");
assert_eq!(panel.app().run("brush.get", json!({"name": name})).unwrap(), brush);
let app = panel.app();
let st = app.session.active().unwrap();
assert_eq!(st.doc, document, "unchanged {name} approval preserves the entire stored library");
assert_eq!(st.revision, revision);
assert_eq!(st.history.undo.len(), undo, "unchanged {name} approval adds no Undo step");
}
}
#[test]
fn brush_automation_approval_skips_noop_but_saves_changed_options_in_one_step() {
let mut app = app();
app.run("brush.options", json!({"name": "Arrow", "params": {"width": 100.25}})).unwrap();
let original = app.session.active().unwrap().doc.clone();
let revision = app.session.active().unwrap().revision;
let undo = app.session.active().unwrap().history.undo.len();
open(&mut app, "Arrow");
confirm(&mut app).unwrap();
assert_eq!(app.session.active().unwrap().doc, original);
assert_eq!(app.session.active().unwrap().revision, revision);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
for name in [" Arrow ", ""] {
open(&mut app, "Arrow");
set(&mut app, json!({"name": name}));
confirm(&mut app).unwrap();
assert_eq!(app.session.active().unwrap().doc, original, "a command-equivalent name does not rewrite the brush");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
}
open(&mut app, "Arrow");
set(&mut app, json!({"width": 110.25}));
confirm(&mut app).unwrap();
assert_eq!(app.run("brush.get", json!({"name": "Arrow"})).unwrap()["width"], json!(110.25));
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
app.run("edit.undo", json!({})).unwrap();
assert_eq!(app.session.active().unwrap().doc, original);
}
#[test]
fn normal_brush_rename_still_saves_and_a_deleted_brush_still_refuses_approval() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
let mut app = app();
app.run("brush.options", json!({"name": "Arrow", "params": {}})).unwrap();
let original = app.session.active().unwrap().doc.clone();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(vec2(1200.0, 1200.0));
panel.app().run("ui.brushOptions", json!({"name": "Arrow"})).unwrap();
panel.frame();
panel.click_role("Name", Role::TEXT_INPUT);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("Renamed Arrow");
panel.key(Key::Tab, Modifiers::NONE);
panel.click("OK");
panel.frame();
panel.frame();
assert!(!is_open(&panel.app()));
assert!(panel.app().run("brush.get", json!({"name": "Renamed Arrow"})).is_ok());
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(panel.app().session.active().unwrap().doc, original);
open(&mut panel.app(), "Arrow");
panel.app().run("brush.delete", json!({"name": "Arrow"})).unwrap();
let deleted = panel.app().session.active().unwrap().doc.clone();
let undo = panel.app().session.active().unwrap().history.undo.len();
assert!(confirm(&mut panel.app()).unwrap_err().contains("no brush named"));
assert!(is_open(&panel.app()), "the stale unchanged dialog reports its normal error");
assert_eq!(panel.app().session.active().unwrap().doc, deleted);
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
cancel(&mut panel.app());
}
fn ctx(app: &VectorcraftApp) -> egui::Context {
app.ui_ctx.clone().expect("the test app has a context")
}
@@ -313,6 +313,8 @@ mod tests {
#[test]
fn gallery_cutout_setting_uses_its_localized_label() {
// The Japanese pass measures Cutout in one frame and clicks it in a later one.
crate::testing::wait_for_cjk_fonts();
let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let mut shown_labels = Vec::new();
for (language, expected) in [("en", "Levels"), ("de", "Stufen"), ("ja", "レベル数")] {
@@ -77,6 +77,8 @@ fn compact_objects_on_path_options_pivot_rotate_reset_and_save() {
}
const PIVOT_NAMES: [&str; 9] = ["Top Left", "Top", "Top Right", "Left", "Center", "Right", "Bottom Left", "Bottom", "Bottom Right"];
// The Japanese pass measures the controls once and clicks them frames later.
crate::testing::wait_for_cjk_fonts();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let mut untranslated = Vec::new();
for lang in ["en", "de", "fr", "ja"] {
@@ -371,11 +371,12 @@ fn row(ui: &mut egui::Ui, name: &Label, salt: &str, mut body: impl FnMut(&mut eg
Field::new(name.clone()).id_salt(salt).show(ui, |ui, _| body(ui));
}
/// A select of `entries` named `name` (an English label), over `value`; `set` takes a pick.
/// A select of `entries` named `name` (an English label), over `value`; `set` takes the entry chosen, not one only
/// highlighted.
fn choose<T: craft::behavior::Value>(ui: &mut egui::Ui, name: &str, salt: &str, entries: &[Entry<T>], value: T, mut set: impl FnMut(T)) {
let label = word(name);
row(ui, &label, salt, |ui| {
if let Some(picked) = Select::new(label.clone(), Bind::given(value.clone()), entries).show(ui).value().cloned() {
if let Some(picked) = Select::new(label.clone(), Bind::given(value.clone()), entries).show(ui).events.committed().cloned() {
set(picked);
}
});
+2 -2
View File
@@ -223,7 +223,7 @@ fn resolution_row() -> Param {
let entries: Vec<Entry<usize>> = RESOLUTION_LABELS.iter().enumerate().map(|(i, label)| Entry::new(i, tl!(*label))).collect();
let (mut picked, mut typed) = (None, None);
let shown = Row::new().show(ui, |ui, _| {
picked = Select::new(tl!("Resolution:"), Bind::given(preset.unwrap_or(other)), &entries).show(ui).value().copied();
picked = Select::new(tl!("Resolution:"), Bind::given(preset.unwrap_or(other)), &entries).show(ui).events.committed().copied();
if preset.is_none() {
let field = NumberField::new(tl!("Resolution:"), Bind::given(Some(ppi)))
.range(1.0..=4608.0)
@@ -274,7 +274,7 @@ fn color_choice(
let color = (at == ids.len()).then(|| Srgba::from(Rgba::from_hex(&current).unwrap_or(Rgba::rgb(128, 128, 128))));
let (mut picked, mut pick_color) = (None, false);
let shown = Row::new().show(ui, |ui, _| {
picked = Select::new(tl!(label), Bind::given(at.max(start)), &entries).show(ui).value().copied();
picked = Select::new(tl!(label), Bind::given(at.max(start)), &entries).show(ui).events.committed().copied();
if let Some(color) = color {
pick_color = Swatch::new(tl!(label), color).show(ui).clicked;
}
+6 -4
View File
@@ -130,14 +130,15 @@ fn set_value(fields: &mut DialogFields, key: &str, value: &Value) {
}
}
/// A select over `titles`: the index picked this pass. `at` is the shown entry (none shows a placeholder).
/// A select over `titles`: the index chosen this pass, not one only highlighted. `at` is the shown entry (none shows a
/// placeholder).
fn pick(ui: &mut egui::Ui, label: &str, titles: &[String], at: Option<usize>, default: Option<usize>) -> Option<usize> {
let entries: Vec<Entry<usize>> = titles.iter().enumerate().map(|(i, t)| Entry::new(i, t.clone())).collect();
let mut bind = Bind::given(at.unwrap_or(usize::MAX));
if let Some(d) = default {
bind = bind.reset(d);
}
Select::new(label.to_owned(), bind, &entries).id_salt(label).show(ui).value().copied()
Select::new(label.to_owned(), bind, &entries).id_salt(label).show(ui).events.committed().copied()
}
/// A select row of JSON `options` (value, title) for `key`.
@@ -193,11 +194,12 @@ impl Rows<'_> {
self.range(key, label, range, 1, UnitKind::Percent)
}
/// A length in points, shown in the general unit.
/// A length in points, its unit shown as [`length_unit`](super::three_d_classic::length_unit) says.
fn length(&self, key: &str, label: &'static str, range: (f64, f64)) -> Param {
// Stored in points; a pixel is a point, as the rulers count it.
let lengths = LengthUnits::new(UnitKind::Points, crate::canvas::rulers::unit_kind(self.unit), 72.0);
self.range(key, label, range, 1, UnitKind::Pixels).length(crate::fields::bare_points(lengths, self.bare_points))
let shown = super::three_d_classic::length_unit(self.unit);
self.range(key, label, range, 1, shown).length(crate::fields::bare_points(lengths, self.bare_points))
}
fn flag(&self, key: &str, label: &'static str) -> Param {
@@ -494,6 +494,41 @@ fn the_bevel_repeat_and_the_revolve_segments_show_no_unit() {
assert_eq!(unit(EXTRUDE, "object", "taper"), Some(Some(UnitKind::Percent)));
}
/// The depth, bevel and offset rows of Extrude & Bevel and Revolve, classic ones included, are lengths in points: their
/// sliders show "pt" in a points document, "px" in a pixels one, and points in a document of any other unit.
#[test]
fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() {
use craft::ui::patterns::form_dialogs::DialogFields;
use craft::ui::runtime::env::UnitKind;
use vectorcraft_doc::Unit;
let app = VectorcraftApp::new(Session::new(), crate::Services::default());
let unit = |general: Unit, effect: &str, page: &str, key: &str| {
let mut data = super::super::three_d::data(&app, Some(effect), &serde_json::Map::new());
data.unit = general;
let mut fields = DialogFields::new();
fields.set("__page", FieldValue::Text(page.into()));
super::params(&data, &fields, super::Place::Dialog).into_iter().find(|p| p.key == key).map(|p| p.unit)
};
let mut checked = 0;
for (general, shown) in [(Unit::Points, UnitKind::Points), (Unit::Pixels, UnitKind::Pixels), (Unit::Millimeters, UnitKind::Points)] {
for key in ["depth", "bevelWidth", "bevelHeight"] {
assert_eq!(unit(general, EXTRUDE, "object", key), Some(Some(shown)), "{key} in {general:?}");
checked += 1;
}
let others = [
(REVOLVE, "rotation", "offset"),
(CLASSIC_EXTRUDE, "object", "depth"),
(CLASSIC_EXTRUDE, "object", "bevelHeight"),
(CLASSIC_REVOLVE, "object", "offset"),
];
for (effect, page, key) in others {
assert_eq!(unit(general, effect, page, key), Some(Some(shown)), "{effect} {key} in {general:?}");
checked += 1;
}
}
assert_eq!(checked, 21);
}
#[test]
fn reset_all_keeps_map_art_and_its_options() {
let mut h = drawn(SQUARE, CLASSIC_EXTRUDE);
+2 -1
View File
@@ -722,7 +722,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp) {
return;
}
let Some(w) = app.session.script_window() else { return };
if with_window(app, |d| d.shown()) != Some(w.shown) {
// A question open over the dialog keeps its queued events until the dialog is on top again.
if with_window(app, |d| d.shown()) != Some(w.shown) || !is_top(app) {
return;
}
if let Some(event) = with_window(app, |d| d.next_event(&w)).flatten() {
@@ -224,6 +224,47 @@ fn png_options_name_the_pixel_size_in_the_accessibility_tree() {
assert_eq!(sizes(&mut app), ["120 × 80 px"]);
}
/// PNG Options' Resolution and Background Color, and PNG-8 Options' Matte: an entry highlighted with the arrow keys
/// changes no field, Escape closes the list with the dialog open and its fields as they were, and Enter applies the
/// entry.
#[test]
fn a_highlighted_raster_option_applies_only_once_it_is_chosen() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use vectorcraft_engine::cmd::fileio::FORMATS;
use crate::tests::panel_harness::Panel;
for (id, name) in [("png", "Resolution:"), ("png", "Background Color:"), ("png8", "Matte:")] {
let mut app = VectorcraftApp::new(Session::new(), Services::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(1280.0, 1100.0));
let format = FORMATS.iter().find(|f| f.id == id).unwrap();
super::png_options::open(&mut panel.app(), format, json!({"format": id, "path": format!("/out/a.{id}")}));
panel.frame();
panel.frame();
let fields =
|panel: &Panel| on_top(&panel.app(), |h, _, at| h.open_dialogs().into_iter().find(|d| d.id == at).and_then(|d| d.fields)).flatten();
let before = fields(&panel);
assert!(before.is_some(), "{id} options are open");
panel.click_role(name, Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
panel.frame();
assert_eq!(fields(&panel), before, "a highlighted {name} entry changes no field");
panel.key(Key::Escape, Modifiers::NONE);
panel.frame();
assert_eq!(fields(&panel), before, "Escape closes the {name} list with the fields as they were");
panel.click_role(name, Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
panel.key(Key::Enter, Modifiers::NONE);
panel.frame();
let after = fields(&panel);
assert!(after.is_some(), "Enter in the {name} list keeps the dialog open");
assert_ne!(after, before, "Enter applies the {name} entry");
}
}
/// The role and name of each node of the window's accessibility tree, in a frame drawn once the dialogs have settled.
fn access_names(app: &mut VectorcraftApp) -> Vec<(egui::accesskit::Role, String)> {
super::tests::settle(app);
@@ -223,6 +223,42 @@ fn enter(app: &mut VectorcraftApp) {
frame(app);
}
/// Define Grid's Type, Units and Scale: an entry highlighted with the arrow keys changes no field, Escape closes the
/// list with the dialog open and its fields as they were, and Enter applies the entry.
#[test]
fn a_highlighted_define_grid_choice_applies_only_once_it_is_chosen() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use crate::tests::panel_harness::Panel;
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(1280.0, 1100.0));
panel.app().run("ui.perspectiveGridDialog", json!({})).unwrap();
panel.frame();
panel.frame();
let fields = |panel: &Panel| host(&panel.app(), |h| h.open_dialogs().pop().and_then(|d| d.fields));
for name in ["Type:", "Units:", "Scale:"] {
let before = fields(&panel);
panel.click_role(name, Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
panel.frame();
assert_eq!(fields(&panel), before, "a highlighted {name} entry changes no field");
panel.key(Key::Escape, Modifiers::NONE);
panel.frame();
assert_eq!(kind(&panel.app()).as_deref(), Some(super::perspective_grid::KIND), "Escape closes the list, not the dialog");
assert_eq!(fields(&panel), before, "Escape leaves the fields as they were");
panel.click_role(name, Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
panel.key(Key::Enter, Modifiers::NONE);
panel.frame();
assert_eq!(kind(&panel.app()).as_deref(), Some(super::perspective_grid::KIND), "Enter in the list keeps the dialog open");
assert_ne!(fields(&panel), before, "Enter applies the {name} entry");
}
}
#[test]
fn enter_is_ok_in_define_grid_and_save_grid_as_preset() {
let mut app = app();
@@ -50,9 +50,13 @@ const MAP_SYMBOL: &str = "mapSymbol";
/// The Map Art page's rows of the shown surface's map: views of `mapArt`, never effect parameters.
pub(super) const MAP_ROWS: [&str; 6] = [MAP_SYMBOL, MAP_KEYS[0], MAP_KEYS[1], MAP_KEYS[2], MAP_KEYS[3], MAP_KEYS[4]];
/// The unit of the general-unit length rows.
fn length_unit(unit: Unit) -> UnitKind {
crate::canvas::rulers::unit_kind(unit)
/// The unit shown after a 3D length row, whose slider shows the number of points it holds: the general `unit` when
/// that counts the same number (points, or pixels at 72 per inch), and points otherwise.
pub(super) fn length_unit(unit: Unit) -> UnitKind {
match crate::canvas::rulers::unit_kind(unit) {
UnitKind::Pixels => UnitKind::Pixels,
_ => UnitKind::Points,
}
}
/// Where the rows show: the 3D and Materials panel marks its fields with `__panel`.
@@ -1,8 +1,12 @@
//! Three-Point Arc Tool Options (double-click the Three-Point Arc tool, or `tool.options`):
//! Third Point Sets Direction, the tool's `direction` option. With it on, the third point gives the
//! direction the arc leaves an end in; with it off, the arc passes through the third point. OK
//! sets it with `tool.setOption {tool: "threePointArc", values: {direction}}`; it lasts across
//! tool switches and is saved with the preferences. `]` also switches it while an arc is drawn.
//! direction the arc leaves an end in; with it off, the arc passes through the third point. Snap
//! Where the Arc Continues a Path (`tangentSnap`, on by default) snaps the third point, in
//! direction mode, to where the arc carries on an open path it starts at. Join to Open Path Ends
//! (`join`) joins the arc to the open paths whose ends its ends are placed on. OK sets them with
//! `tool.setOption {tool: "threePointArc", values: {direction, tangentSnap, join}}`; they last
//! across tool switches and are saved with the preferences. `]` also switches `direction`, and J
//! `join`, while an arc is drawn.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
@@ -17,7 +21,11 @@ pub const KIND: &str = "threePointArcOptions";
/// Open the tool's options with their current values.
pub fn open(app: &mut VectorcraftApp) -> Value {
let params = vec![Param::new("direction", tl!("Third Point Sets Direction"), ParamKind::bool(false))];
let params = vec![
Param::new("direction", tl!("Third Point Sets Direction"), ParamKind::bool(false)),
Param::new("tangentSnap", tl!("Snap Where the Arc Continues a Path"), ParamKind::bool(true)),
Param::new("join", tl!("Join to Open Path Ends"), ParamKind::bool(false)),
];
let options = app.session.tool_options_of(TOOL);
let fields = options.as_object().map(|m| form::fields_of(&params, m)).unwrap_or_default();
let (title, shown) = (tool_options::title(TOOL), params.clone());
+1 -1
View File
@@ -1133,7 +1133,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.brushOptions",
"Brush Options…",
"",
"{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°, saturationJitter 0..100%, brightnessJitter 0..100%), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, scaleMax %, scaleMode: fixed|pressure|tilt|bearing|rotation|stylusWheel, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options",
"{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°, saturationJitter 0..100%, brightnessJitter 0..100%), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, scaleMax %, scaleMode: fixed|pressure|tilt|bearing|rotation|stylusWheel, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options only when its name or options changed; unchanged approval preserves the brush and adds no Undo",
),
(
"ui.brushObjectOptions",
+1 -1
View File
@@ -58,7 +58,7 @@ pub use playback::{
deserialize_playback, play, play_action, play_at, playback_drawn, playback_held, playback_options, playback_shown, tick_playback,
waiting_at_stop,
};
pub(crate) use playback::{KnownCommands, has_stop, is_ui_step, shown_text, step_place, stop_params, unknown_commands};
pub(crate) use playback::{KnownCommands, add_script_actions, has_stop, is_ui_step, shown_text, step_place, stop_params, unknown_commands};
pub use recording::{START_RECORDING, STOP_RECORDING, record, stop};
pub(crate) use recording::{after_journaled_edit, after_recorded_command, before_recorded_command};
@@ -39,6 +39,72 @@ fn playback_steps(action: &Action) -> Vec<PlayStep> {
.collect()
}
/// For command `id` `script.run`, or the script of `script.startup.run`'s `then`: gives its
/// `params` the panel's actions as `actions`, which the script's `app.doScript` plays, unless the
/// caller gave them: every action of every set, in panel order, with its steps as playback runs
/// them ([`playback_steps`]) and each step's place in the action. An action that `actions` cannot
/// hold (a step that is not a command, a name that is too long, or one past the limits of
/// [`vectorcraft_engine::script::actions`]) is left out.
pub(crate) fn add_script_actions(app: &VectorcraftApp, id: &str, params: &mut Value) {
use vectorcraft_engine::script::actions::{MAX_ACTIONS, MAX_ACTIONS_BYTES, MAX_ALL_STEPS, Playable, parse};
let target = match id {
"script.run" => Some(params),
"script.startup.run" => params.get_mut("then"),
_ => None,
};
let Some(p) = target.and_then(Value::as_object_mut) else { return };
if p.contains_key("actions") {
return;
}
let list = &app.ui.actions;
let (mut held, mut steps, mut bytes) = (Vec::new(), 0usize, 2usize);
for set in list.sets() {
for a in model::members(list, set).into_iter().filter_map(|i| list.action(i)) {
if held.len() >= MAX_ACTIONS {
break;
}
// The commands of a recorded `command.batch` step go back into one batch step, so that an
// error names a failing command by the batch's place and its own (`3.2`).
let mut played: Vec<Value> = Vec::new();
for s in playback_steps(a) {
let params = match s.command.get("params") {
None | Some(Value::Null) => json!({}),
Some(p) => p.clone(),
};
let one = json!({"command": s.command.get("command").cloned().unwrap_or(Value::Null), "params": params});
let place = s.row + 1;
if a.steps.get(s.row).is_none_or(|step| step.command != "command.batch") {
let mut one = one;
one["step"] = json!(place);
played.push(one);
continue;
}
match played.last_mut() {
Some(last) if last["command"] == "command.batch" && last["step"] == place => {
if let Some(Value::Array(inner)) = last.pointer_mut("/params/commands") {
inner.push(one);
}
}
_ => played.push(json!({"command": "command.batch", "params": {"commands": [one]}, "step": place})),
}
}
let one = Value::Array(vec![json!({"set": set, "name": a.name, "steps": played})]);
let Ok(parsed) = parse(Some(&one)) else { continue };
let count = parsed.first().map_or(0, Playable::len);
let size = serde_json::to_vec(&one).map_or(usize::MAX, |b| b.len());
if steps + count > MAX_ALL_STEPS || bytes.saturating_add(size) > MAX_ACTIONS_BYTES {
continue;
}
steps += count;
bytes += size;
if let Value::Array(mut one) = one {
held.append(&mut one);
}
}
}
p.insert("actions".into(), Value::Array(held));
}
/// The steps of `action` whose command `known` does not hold, in order, as (step index, the index
/// of the command in a `command.batch` step, command id). A `command.batch` step's own commands are
/// checked one by one, as playback runs them ([`included_commands`]); a command of one with no
@@ -637,6 +637,79 @@ fn an_error_counts_excluded_steps() {
assert_eq!(x(&app), 0.0, "the failing batch changes nothing");
}
/// A script's `app.doScript` plays the panel's actions with their included steps; an action whose
/// step `script.run`'s `actions` cannot hold is left out, and a caller's own list is kept.
#[test]
fn a_script_plays_the_panels_actions() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let rect = |x: i64| ("shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}));
let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}});
let batch = json!({"commands": [{"command": "select.none"}, bad]});
let actions = vec![
action("Draw", &[rect(0), rect(20), rect(40)]),
action("Odd", &[rect(0), ("select.none", json!(5))]),
action("Batched", &[("select.none", json!({})), ("command.batch", batch)]),
];
push_set(&mut app, "Mine", actions);
let draw = model::members(&app.ui.actions, "Mine")[0];
app.ui.actions.set_step(draw, 1, false).unwrap();
let objects =
|app: &VectorcraftApp| app.session.active().map_or(0, |d| d.doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::<usize>());
let undo = app.session.active().map_or(0, |d| d.history.undo.len());
app.session.script_frames = false;
let source = "app.doScript('Draw', 'Mine'); try { app.doScript('Odd', 'Mine'); } catch (e) { vc.log(e.message); }";
let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap();
assert_eq!(r["log"], json!(["the set “Mine” has no action “Odd”"]));
assert_eq!(objects(&app), 2, "the excluded step does not run");
assert_eq!(app.session.active().map_or(0, |d| d.history.undo.len()), undo + 1);
// A failing command of a recorded batch is named by the batch's place and its own.
let source = "try { app.doScript('Batched', 'Mine'); } catch (e) { vc.log(e.message); }";
let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap();
let m = r["log"][0].as_str().unwrap_or_default();
assert!(m.starts_with("action step 2.2 of “Batched” (`object.move`) failed:"), "{m}");
let r =
app.run("script.run", json!({"source": "try { app.doScript('Draw', 'Mine'); } catch (e) { vc.log(e.message); }", "actions": []})).unwrap();
assert_eq!(r["log"], json!(["there is no action set “Mine”"]));
assert_eq!(objects(&app), 2);
}
/// The script that `script.startup.run` runs after the startup scripts (its `then`) plays the
/// panel's actions too, as File › Scripts runs a script with Run Startup Scripts on.
#[test]
fn the_script_after_the_startup_scripts_plays_the_panels_actions() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
push_set(&mut app, "Mine", vec![action("Draw", &[("shape.rectangle", json!({"x": 0, "y": 10, "width": 10, "height": 10}))])]);
app.session.script_frames = false;
let then = json!({"source": "try { app.doScript('Draw', 'Mine'); vc.log('ok'); } catch (e) { vc.log(e.message); }", "name": "t.js"});
let r = app.run("script.startup.run", json!({"reason": "menu", "then": then})).unwrap();
assert_eq!(r["then"]["log"], json!(["ok"]), "{r}");
}
/// The steps a script's `app.doScript` plays act on the view's active artboard, as the panel's
/// playback does: Align to Artboard in a recorded batch, and Fit to Selected Art.
#[test]
fn a_script_plays_the_actions_on_the_active_artboard() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
app.run("paint.setStroke", json!({"none": true})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}});
let batch = json!({"commands": [align]});
push_set(&mut app, "Mine", vec![action("Align", &[("command.batch", batch)]), action("Fit", &[("artboard.fitToSelection", json!({}))])]);
let boards = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
let was = boards(&app);
app.view_mut().unwrap().artboard = 1;
app.session.script_frames = false;
let source = "app.doScript('Align', 'Mine'); app.doScript('Fit', 'Mine');";
app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap();
let art = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
assert_eq!(art.x0, was[1].x0, "aligned to artboard 2, the active one");
assert_eq!(boards(&app), [was[0], art], "Fit to Selected Art resizes artboard 2 and leaves artboard 1");
}
/// A step of a recorded `command.batch` that fails is named by the batch's place in the action
/// and its own command.
#[test]
+3 -7
View File
@@ -357,15 +357,11 @@ impl Component for Cells {
/// The marks of node row `n`'s selection square in the panel over `tree`: whether it shows the
/// full-sized square (the row is selected, or it is a layer or sublayer whose visible, unlocked art
/// is all selected), and whether it shows the small one (it holds selected art otherwise).
/// is all selected), and whether it shows the small one (it holds selected art otherwise). It reads
/// the nodes that hold selected art from the rows, which list them once per revision.
pub(super) fn square_marks(tree: &DocLayers<'_>, n: &Node) -> (bool, bool) {
let full = tree.is_selected(n.id) || tree.is_full(n.id);
let holds = !full && {
let mut any = false;
n.walk(&mut |c| any |= c.id != n.id && tree.is_selected(c.id));
any
};
(full, holds)
(full, !full && tree.holds_selected(n.id))
}
/// The cells of row `row` (shown as `info`) of the panel over `tree`.
@@ -193,6 +193,9 @@ pub(super) struct LayerRows {
/// and not empty.
#[plain_data(assume = "node ids are integers")]
full: HashSet<NodeId>,
/// The nodes that hold a selected object below them ([`super::rows::holding`]).
#[plain_data(assume = "node ids are integers")]
holding: HashSet<NodeId>,
/// The selected blends, in selection order.
#[plain_data(assume = "node ids are integers")]
blends: Vec<NodeId>,
@@ -252,6 +255,7 @@ impl LayerRows {
ruler,
guide_rows,
full: super::rows::full_layers(doc, &selected),
holding: super::rows::holding(doc, &selected),
selected,
blends: blends.collect(),
root: st.isolation.and_then(|i| isolated_root(doc, i)).map(|(n, ..)| n.id),
@@ -310,6 +314,11 @@ impl LayerRows {
self.full.contains(&id)
}
/// Whether node `id` holds a selected object below it.
pub(super) fn holds_selected(&self, id: NodeId) -> bool {
self.holding.contains(&id)
}
/// The node ids a row menu's command acts on: every highlighted row when the menu's row is one of
/// them, else the row's own node.
pub(super) fn targets(&self, target: &MenuTarget<RowId>) -> Vec<u64> {
+31
View File
@@ -150,6 +150,37 @@ pub(super) fn full_layers(doc: &Document, sel: &HashSet<NodeId>) -> HashSet<Node
out
}
#[cfg(test)]
thread_local! {
/// How many nodes [`holding`] visited on this thread.
pub(super) static HOLDING_VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The nodes of `doc` that hold an object of `sel` below them, found in one pass over the tree: the rows whose
/// selection square shows the small mark when they are not full.
pub(super) fn holding(doc: &Document, sel: &HashSet<NodeId>) -> HashSet<NodeId> {
/// Adds `n` to `out` when an object of `sel` is below it, and returns whether `n` or one below it is in `sel`.
fn visit(n: &Node, sel: &HashSet<NodeId>, out: &mut HashSet<NodeId>) -> bool {
#[cfg(test)]
HOLDING_VISITS.with(|v| v.set(v.get() + 1));
let mut below = false;
for c in n.children().into_iter().flatten() {
below |= visit(c, sel, out);
}
if below {
out.insert(n.id);
}
below || sel.contains(&n.id)
}
let mut out = HashSet::new();
if !sel.is_empty() {
for n in &doc.layers {
visit(n, sel, &mut out);
}
}
out
}
/// The `layer.target` of a click with `mods` on the target circle of `id`, by the rules of a row click (#8639): plain
/// targets it, Ctrl/Cmd adds it to the selection or takes it out, Shift selects the art of every row `filter` lists
/// from `anchor` (the last circle clicked, else the targeted row) to it, and Shift+Ctrl/Cmd adds that art. With it,
+24
View File
@@ -1328,3 +1328,27 @@ fn a_target_circle_drop_after_file_revert_leaves_the_restored_appearance_in_plac
panel.drag("Target A", "Target B", Modifiers::NONE);
assert_eq!(fill(&panel.app(), b), red, "a target circle drag started after the revert still moves the appearance");
}
/// The rows find which nodes hold selected art once per revision: frames that change nothing walk no node for the
/// selection squares, and a new selection walks the tree once.
#[test]
fn idle_frames_walk_no_node_for_the_selection_squares() {
use crate::tests::panel_harness::Panel;
let visits = || super::rows::HOLDING_VISITS.with(std::cell::Cell::get);
let (mut app, [layer, sub, g, b, a, c]) = nested();
app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap();
let mut panel = Panel::new(app, show);
panel.frame();
assert_eq!(squares(&panel.app(), &[layer, sub, g, b, a, c]), (vec![b], vec![layer, sub, g]), "the layers and the group hold B");
let before = visits();
for _ in 0..10 {
panel.frame();
}
assert_eq!(visits() - before, 0, "frames that change nothing walk no node");
panel.app().session.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let before = visits();
for _ in 0..5 {
panel.frame();
}
assert!((1..=12).contains(&(visits() - before)), "a new selection walks the tree once: {}", visits() - before);
}
+42 -2
View File
@@ -66,7 +66,7 @@ fn check(ui: &mut Ui, label: &'static str, on: bool, enabled: bool) -> Option<bo
}
/// A select named `name` (shown before it when `caption`) over `items` of `(value, shown name)`; the
/// value the user picked this pass.
/// value the user chose this pass, not one only highlighted.
fn pick<T: Clone + PartialEq + Send + Sync + 'static>(
ui: &mut Ui,
name: &str,
@@ -82,7 +82,8 @@ fn pick<T: Clone + PartialEq + Send + Sync + 'static>(
if caption {
Text::new(label.clone()).show(ui);
}
picked = Select::new(label.clone(), Bind::given(current.clone()), &entries).enabled(enabled).id_salt(name).show(ui).value().cloned();
picked =
Select::new(label.clone(), Bind::given(current.clone()), &entries).enabled(enabled).id_salt(name).show(ui).events.committed().cloned();
});
picked
}
@@ -541,6 +542,45 @@ mod tests {
assert_eq!(none.params(AssignChoice::Profile, None), None, "no other profile to pick");
}
/// A profile highlighted in the Assign rows' Profile list assigns nothing, Escape leaves the document as it was,
/// and the profile chosen with Enter is assigned in one undo step.
#[test]
fn a_highlighted_profile_is_assigned_only_once_it_is_chosen() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
// Assigning a profile to the front document changes the process's active color settings.
if !crate::testing::in_own_process("panels::separations::tests::a_highlighted_profile_is_assigned_only_once_it_is_chosen") {
return;
}
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({})).unwrap();
app.run("edit.assignProfile", json!({"rgb": null, "cmyk": null})).unwrap();
let row = AssignRow::of(&app.session.active().unwrap().doc);
assert!(row.others.len() >= 2, "{row:?}");
let mut panel = Panel::new(app, show);
let state = |panel: &Panel| {
let app = panel.app();
let st = app.session.active().unwrap();
(vectorcraft_engine::cmd::colormgmt::doc_profiles(&st.doc), st.history.undo.len())
};
let before = state(&panel);
panel.click_role("Profile:", Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
panel.frame();
assert_eq!(state(&panel), before, "a highlighted profile assigns nothing");
panel.key(Key::Escape, Modifiers::NONE);
panel.frame();
assert_eq!(state(&panel), before, "Escape leaves the document's profiles as they were");
panel.click_role("Profile:", Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
panel.key(Key::Enter, Modifiers::NONE);
panel.frame();
let ((rgb, _), undo) = state(&panel);
assert_eq!(rgb.as_deref(), Some(row.others[1].as_str()), "Enter assigns the chosen profile");
assert_eq!(undo, before.1 + 1, "the choice is one undo step");
}
/// The Assign rows follow the document's color mode: an RGB document lists the RGB working space
/// and the RGB profiles and assigns its RGB profile, a CMYK document the CMYK ones, and the other
/// model's profile stays as it was.
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff. Show more