diff --git a/ROADMAP.md b/ROADMAP.md index abd6bea6bf..d40c33e9e1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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. diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 2a39d50010..c5d13cd0fa 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -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::())); + } + 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] diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index 7ffcb472ff..3cfa54db21 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -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 { +/// 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 { 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> = - 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) { } /// 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> { +/// 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> { 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> { 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 = 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 { + 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 = 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 { +/// +/// 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 { 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 { + (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 f64) -> Option { +/// 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 { 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 = + 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 { + 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 { +/// 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 { 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 = densified(art, tol, MAX_SEG).expect("the tile flattens").into_iter().map(f).collect(); + let chords: Vec = 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"); diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 3e5743aec3..dc1e082ac0 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -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)) } diff --git a/crates/doc/src/id_index.rs b/crates/doc/src/id_index.rs index 34453234ec..0e1673580a 100644 --- a/crates/doc/src/id_index.rs +++ b/crates/doc/src/id_index.rs @@ -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>> { 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], 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 = 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)] diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index de8bfc2875..470b0a94c4 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -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; diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index 295c347765..4a8f6a9d71 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -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> = (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"); +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index b9fd0b98e6..009fc4efd8 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -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. diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 7a4a4dea07..78c066405d 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -110,7 +110,7 @@ pub fn specs() -> Vec { "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 { } /// 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 { 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 { } _ => 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() }, diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 409354719b..4f11935db0 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -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, String>, opts: &LoadOptions) -> Result<(Document, Vec)> { +/// 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, String>, + opts: &LoadOptions, + widths: vectorcraft_pdf::PageWidths, +) -> Result<(Document, Vec)> { 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 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 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 // 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 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) } }; diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 703e9b88af..6e63170f88 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -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 { + 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 = 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 = (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 { + 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"]); +} diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 37f4b132b5..1d6bd59fd1 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -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 diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs index cc210ffa2a..ded0f137b3 100644 --- a/crates/engine/src/cmd/fileio/tests_psdslices.rs +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -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())); diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index de6f945b58..65f268f2b0 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -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 { +pub(super) fn warped(path: &PathData, map: &Homography) -> Option { 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; diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 9bb39e1e96..88ee200c2c 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -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)?; diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index efcd2b1e13..bd6609e2f8 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -59,7 +59,7 @@ pub fn specs() -> Vec { "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 { } // 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 { .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, 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 { + 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 { diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index c277af5c28..58612c744c 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -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 { "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.\" (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 order (returned object order without layers), embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{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.\" (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 order (returned object order without layers), embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -655,7 +655,7 @@ fn at_param(p: &Value) -> Result> { /// 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 { + 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 { 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 { 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 { 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) => { diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 829a52d1fa..612cf436b7 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -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", diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index d895c3969f..194df59e51 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "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 result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{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 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 result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -195,6 +195,7 @@ fn prepare(s: &Session, p: &Value) -> Result { 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 { 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| { diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index f4f807cb15..1a79fbfbc9 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -59,6 +59,15 @@ pub fn specs() -> Vec { 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::>()).collect::>())) }), @@ -986,5 +995,111 @@ fn break_thread(s: &mut Session, p: &Value) -> Result { 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 { + 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::>()).collect::>()) +} + +/// `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 { + 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 = 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; diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs new file mode 100644 index 0000000000..2abb290cf7 --- /dev/null +++ b/crates/engine/src/script/actions.rs @@ -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 +//! (). +//! +//! 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, +} + +/// 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, +} + +/// `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, 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, 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, key: &str, at: &str) -> Result { + 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, 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) -> Step { + let bytes = serde_json::to_vec(¶ms).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 { + let l = link.clone(); + let play = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + 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 { + 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, ¶ms); + 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 = 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)>, + pub batch: Option, +} diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 5a4bb380c0..168f033166 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -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| { @@ -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 { 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 { + 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 { ]); 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| { @@ -2706,6 +2741,7 @@ fn classes(link: &Link) -> Vec { ), ("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", &[])), diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 7452051580..8d15f1b19e 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -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>>, + stories: threads::StoryState, /// The number of text range objects made, which numbers the next one. made: Cell, /// 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", ¶ms))?; - 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 = 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 = 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::>().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::>().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::>()})))?; } @@ -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 { let mut out = Vec::new(); for (name, attr) in ATTRS { @@ -1540,12 +1578,7 @@ fn attr_members(link: &Link) -> Vec { h.charge_call(16 + a.iter().map(super::data_size).sum::())?; 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 { h.charge_call(16 + a.iter().map(super::data_size).sum::())?; 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 { + 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 { ("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 { ("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 { 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 { 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 { ("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 { ("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 { ]), None, ), - ] + ]; + out.extend(stories); + out } #[cfg(test)] diff --git a/crates/engine/src/script/dom/text/threads.rs b/crates/engine/src/script/dom/text/threads.rs new file mode 100644 index 0000000000..e159893e8d --- /dev/null +++ b/crates/engine/src/script/dom/text/threads.rs @@ -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 +//! , +//! and +//! 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, Rc>); + +/// 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>, + list: RefCell>, +} + +/// 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 { + 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, 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", ¶ms).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, 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 { + 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 { + 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, 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, 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 { + 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 { + span_of(h, arg(a, 0), &["StoryRange"]) +} + +/// The span and index of `r` now. +fn resolve(h: &Host, r: StorySpan) -> std::result::Result<(Rc, 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 = 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>, 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::())?; + // 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 = 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 = 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_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| { + 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| { + 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 { + 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 { + 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)), + ), + ] +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index bc6ae00250..19ee454c87 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -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, + /// The actions `app.doScript` can play. + pub actions: Vec, } 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, + /// 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)>, /// 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 = 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() diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 71d7cc1399..4b9cf973a9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -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; diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 320d6ba70f..6ccdfad0a5 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -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] diff --git a/crates/engine/src/tests/dcs.rs b/crates/engine/src/tests/dcs.rs index a8e37ff812..34bfe7a7bc 100644 --- a/crates/engine/src/tests/dcs.rs +++ b/crates/engine/src/tests/dcs.rs @@ -56,7 +56,7 @@ fn single_file(plates: &[(&str, String)], extra: &str) -> Vec { } /// Cyan solid on the top row, PANTONE 185 C at 50% on the left column. -fn two_plates() -> Vec { +pub(crate) fn two_plates() -> Vec { 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"); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 6391c4f3db..405bb12a37 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -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() { diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs new file mode 100644 index 0000000000..1432b8671b --- /dev/null +++ b/crates/engine/src/tests/script_actions.rs @@ -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 { + s.execute("script.run", &json!({"source": source, "name": "t.js", "actions": actions})) +} + +fn log_with(s: &mut Session, source: &str, actions: &Value) -> Vec { + 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 { + 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::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 = (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::>(); + 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::>(); + 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})); +} diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 9e840ddedf..330b3f4d4d 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -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. diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index 7d8f06700e..dc9749fb6c 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -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])); diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 0272e95212..184f43cc4a 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -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"), diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 2935fd0566..0a71638c92 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -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 = [ diff --git a/crates/engine/src/tests/script_threads.rs b/crates/engine/src/tests/script_threads.rs new file mode 100644 index 0000000000..81987f52d9 --- /dev/null +++ b/crates/engine/src/tests/script_threads.rs @@ -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 { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + 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> { + 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, usize)) { + assert_eq!((threads(s), ids.iter().map(|i| plain(s, *i)).collect::>(), undo_steps(s)), *before); +} + +fn state(s: &Session, ids: &[NodeId]) -> (Vec>, Vec, 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 = (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::>()})).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::>().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::>()})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("text.setFormat", &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "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::>() + }; + 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 = (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); +} diff --git a/crates/engine/src/tests/three_point_arc.rs b/crates/engine/src/tests/three_point_arc.rs index ebd755dda7..fb34e0da6e 100644 --- a/crates/engine/src/tests/three_point_arc.rs +++ b/crates/engine/src/tests/three_point_arc.rs @@ -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, 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 = 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"); } diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index ea3142e6cc..d455f6ad2f 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -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"")}), ), ] { let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 749dc57646..9ff294a878 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -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 { + ( + 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::(), + ) + .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> ", "<00> ", "endcodespacerange", "2 beginbfchar", "<0001> <0041>", + "<0002> ", "<41> ", "1 beginbfrange", "<0000> <0000>", " <0000> <0041>", "<0001> <0003> [<0041> <0042>]", + "endbfrange", "endbfchar", "endcmap", "/Identity-H usecmap", "99999999999 beginbfchar", + ]), 0..12), + ) { + let list: Vec = 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 { diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index a59d50e88b..0eeae87282 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -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"), diff --git a/crates/engine/tests/it/several_handles.rs b/crates/engine/tests/it/several_handles.rs index b45b6b16b6..7b5469c278 100644 --- a/crates/engine/tests/it/several_handles.rs +++ b/crates/engine/tests/it/several_handles.rs @@ -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"); +} diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 3c9ce44a77..b6941e4730 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -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 diff --git a/crates/eps/src/import/ai/legacy_text.rs b/crates/eps/src/import/ai/legacy_text.rs index a3864b43d0..e35f61cb54 100644 --- a/crates/eps/src/import/ai/legacy_text.rs +++ b/crates/eps/src/import/ai/legacy_text.rs @@ -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) diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index dc757b1462..17d9896ab9 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -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, + /// 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 diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 9621e7a9b0..20102b29c4 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -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, diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index a4c32b092b..3fb4393b19 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -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, - /// [`Self::font`]'s answer, found once for every run that names the record. - font: std::sync::OnceLock, + /// 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>, + /// [`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>, } 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 { fn find(h: &[u8], n: &[u8], from: usize) -> Option { @@ -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), Arc>> = 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> \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 { diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index d5d7dbc1c8..5b0eb51a73 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -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) -> Option<&Texts> { + fn texts_with( + &mut self, + data: &[u8], + paints: std::collections::HashMap, + 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>> = Default::default(); let stories: Vec>> = 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>> = Default::default(); let stories: Vec>> = infos diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index 69bf4c0af1..bbbacc1c4b 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -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]) -> 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), 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), 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), 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::::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, + /// 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, 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> { - 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> { - 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> { + 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> { - 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> { + 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) diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index e55d2fe4da..2d8d270cc7 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -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 = (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 = text.chars().collect(); + let pairs: Vec = chars.iter().enumerate().map(|(i, c)| format!("<{:04X}> <{:04X}>", i + 1, u32::from(*c))).collect(); + let cmap = format!( + "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n{} beginbfchar\n{}\nendbfchar\nendcmap\n", + pairs.len(), + pairs.join("\n") + ); + let w: Vec = 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 diff --git a/crates/eps/src/import/text.rs b/crates/eps/src/import/text.rs index eff4f8b20e..4b6e5414f9 100644 --- a/crates/eps/src/import/text.rs +++ b/crates/eps/src/import/text.rs @@ -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) { - 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) { + 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)> { - 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)> { + 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> { +pub(crate) fn postscript_face( + name: &str, + version: Option<&str>, + widths: Option<&vectorcraft_pdf::FontWidths>, +) -> Option> { 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); diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index 39734bb088..3ec93edc07 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -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, +) -> JsResult { + 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 = 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). diff --git a/crates/js/src/builtins/collections.rs b/crates/js/src/builtins/collections.rs index 70da37c39c..2d9f6176d3 100644 --- a/crates/js/src/builtins/collections.rs +++ b/crates/js/src/builtins/collections.rs @@ -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 { 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); } diff --git a/crates/js/src/collections_tests.rs b/crates/js/src/collections_tests.rs index cbc35d3929..31230e4958 100644 --- a/crates/js/src/collections_tests.rs +++ b/crates/js/src/collections_tests.rs @@ -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); } diff --git a/crates/js/src/iteration.rs b/crates/js/src/iteration.rs index eac1d4abe6..c0ce093ebb 100644 --- a/crates/js/src/iteration.rs +++ b/crates/js/src/iteration.rs @@ -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 { + 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; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 346f21eb58..1f2863ed2d 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -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)] diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 95719bf965..dc4a942d6c 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -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()]); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index be26fc5bca..7d1e74bc07 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -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", diff --git a/crates/pdf/src/import.rs b/crates/pdf/src/import.rs index b0d6ac3adf..29417779df 100644 --- a/crates/pdf/src/import.rs +++ b/crates/pdf/src/import.rs @@ -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::{ diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index 5163654842..0cfb8ea805 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -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) }, diff --git a/crates/pdf/src/import/cid.rs b/crates/pdf/src/import/cid.rs index 5b2747c6b3..e47726517c 100644 --- a/crates/pdf/src/import/cid.rs +++ b/crates/pdf/src/import/cid.rs @@ -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, diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index 1f62a7b380..11d18c2976 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -1020,19 +1020,26 @@ pub(crate) fn vertical_metrics(f: &Dict<'_>, embedded: bool) -> Option /// 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 = list.iter::().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::(); + 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 { +pub(crate) fn font_name(f: &Dict<'_>) -> Option { if f.get::>(b"Subtype").is_some_and(|s| s.as_ref() == b"Type3") { if let Some(base) = f.get::>(b"BaseFont") { return Some(String::from_utf8_lossy(base.as_ref()).into_owned()); diff --git a/crates/pdf/src/import_text.rs b/crates/pdf/src/import_text.rs index 436db268ce..b17680193b 100644 --- a/crates/pdf/src/import_text.rs +++ b/crates/pdf/src/import_text.rs @@ -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, 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); diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 9d05c726d9..7c97651d1d 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -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::{ diff --git a/crates/pdf/src/page_widths.rs b/crates/pdf/src/page_widths.rs new file mode 100644 index 0000000000..e5ea1bf796 --- /dev/null +++ b/crates/pdf/src/page_widths.rs @@ -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; + +/// 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>>, +} + +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> { + 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>, + /// The narrowest and widest width given each character of each font so far. + bounds: HashMap>, + /// The font dictionaries, form XObjects and resource dictionaries already looked at. + seen_fonts: HashSet<(usize, usize)>, + seen_forms: HashSet, + walked: HashSet<(usize, usize)>, + /// The `ToUnicode` maps parsed, by their stream: `None` for one that can't be read. + maps: HashMap>>, + /// 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>>, + cid_widths: HashMap>, + /// 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> { + 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>) -> Option> { + 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> { + let read = |w: &mut Self| w.width_array(f.get::>(b"Widths")).map(|a| a.iter::().take(256).collect::>()); + 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 { + let read = |w: &mut Self| { + let a = w.width_array(d.get::>(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>) -> 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>) -> 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::>(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::>(key.as_ref()) else { continue }; + let d = s.dict(); + let form = d.get::>(b"Subtype").is_some_and(|t| t.as_ref() == b"Form"); + if let (true, Some(own)) = (form, d.get::>(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::>(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::>(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::>(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::>(b"DescendantFonts").and_then(|a| a.iter::>().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::(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 { + /// 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 = 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> \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::>()); + 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 = (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 = (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 = (0..n).map(|i| format!("/F{i} {} 0 R", extra + 1 + i % 50)).collect(); + let objects: Vec = std::iter::once(format!("<< {} >>", entries.join(" "))) + .chain((0..50).map(|i| simple("TrueType", &format!("S{i}"), "WinAnsiEncoding", 65, "500"))) + .collect(); + let pages: Vec = + (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 = + (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 = (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> \nendcodespacerange\n1 beginbfrange\n<0000> <00FF> <0041>\nendbfrange\nendcmap\n"; + let fonts: Vec = (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 = (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 = (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 = (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> \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> \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 = 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 = + [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::>()); + 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> \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 = + ["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::>(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::>(); + 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> \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> \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 = + 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 = 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> \nendcodespacerange\n1 beginbfchar\n<0001> <0041>\nendbfchar\nendcmap\n".to_string(); + let mut big = String::from("begincmap\n1 begincodespacerange\n<0000> \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 = (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::>()), 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())); + } +} diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 988442a164..a742070d20 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -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() diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 2e05fca92b..2eece1125f 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -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 { 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 { /// 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 { 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 { } 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; diff --git a/crates/render/src/tests/changed.rs b/crates/render/src/tests/changed.rs index 4440c06baf..d97bfd7baf 100644 --- a/crates/render/src/tests/changed.rs +++ b/crates/render/src/tests/changed.rs @@ -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(); diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index e3905de6db..2f8b2b8cbe 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -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. diff --git a/crates/tools/src/three_point_arc.rs b/crates/tools/src/three_point_arc.rs index 60314cbe1f..994f60cef2 100644 --- a/crates/tools/src/three_point_arc.rs +++ b/crates/tools/src/three_point_arc.rs @@ -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, +} + +/// 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 { + 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 { + 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, end: Option, + /// The open path ends found under the first and the second end as each was placed. + open: [Option; 2], press: Option, /// Where the pointer is, snapped: the point the next press or release places. pointer: Option, + /// 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 { @@ -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)), } } diff --git a/crates/tools/src/three_point_arc/tests.rs b/crates/tools/src/three_point_arc/tests.rs index eaf269e974..1fa9451478 100644 --- a/crates/tools/src/three_point_arc/tests.rs +++ b/crates/tools/src/three_point_arc/tests.rs @@ -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] diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 03f69718b9..e58443e259 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -42,13 +42,24 @@ pub(crate) struct AddonDialogs { struct Open { id: DialogId, spec: &'static Spec, - document: Option, + /// 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); } diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index b7f648aa1e..679a2e2e34 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -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(); diff --git a/crates/ui-egui/src/addons/packaging/preview.rs b/crates/ui-egui/src/addons/packaging/preview.rs index 7fde5f2f4b..5af2119835 100644 --- a/crates/ui-egui/src/addons/packaging/preview.rs +++ b/crates/ui-egui/src/addons/packaging/preview.rs @@ -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); diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs index 63f7bcc3a3..5c729aae39 100644 --- a/crates/ui-egui/src/addons/packaging/preview/tests.rs +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -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"); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 83998cb77c..283c1bd6a8 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -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, diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 53c9664aec..89ccb1ae9c 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -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. diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 61f572a46c..6679ecf591 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -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. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3fc37f6433..8b7cabc0cb 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -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"); +} diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index af12608aa5..cc62cc3fe6 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -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 = 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 }) } diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index 2d47de4add..04173c2cf3 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -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, 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, 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")?, diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 0daecbd7c7..7e6fdf0952 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -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") } diff --git a/crates/ui-egui/src/dialogs/effect_params.rs b/crates/ui-egui/src/dialogs/effect_params.rs index 10028d3c4b..fc8fd14c9d 100644 --- a/crates/ui-egui/src/dialogs/effect_params.rs +++ b/crates/ui-egui/src/dialogs/effect_params.rs @@ -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", "レベル数")] { diff --git a/crates/ui-egui/src/dialogs/objects_on_path_options.rs b/crates/ui-egui/src/dialogs/objects_on_path_options.rs index cfc699334e..cd1eb96f98 100644 --- a/crates/ui-egui/src/dialogs/objects_on_path_options.rs +++ b/crates/ui-egui/src/dialogs/objects_on_path_options.rs @@ -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"] { diff --git a/crates/ui-egui/src/dialogs/perspective_grid.rs b/crates/ui-egui/src/dialogs/perspective_grid.rs index f899a9d7e9..9c3dfcb00e 100644 --- a/crates/ui-egui/src/dialogs/perspective_grid.rs +++ b/crates/ui-egui/src/dialogs/perspective_grid.rs @@ -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(ui: &mut egui::Ui, name: &str, salt: &str, entries: &[Entry], 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); } }); diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 3a69a42763..cafd0f6a12 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -223,7 +223,7 @@ fn resolution_row() -> Param { let entries: Vec> = 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(¤t).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; } diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 2d9c252ef3..a3acab8b0b 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -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, default: Option) -> Option { let entries: Vec> = 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 { diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index 6b73aed5f9..ceb96018f7 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -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); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index a2ca70446d..c7a85c3e0c 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -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() { diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index f11039d48a..1a1ce7db43 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -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); diff --git a/crates/ui-egui/src/dialogs/tests_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index ce286be347..9f6d312b8f 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -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(); diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 8c9f26bb1e..f461b3cfe2 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -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`. diff --git a/crates/ui-egui/src/dialogs/three_point_arc_options.rs b/crates/ui-egui/src/dialogs/three_point_arc_options.rs index 45f9546aa0..93facb987e 100644 --- a/crates/ui-egui/src/dialogs/three_point_arc_options.rs +++ b/crates/ui-egui/src/dialogs/three_point_arc_options.rs @@ -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(¶ms, m)).unwrap_or_default(); let (title, shown) = (tool_options::title(TOOL), params.clone()); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 1d6bc7a2a6..6b0aac8b1f 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -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", diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index c44c6dc8ba..8694052a3a 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -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}; diff --git a/crates/ui-egui/src/panels/actions/playback.rs b/crates/ui-egui/src/panels/actions/playback.rs index 50cab383e2..bff0bd1d4d 100644 --- a/crates/ui-egui/src/panels/actions/playback.rs +++ b/crates/ui-egui/src/panels/actions/playback.rs @@ -39,6 +39,72 @@ fn playback_steps(action: &Action) -> Vec { .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 = 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 diff --git a/crates/ui-egui/src/panels/actions/tests_playback.rs b/crates/ui-egui/src/panels/actions/tests_playback.rs index b6db1c5941..f566eb22fc 100644 --- a/crates/ui-egui/src/panels/actions/tests_playback.rs +++ b/crates/ui-egui/src/panels/actions/tests_playback.rs @@ -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::()); + 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::>(); + 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] diff --git a/crates/ui-egui/src/panels/layers/cells.rs b/crates/ui-egui/src/panels/layers/cells.rs index ce0de11247..d12f248bb4 100644 --- a/crates/ui-egui/src/panels/layers/cells.rs +++ b/crates/ui-egui/src/panels/layers/cells.rs @@ -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`. diff --git a/crates/ui-egui/src/panels/layers/model.rs b/crates/ui-egui/src/panels/layers/model.rs index 57345e5040..c73794b6d0 100644 --- a/crates/ui-egui/src/panels/layers/model.rs +++ b/crates/ui-egui/src/panels/layers/model.rs @@ -193,6 +193,9 @@ pub(super) struct LayerRows { /// and not empty. #[plain_data(assume = "node ids are integers")] full: HashSet, + /// The nodes that hold a selected object below them ([`super::rows::holding`]). + #[plain_data(assume = "node ids are integers")] + holding: HashSet, /// The selected blends, in selection order. #[plain_data(assume = "node ids are integers")] blends: Vec, @@ -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) -> Vec { diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index 8b1ca836fe..c7f140123c 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -150,6 +150,37 @@ pub(super) fn full_layers(doc: &Document, sel: &HashSet) -> HashSet = 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) -> HashSet { + /// 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, out: &mut HashSet) -> 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, diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 2cd61e7083..5eeca21a8e 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -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); +} diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index 96d558186a..691bd720fc 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -66,7 +66,7 @@ fn check(ui: &mut Ui, label: &'static str, on: bool, enabled: bool) -> Option( ui: &mut Ui, name: &str, @@ -82,7 +82,8 @@ fn pick( 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. diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index c253ba9747..f6b92fd209 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -237,6 +237,39 @@ fn a_drag_previews_and_records_one_undo_step_when_released() { assert_eq!(undo_len(&app), history + 1); } +/// A bevel shape highlighted with the arrow keys leaves the effect as it was, Escape closes the list with nothing +/// changed, and the shape chosen with Enter applies in one undo step. +#[test] +fn a_highlighted_bevel_shape_applies_only_once_it_is_chosen() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let mut app = app(); + set_type(&mut app, "extrude").unwrap(); + let mut panel = Panel::new(app, show); + let state = |panel: &Panel| { + let app = panel.app(); + (effect(&app).1, undo_len(&app)) + }; + let before = state(&panel); + panel.click_role("Bevel Shape", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + assert_eq!(state(&panel), before, "a highlighted bevel shape changes nothing"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(state(&panel), before, "Escape leaves the effect as it was"); + panel.click_role("Bevel Shape", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + let (params, undo) = state(&panel); + assert_ne!(params["bevel"], before.0["bevel"], "Enter applies the chosen bevel shape"); + assert_eq!(undo, before.1 + 1, "the choice is one undo step"); +} + #[test] fn a_change_reaches_each_selected_3d_effect_and_no_other_effect() { let mut app = app(); diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 75801d93fe..83434e98e7 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -102,9 +102,33 @@ impl Panel { self.look(name) } + /// The fixture's window in the latest frame: the room, or 800 by 600 points where the room is smaller. Dialogs and + /// menus open anywhere in it; the panel is laid out in the room. + fn window(&self) -> Rect { + self.ctx().content_rect() + } + + /// `target`, the control named `name`, once its center is in the window: a pointer aimed at a center outside the + /// window reaches no control. + fn aim(&self, name: &str, target: Target) -> Target { + let window = self.window(); + assert!( + window.contains(target.center()), + "{name:?} at {:?} has its center outside the window {window:?}, so a pointer aimed at it reaches no control", + target.rect + ); + target + } + + /// [`Panel::find`], then [`Panel::aim`]. + fn find_aimed(&mut self, name: &str) -> Target { + let target = self.find(name); + self.aim(name, target) + } + /// Clicks the control named `name`. pub(crate) fn click(&mut self, name: &str) { - let target = self.find(name); + let target = self.find_aimed(name); self.fixture.click(&target); self.after(); } @@ -114,6 +138,7 @@ impl Panel { let tree = self.fixture.tree(); let item = self.fixture.by_role(craft::ui::contract::Role::MENU_ITEM).into_iter().find(|t| tree.name_of(t.node) == Some(name)); let item = item.unwrap_or_else(|| panic!("no menu item {name:?} in {:?}", self.names())); + let item = self.aim(name, item); self.fixture.click(&item); self.after(); } @@ -135,7 +160,7 @@ impl Panel { /// [`Panel::click_role`] with `mods` held. pub(crate) fn click_role_with(&mut self, name: &str, role: craft::ui::contract::Role, mods: Modifiers) { self.frame(); - let target = self.look_role(name, role); + let target = self.aim(name, self.look_role(name, role)); self.fixture.hold(mods).click(&target).hold(Modifiers::NONE); self.after(); } @@ -149,6 +174,7 @@ impl Panel { self.fixture.by_role(role).into_iter().filter(|t| tree.name_of(t.node) == Some(name)).nth(index) }; let target = target.unwrap_or_else(|| panic!("no {role:?} named {name:?} at {index} in {:?}", self.names())); + let target = self.aim(name, target); self.fixture.click(&target); self.after(); } @@ -169,7 +195,7 @@ impl Panel { /// Clicks the control named `name` with `mods` held. pub(crate) fn click_with(&mut self, name: &str, mods: Modifiers) { - let target = self.find(name); + let target = self.find_aimed(name); self.fixture.hold(mods).click(&target).hold(Modifiers::NONE); self.after(); } @@ -187,7 +213,7 @@ impl Panel { /// Presses on the control named `name` and keeps the button down until [`Panel::release`]. pub(crate) fn press(&mut self, name: &str) { - let target = self.find(name); + let target = self.find_aimed(name); self.fixture.press(&target); self.after(); } @@ -196,7 +222,7 @@ impl Panel { /// the name (a slider beside its number box). pub(crate) fn drag_hold_role(&mut self, name: &str, role: craft::ui::contract::Role, by: Vec2) { self.frame(); - let from = self.look_role(name, role).center(); + let from = self.aim(name, self.look_role(name, role)).center(); self.drag_hold_between(from, from + by); } @@ -234,7 +260,7 @@ impl Panel { .into_iter() .flat_map(|role| self.fixture.by_role(role)) .find(|t| tree.name_of(t.node) == Some(name)); - typed.unwrap_or_else(|| self.look(name)) + self.aim(name, typed.unwrap_or_else(|| self.look(name))) } /// Types `text` into the focused field. @@ -258,13 +284,13 @@ impl Panel { /// Drags from the control named `from` to the one named `to`. pub(crate) fn drag(&mut self, from: &str, to: &str, mods: Modifiers) { - let to = self.find(to).center(); + let to = self.find_aimed(to).center(); self.drag_to(from, to, mods); } /// Drags from the control named `from` and releases at `to`. pub(crate) fn drag_to(&mut self, from: &str, to: Pos2, mods: Modifiers) { - let from = self.find(from).center(); + let from = self.find_aimed(from).center(); self.drag_between(from, to, mods); } @@ -278,7 +304,8 @@ impl Panel { /// Clicks the pointer-only part `part` (a row's thumbnail, a step arrow) of the control named `name`. pub(crate) fn click_part(&mut self, name: &str, part: impl Into, mods: Modifiers) { let (target, part) = (self.find(name), part.into()); - let at = part_rect_of_node(self.ctx(), target.node.into(), part).unwrap_or_else(|| panic!("{name:?} has no part {part:?}")).center(); + let rect = part_rect_of_node(self.ctx(), target.node.into(), part).unwrap_or_else(|| panic!("{name:?} has no part {part:?}")); + let at = self.aim(&format!("{name}'s part {part:?}"), Target { node: target.node, rect }).center(); self.fixture.hold(mods).click_at(at).hold(Modifiers::NONE); self.after(); } @@ -291,21 +318,21 @@ impl Panel { /// Two clicks on the control named `name`, close enough in time to be a double click. pub(crate) fn double_click(&mut self, name: &str) { - let target = self.find(name); + let target = self.find_aimed(name); self.fixture.click(&target).click(&target); self.after(); } /// A right click on the control named `name`. pub(crate) fn secondary_click(&mut self, name: &str) { - let at = self.find(name).center(); + let at = self.find_aimed(name).center(); self.secondary_click_at(at); } /// Right-clicks the zero-based control of `role`, including rows with identical names. pub(crate) fn secondary_click_nth(&mut self, role: craft::ui::contract::Role, index: usize) { self.frame(); - let at = self.look_nth(role, index).center(); + let at = self.aim(&format!("{role:?} at {index}"), self.look_nth(role, index)).center(); self.secondary_click_at(at); } @@ -337,9 +364,11 @@ impl Panel { tree.keys().into_iter().any(|key| tree.role_of(key) == Some(Role::STATUS) && tree.name_of(key) == Some(text)) } - /// Whether some of the control named `name` can be seen in the latest frame. + /// Whether some of the control named `name` can be seen in the latest frame: inside its arena's clip and inside the + /// window. pub(crate) fn in_view(&self, name: &str) -> bool { - self.fixture.visible(&self.look(name)).is_some() + let seen = self.fixture.visible(&self.look(name)).map(|t| t.rect.intersect(self.window())); + seen.is_some_and(|r| r.width() >= 0.0 && r.height() >= 0.0) } /// Whether the control named `name` takes input. @@ -550,3 +579,46 @@ pub(crate) fn floated(mut app: VectorcraftApp, panel: &str, lang: &str, place: P } Shown { body, nodes, names } } + +#[cfg(test)] +mod tests { + use std::panic::{AssertUnwindSafe, catch_unwind}; + + use craft::ui::buttons::Button; + use craft::ui::contract::Show as _; + use egui::{Pos2, Rect, Ui, vec2}; + use vectorcraft_engine::Session; + + use super::{Panel, ROOM}; + use crate::VectorcraftApp; + + /// A button at the top of the room and one a room's height below it, past the bottom of the window. + fn show(_: &mut VectorcraftApp, ui: &mut Ui) { + Button::new("Above").show(ui); + ui.allocate_space(vec2(100.0, ROOM.y)); + Button::new("Below").show(ui); + } + + /// The message of the panic `drive` ends with, or `None` when it returns. + fn panic_of(drive: impl FnOnce()) -> Option { + let payload = catch_unwind(AssertUnwindSafe(drive)).err()?; + payload.downcast_ref::().cloned().or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned())) + } + + #[test] + fn a_control_below_the_window_is_out_of_view_and_cannot_be_clicked_or_pressed() { + let mut panel = Panel::new(VectorcraftApp::new(Session::new(), Default::default()), show); + // The fixture's window is as tall as the room and at least 800 points wide. + let window = Rect::from_min_size(Pos2::ZERO, ROOM.max(vec2(800.0, 600.0))); + let below = panel.rect("Below"); + assert!(below.top() > window.bottom(), "the button is drawn below the window {window:?}: {below:?}"); + assert!(panel.in_view("Above"), "the button at the top is in view"); + assert!(!panel.in_view("Below"), "the button below the window is out of view: {below:?}"); + assert_eq!(panic_of(|| panel.click("Above")), None, "the button at the top takes a click"); + for (driver, message) in [("click", panic_of(|| panel.click("Below"))), ("press", panic_of(|| panel.press("Below")))] { + let message = message.unwrap_or_else(|| panic!("{driver} on the button below the window went ahead")); + let expected = format!("\"Below\" at {below:?} has its center outside the window {window:?}"); + assert!(message.starts_with(&expected), "{driver} fails naming the control, its rect and the window: {message}"); + } + } +} diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index e69a40c670..403e20faea 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -290,6 +290,27 @@ fn quitting_while_a_handler_runs_keeps_the_events_still_queued() { assert_eq!(log(&app), json!([[1, "Ann!"]])); } +#[test] +fn a_question_open_over_the_dialog_keeps_its_queued_click_until_it_is_answered() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + with_window(&app, |d| d.queue(&UiEvent::Click(3))).unwrap(); + crate::dialogs::script_run::ask_to_close(&mut app); + assert!(is_open::(&app)); + for _ in 0..3 { + pump(&mut app); + script_runs::poll(&mut app); + } + assert!(matches!(queued(&app).as_slice(), [Queued::Click(_)]), "the click waits under the question"); + assert!(app.session.script_window().is_some(), "the run still waits at the dialog"); + cancel_close_question(&mut app); + assert!(until_window(&mut app), "the dialog shows again"); + step(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([1])); +} + #[test] fn a_click_from_ui_dialog_confirm_gives_the_typed_text_first() { let mut app = app(); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 9a3c6c2139..be89cd34c1 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -645,7 +645,9 @@ pub fn control_bar_options(app: &mut VectorcraftApp, ui: &mut Ui) { let entries: Vec> = choices.iter().map(|&(value, name)| Entry::new(value, tl!(name))).collect(); let current = opts[key].as_str().and_then(|v| choices.iter().find(|(value, _)| *value == v)).map(|(value, _)| *value); let picked = Field::new(tl!(label)) - .show(ui, |ui, _| Select::new(tl!(label), Bind::given(current.map_or(Mixed::Mixed, Mixed::Same)), &entries).show(ui).value().copied()) + .show(ui, |ui, _| { + Select::new(tl!(label), Bind::given(current.map_or(Mixed::Mixed, Mixed::Same)), &entries).show(ui).events.committed().copied() + }) .inner .flatten(); if let Some(value) = picked { @@ -691,7 +693,7 @@ fn crop_options(app: &mut VectorcraftApp, ui: &mut Ui) { let label = |v: f64| crate::i18n::fmt(tl!("{n} ppi"), &[("n", &format!("{}", (v * 100.0).round() / 100.0))]); let choices: Vec> = PPI_CHOICES.iter().map(|&v| Entry::new(v, label(v)).enabled(v <= max + 1e-6)).collect(); Field::new(tl!("PPI")).show(ui, |ui, _| { - if let Some(v) = Select::new(tl!("PPI"), Bind::given(ppi), &choices).placeholder(label(ppi)).show(ui).value().copied() { + if let Some(v) = Select::new(tl!("PPI"), Bind::given(ppi), &choices).placeholder(label(ppi)).show(ui).events.committed().copied() { edits.push(("ppi", json!(v))); } // An image's own resolution above the limit (a linked image's, or one past 2400 ppi) still diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 243cde1c7f..5671cbe62e 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -508,6 +508,60 @@ fn a_tool_card_shows_what_the_tool_does_and_what_its_keys_do() { assert!(!card::Cards::new(&app).has(&"selection".to_string()), "tool tips off: no card"); } +/// The Control bar's lists of the Mirror & Cut tool (Axis, Keep) and of Crop Image (PPI): an entry highlighted with the +/// arrow keys leaves the tool's options as they were, Escape closes the list with nothing changed, and the entry +/// chosen with Enter sets the option without touching the drawing. +#[test] +fn a_highlighted_control_bar_option_applies_only_once_it_is_chosen() { + use craft::ui::contract::Role as Kind; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let png = vectorcraft_testkit::temp_dir("toolbar-crop-ppi").join("red.png"); + let image = craft_image_codecs::Image::from_raw( + 40, + 40, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [200u8, 40, 40, 255].repeat(40 * 40), + ) + .unwrap(); + let encoded = craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + std::fs::write(&png, encoded).unwrap(); + for (tool, name, key) in [("mirrorCut", "Axis:", "axis"), ("mirrorCut", "Keep:", "keep"), (vectorcraft_tools::cropimage::ID, "PPI", "ppi")] { + let mut app = app_with(300, 300); + if tool == vectorcraft_tools::cropimage::ID { + app.run("file.place", json!({"path": png, "link": true, "at": [100.0, 100.0]})).unwrap(); + app.run("ui.cropImage", json!({})).unwrap(); + } else { + app.run("tool.select", json!({ "tool": tool })).unwrap(); + } + assert_eq!(app.session.tool_id(), tool); + let mut panel = Panel::new(app, control_bar_options); + let state = |panel: &Panel| { + let app = panel.app(); + let st = app.session.active().unwrap(); + (app.session.tool_options()[key].clone(), st.doc.clone(), st.history.undo.len()) + }; + let before = state(&panel); + panel.click_role(name, Kind::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + assert_eq!(state(&panel), before, "a highlighted {name} entry changes no option"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(state(&panel), before, "Escape leaves {name} as it was"); + panel.click_role(name, Kind::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + let (option, doc, undo) = state(&panel); + assert_ne!(option, before.0, "Enter sets {name}"); + assert_eq!((doc, undo), (before.1, before.2), "{name} only changes the tool's options"); + } +} + #[test] fn the_rail_builds_its_slots_only_when_its_tool_groups_change() { let mut app = app_with(300, 300); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 9547365394..a22db526d1 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (EPS import: images over 67 million pixels are read at a lower resolution; `.ai` import: a stroke's arrowheads, the symbols its style names, come in as custom arrowheads with their tip on, or past, the path's end, as the drawn art places it, and the line stopping where the symbol's sample of it ends, #8188; PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group instead of reading as nested clipping groups that clip nothing or stop the editing data from being read; previously: PDF import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF export writes the document language as the catalog's `/Lang`, #3644; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (`.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where several copies share its PostScript name, follows #6983; scores and estimates unchanged; previously: EPS import: images over 67 million pixels are read at a lower resolution; `.ai` import: a stroke's arrowheads, the symbols its style names, come in as custom arrowheads with their tip on, or past, the path's end, as the drawn art places it, and the line stopping where the symbol's sample of it ends, #8188; PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group instead of reading as nested clipping groups that clip nothing or stop the editing data from being read; previously: PDF import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF export writes the document language as the catalog's `/Lang`, #3644; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) > > **File-font integration status (2026-11-19, #4569):** 56 focused PDF/native-reopen, file-font, stroked-text and font-binding tests passed on the current-main integration candidate. Full workspace CI and hardening paths outside those suites remain pending. Scores and estimates unchanged. > @@ -99,7 +99,7 @@ private editing data. VectorCraft: an art style of one paint, and the pattern is in that style (its colour in the text document is black). A pattern the file doesn't define, or a style that isn't a pattern, keeps the colour as before. Type set in a spot ink or a global process colour keeps it, at its tint: that style holds the ink's name and tint (the text document keeps only its process values), and - the type is linked to the document's swatch of that name, the one art in the same ink is linked to. Type keeps its manual kerning (key 8 of a story's text, thousandths of an em after a character). Its font is an installed face of the PostScript name its font record gives: one of exactly that name, case and punctuation included (`SampleSans` isn't the face named `SAMPLESANS`, nor `SampleSerif-Bold` the one named `SampleSerifBold`), when one is installed, else one whose name differs only in them. The type takes that face's own family and style, not another family spelled alike (`SAMPLE INK` beside `Sample/Ink`, whose PostScript name is `SampleInk`). Among those faces the record's version (key 5, name ID 5) picks the one in that version when it is installed; a version that isn't installed gives the first, without a note. The type names the face's version when its family and style alone resolve to another installed copy. Copies that share their family, style and version (an OpenType and a TrueType build of one release) can't be told apart: only the first of them loads. Type that a PostScript program sets, and legacy `.ai` type, take the face of their font's name the same way, with no version to read. Area type of one + the type is linked to the document's swatch of that name, the one art in the same ink is linked to. Type keeps its manual kerning (key 8 of a story's text, thousandths of an em after a character). Its font is an installed face of the PostScript name its font record gives: one of exactly that name, case and punctuation included (`SampleSans` isn't the face named `SAMPLESANS`, nor `SampleSerif-Bold` the one named `SampleSerifBold`), when one is installed, else one whose name differs only in them. The type takes that face's own family and style, not another family spelled alike (`SAMPLE INK` beside `Sample/Ink`, whose PostScript name is `SampleInk`). Among those faces the record's version (key 5, name ID 5) picks the one in that version when it is installed; a version that isn't installed gives the first, without a note. A record that keeps no version, in a `.ai` with a PDF part, takes among those faces the first that sets the characters the PDF part draws in that font (the first 512 in code-point order) each within 1/1000 em of the width the PDF part gives it (its `Widths` or `W`, each code's character from the font's `ToUnicode` map or, for a simple font without one, `WinAnsiEncoding`): two copies can share a name, family and style and set the type at other widths (two releases of one font). Without such widths, or with no face that sets them all, it takes the first, as before. The type names the face's version when its family and style alone resolve to another installed copy. Copies that share their family, style and version (an OpenType and a TrueType build of one release) can't be told apart: only the first of them loads. Type that a PostScript program sets, and legacy `.ai` type, take the face of their font's name the same way, with no version to read. Area type of one frame whose last lines the file sets but which don't fit here (the fallback font, or a descent past the frame's bottom) may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines, with a warning when it does. RGB in the PDF page's `ICCBased` spaces keeps the file's numbers in a `.ai` (the `uncalibrated_rgb` @@ -437,6 +437,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | 2026-11-18 | minor | PDF export (#3644): the document language chosen in Document Setup is written as the catalog's `/Lang` (BCP 47, `en-US` by default) and as XMP `dc:language`; a language without a tag writes none. Scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | +| 2026-11-16 | minor | `.ai` import: type from the text document whose font record keeps no version (no key 5), where several installed faces answer to the record's PostScript name, is set in the one whose advances match the widths the file's PDF part gives the characters it draws in that font: the case #6983 left out, two copies of one PostScript name, family and style (two releases of one font) that differ only in their widths. The PDF part's fonts are read from their dictionaries alone, without importing its pages (`Opened::page_widths`, which looks into the forms they draw too): a simple font's `Widths` from its `FirstChar`, a composite font's descendant's `W` under an `Identity-H` or `Identity-V` CMap, each code's character from the font's `ToUnicode` map or, for a simple font without one, `WinAnsiEncoding` (ISO 32000-1 §9.6.2, §9.7.4.3, §9.10.3, Annex D.2), by `BaseFont` without its subset prefix. A code 0 wide is one the subset doesn't use and is left out; a font whose subsets give one character two widths gives none. Each resource dictionary is walked once, though pages and forms share it, and at most 65,536 of their entries (for the whole file, all pages together), 256 fonts and 4,096 forms are looked at; a width array that fonts share by reference is read once, and no more are read past 4 MB of them; a `ToUnicode` map is parsed once for all the fonts that name it, and one longer than 256 KB decoded, or past 4 MB of maps in all (each charged at most what could be decoded of it), is left unread. All the records of one font share its widths and the face they resolve to, so a text document of many records of one font holds one copy of them. Of the faces `postscript_face` finds for the name, the first that sets those characters (the first 512 of them in code-point order) each within 1/1000 em of its width takes the type, and the type names its version as before. With no widths for the font, one face, a version in the record (installed or not), or no face that sets them all, the face is the one taken before; each record is still resolved once. It applies whether the layers open alone, with the PDF part imported, or from the editing data alone beside a PDF part that is only type; a `.ai` saved without its PDF part, EPS and legacy `.ai` are unchanged. On 224 users' files (used locally, never committed), 332 font records have widths to compare: 299 already took a face that sets every character within 1/1000 em, 29 have none that does and keep their face, 1 keeps the version its record names, and 3 (one font installed in two releases, in 3 files) change copy, from up to 66/1000 em off the page to within 0.5/1000 em. Those 3 renders at 40 ppi, and no others, change, all closer to the file's own page (30.0% → 24.5%, 18.0% → 12.3% and 1.03% → 0.02% of the page differing; in the first two only that font's type changes, and the rest that differs is untouched); envelopes of type that open live go from 185 to 186, none fewer in any file; no file opens another way; in one file the note on type in an envelope gives way to the note of how far the layers differ from the page (0.2%), as its envelope now opens live. Tests: `page_widths::tests::the_pages_give_each_font_the_widths_of_its_characters`, `shared_resources_are_walked_once`, `fonts_past_the_most_read_are_not_looked_at`, `a_to_unicode_map_is_read_once_and_only_up_to_its_limit`, `a_long_plain_map_leaves_the_others_read`, `a_width_array_fonts_share_is_read_once`, `width_arrays_past_the_most_read_are_left`, `cid_ranges_give_each_cid_its_values` (`vectorcraft-pdf`), `tests_native::type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths`, `ate::tests::records_of_one_font_share_its_page_widths_and_answer` (`vectorcraft-eps`), `tests_aiimport::type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in`, `type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save`, and the fuzz target `import_fuzz::pdf_font_widths_never_panic` (`vectorcraft-engine`). Scores unchanged. | | 2026-11-16 | minor | `.ai` and EPS import (#8200): a path whose Art brush colors its art with Tints, its stroke a color linked to a swatch (a spot color, for example), comes in brushed instead of as its drawn look. Tints of a stroke color linked to a swatch are now tints of that swatch, linked to it (`vectorcraft_brush::colorize`): each piece is the swatch at the stroke's tint times how dark the art is there, and shows the same color as before (except a Lab swatch, whose tints now go toward L 100 as swatch tints do, not toward RGB white); before, the pieces were unlinked process colors, so the reader kept the look rather than lose the ink (0c570dee8, #5967). This also holds for Art, Scatter and Pattern brushes in Tints drawn in VectorCraft. In 200 garment files we own (used locally, never committed), 33 objects in 5 files no longer come in as their drawn look, and in another 224, 31 in 1 file; of 3 renders compared with their page, 2 move away from it (0.614% to 0.699%, 0.187% to 0.203%; the brush drawn by VectorCraft instead of the look, at most 0.084% of the render past the threshold). Tests `tints_of_a_swatch_stay_linked_to_it` in `crates/brush/src/tests.rs` and `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`. Scores and estimates unchanged. | | 2026-11-16 | minor | `.ai` and EPS import (#8128): clipping paths grouped in a compound path (`*u u W n … U *U`, possibly nested in other groups) are the compound path's subpaths, as its other grouped paths are (#1410), so the compound clipping path, their union, clips its clipping group. Before, each such group came in as a clipping group of its own, its paths nested one level each as an intersection: the compound path clipped nothing, and with dozens of them the file's layers weren't read ("its clipping masks are nested too deeply") and it opened as its PDF part. A group of clipping paths elsewhere is read as before (test `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`). | | 2026-11-16 | minor | `.ai` and EPS import: a path or compound path whose art style fills it with a pattern (alone, or among other fills and strokes) comes in as itself with that pattern fill instead of its drawn look (#8239). As for a stack's gradients, the pattern is taken only where the drawn look fills with it, once, and is placed as the look places it (type keeps taking its style's pattern from wherever its look paints with it, as before); a stack that fills with one pattern twice, or whose look doesn't fill with the pattern, keeps the drawn look. Under effects on the object a stack with a pattern fill keeps the drawn look too, a conservative rule: in one garment file a Scribble over such a fill drew unlike the look though the tiles were placed as the look's are, for a reason not established. In 200 garment files we own (used locally, never committed), 5 files have paths or compound paths under such styles: 11 objects in 3 files no longer come in as their drawn look; one file is held back by the effects rule; in one, the objects' styles aren't stacks for another reason, not looked into. One render changes, by 0.003% of its pixels, none past the threshold (why wasn't looked into). In another 224 garment files, nothing changes. Tests `a_path_with_a_style_pattern_fill_comes_in_as_the_path_with_it`, `a_style_pattern_fill_the_look_doesnt_paint_keeps_the_drawn_look`, `a_stack_with_one_pattern_twice_keeps_the_drawn_look`, `a_look_placing_a_stacks_pattern_twice_keeps_the_drawn_look`, `a_path_with_a_style_pattern_fill_under_an_effect_keeps_its_drawn_look` and `type_with_a_style_pattern_fill_takes_a_stroke_only_looks_placement` in `crates/eps/src/import/ai/tests.rs`. Scores and estimates unchanged. | diff --git a/docs/gaps.md b/docs/gaps.md index 29e201af55..51775cc460 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -846,11 +846,11 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, stories and threads - of type, and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open +- **Missing:** the rest of the document object model for scripts (layers, artboards, paths and the other classes) + and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames with their text ranges and - character and paragraph attributes, the installed fonts, and each document's variables, data sets and variable - libraries. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + character and paragraph attributes, their links to each other and the stories they form, the installed fonts, and + each document's variables, data sets and variable libraries. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index f921c8acad..5e9523396d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -885,7 +885,7 @@ from −100 to 100 and is 50 when left out with `lengthX` and `lengthY`, or 100 `` `baseAlong` must be one of x, y ``), as is a `slope` outside its range; the arc is not drawn and no undo step is added. -`shape.threePointArc {start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: "start"|"end"}` draws an +`shape.threePointArc {start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: "start"|"end", join?: bool}` draws an open circular arc from `start` to `end` and selects it. With `through`, the arc passes through that point. With `toward`, the arc leaves `start` heading toward that point, so the line from `start` to the point is the arc's tangent there. With `at: "end"`, the line from `end` to the point is the tangent at `end` instead. `at` is `"start"` when left @@ -898,14 +898,31 @@ when the third point lies on the line through the ends, when the arc would reach `[x, y]`, when both or neither of `through` and `toward` are given, when `at` is anything but `"start"` or `"end"`, and when `at` is given with `through`. +With `join: true`, an end of the arc that lies on an end of an open subpath of an editable path (not a guide, and in +isolation mode inside the isolated group) joins the arc to that path, as the published arc tool documentation describes for arcs started or ended on an open path's end +(https://docs.astutegraphics.com/subscribe/arc-by-points-tool/arc-by-points-preferences). When several open path ends +lie there, one in the selection comes first, then the last in paint order. The path keeps its look, and when one end +joins, its direction: the arc is added after the path's last anchor or before its first, and the anchor where they meet +is the path's own, with the handle on the arc's side taken from the arc. When the other end of the arc lies on an end of +another open path, that path is joined on as `path.join` joins two paths; when it lies on the other end of the +same subpath, the path closes. It is one undo step, the joined path (or its compound path) is selected, and the result +is `{id, cx, cy, radius, sweep, joined: true}` with `id` the joined path. With no open path end at either end, the arc +is drawn as a new path. A `join` that is not true or false is an error. + The Three-Point Arc tool, in the Line Segment tool's group after the Arc tool, runs this command. A drag from one end to the other, or a click on each, places the ends; Shift keeps the second end at 45° steps from the first (from General › Constrain Angle). A click on a third point, or a press dragged to it, then draws the arc through it. With the tool's `direction` option on, the third point gives the direction the arc leaves the first end in; with `mods.alt`, the direction is at the second end, and Shift keeps the direction at 45° steps. Three-Point Arc Tool Options (`tool.options`, or a double-click on the tool) sets `direction` with its Third Point Sets Direction box, and -`]` (with or without Shift) switches it while the ends are placed; the option is saved with the preferences. Until the -third point is placed, the tool shows the arc as a dashed outline, its center as a small cross, the direction line in +`]` (with or without Shift) switches it while the ends are placed; the option is saved with the preferences. The +`join` option (Join to Open Path Ends in Tool Options, off by default; J switches it while the ends are placed) makes an +end placed within 5 screen points of an end of an open path land on that end (the nearest one, picked among ends equally +near as the command picks), and the tool then runs the command with +`join: true`. The `tangentSnap` option (Snap Where the Arc Continues a Path, on by default) works in direction mode: +when the direction line starts on an end of an open path, a third point within 5 screen points of the line along which +the arc carries the path on, the same way or turned back, snaps onto it, and the tool shows that line dashed. Shift +keeps the direction at 45° steps instead. Until the third point is placed, the tool shows the arc as a dashed outline, its center as a small cross, the direction line in direction mode and, with Measurement Labels on, the radius. Where no arc fits, the tool shows "Arc too large" by the pointer (nothing while the pointer is on an end), and a click there draws nothing and keeps the ends. Escape, and an edit, Undo or Redo made outside the tool, remove the ends. @@ -2935,7 +2952,12 @@ other files through `$`: [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) shows. A read with a name that nothing has, a name the collection class lacks as a member included, throws `Not found`; `"name" in pageItems` is false then, and assigning to such a name throws `Not found` too - (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` and `note` + (VectorCraft's own rule). A read with the text of a number that is not an array index, such as + `pageItems["-1"]`, `pageItems[1.5]` or `documents["NaN"]`, looks for an object of that name and gives `undefined` + when nothing has it; assigning to such a name is then ignored outside strict mode and throws a `TypeError` in + strict mode code or with `#strict on`, instead of `Not found`. This applies only to the text JavaScript writes for that number: `pageItems["1.50"]` is a + plain name and throws `Not found` when nothing has it. `"-1" in pageItems` is true when an object has that name; `index(key)` takes a number as + a position only (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` and `note` take a number or a Boolean as the text `String(value)` gives. `String(object)` gives `[PathItem Logo]` for a page item named `Logo` (`[PathItem ]` with no name), `[Document ]`, `[Layer ]`, `[Application]` and `[PageItems]` (VectorCraft's own rule). @@ -2975,7 +2997,7 @@ other files through `$`: other properties but not the methods. `Object.keys`, `Object.getOwnPropertyNames` and `Object.getOwnPropertyDescriptor` do not report any member of the class. Assigning a member that a page item, a layer, a document or the application does not have does not keep the value; it does not throw, except in - strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, as described above. Other members + strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, except for the text of a number that is not an array index, as described above. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. - `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type @@ -2983,8 +3005,8 @@ other files through `$`: `removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation` - value; a `startTValue`, `endTValue`, `baseFrame` or `postFix` that is given throws an error that says it is not - available yet. A `TextFrame` + value; a `startTValue` or `endTValue` that is given throws an error that says it is not available yet, and + `baseFrame` and `postFix` thread the new frame as the threaded-type paragraph below describes. A `TextFrame` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`, `AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`, `createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to @@ -3036,9 +3058,36 @@ other files through `$`: `addBefore` before its first; with one, a text range or the text frame of the same frame, `PLACEBEFORE` and `PLACEATBEGINNING` insert at its start and `PLACEAFTER`, `PLACEATEND` or no location at its end. An added word is kept apart from the characters next to it by a space, and an added paragraph by a paragraph break; adding an empty - string runs no command. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` - and `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`, - `characterOffset` and `orientation` cannot be set yet. + string runs no command. Members the help pages list that are not here, such as `TextFrame.lines`, + `TextFrame.textPath` and `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, + `end`, `characterOffset` and `orientation` cannot be set yet. +- Threaded type (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, + https://ai-scripting.docsforadobe.dev/jsobjref/Story/, https://ai-scripting.docsforadobe.dev/jsobjref/Stories/): a + `TextFrame` has `nextFrame` and `previousFrame`, the frames after and before it in its story (`null` at either end), + and `story`; a `TextRange` has `story` too. Assigning `nextFrame` or `previousFrame` runs `text.thread.setNeighbor`: + a frame links the last frame of one story to the first frame of another, whose text flows on after the first story's + text, and `null` breaks that link, no text moving across it. `areaText(path, orientation?, baseFrame?, + postFix?)` and `pathText(path, startTValue?, endTValue?, orientation?, baseFrame?, postFix?)` thread the new frame + after `baseFrame`, or before it when `postFix` is false, with `text.thread.add`; `startTValue` and `endTValue` are + not available yet. `Document.stories` lists the stories with `length`, `[i]` and `index(key)`. A `Story` has + `parent` (its document), `length`, `textFrames` (an array of its frames in thread order), `textRange`, `characters`, + `words` and `paragraphs`; `lines`, `insertionPoints`, `textRanges` and `textSelection` are not available yet. + VectorCraft's own rules: point type, a frame of another document, the frame itself, a frame inside a story, a link + that would make a loop and a story with a hidden or locked frame are refused with nothing changed, and assigning the + link that is already there, or `null` where there is none, runs no command. `postFix` is true when it is left out, + and a `baseFrame` given with a path inside a compound path is refused before the path is turned into type. + `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, and `index` with a string finds the first story whose first frame has that name. A frame that + a stored thread lists twice is in its story once. A `Story` is + the story of the frame it was read from, as that frame is threaded now, and throws `Stale story` once that frame is + deleted. The text of a story of one frame is that frame's text, with its ranges. The text of a longer story is its + frames' text in thread order, counted in UTF-16 units: its `textRange` reads and writes across the frames, and + writing it edits the frames from the last one it reaches back to the first, inside the run's one undo step, and the + story then flows through its frames again. Such a range has `contents`, `start`, `end`, `characterOffset`, + `length`, `parent` and `story` (its story), `characters`, `words`, `paragraphs`, `getParagraphLength()` and + `remove()`; its character and paragraph attributes and the other members are not available yet. It keeps its place + through edits made through the story's ranges and throws `Stale text range` after any other change to the story's + text and after `file.revert`. - A `Document` also has `variables`, `dataSets`, `activeDataset`, `variablesLocked`, `importVariables(file)` and `exportVariables(file)` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). `variables` (https://ai-scripting.docsforadobe.dev/jsobjref/Variables/) and `dataSets` @@ -3062,6 +3111,29 @@ other files through `$`: `importVariables` and `exportVariables` take a `File`, not a path, which must be a file the script may read, or write, through its `File` objects; the files of the open documents do not count. A value that changes nothing runs no command. +- `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method + of the scripting reference + https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf + describes it, and returns `undefined` once every step has run. The actions come from `script.run`'s `actions`; the + app passes the Actions panel's actions with their included steps, and a recorded `command.batch` step gives its own + steps. A step that acts on the active artboard (Paste in Place, in Front and in Back, Align, Distribute Objects and + Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to + Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run + started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one + past the end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to + Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that + names its `artboard` acts on that artboard, or the last one past the end, as `command.batch` gives it. VectorCraft's + own rules: the action and its set are matched by their exact names, and a name that matches no action or more than + one throws an error before any step runs, as does an action with no included step. A stop, and a step whose command a script may not run or the engine does not have + (a View menu step, or a step that plays an action or runs a script), throw an error that names the step before any + step runs, as does such a command among the commands a Batch step (`action.batch`) plays on each file, so an + action cannot play itself. + Each step then runs as `vc.run` runs a command: it joins the run's one undo step for each changed document, counts + as a host call, and reads and writes files only where the script may. A step that fails is put back and throws an + error that gives the step's place, the action's name and the step's command, and the steps before it stay done; an + uncaught error later puts them back with the rest of the run. `dialogs` must be `true` or `false` (default + `false`); no step opens a dialog, so it changes nothing. `app.loadAction` and `app.unloadAction` throw an error + that says they are not available yet when they are read or assigned. - `PageItem.tags` and `Document.tags` are `Tags` collections (https://ai-scripting.docsforadobe.dev/jsobjref/Tags/) with `typename`, `length`, `parent`, `[i]`, `index(key)`, `getByName(name)`, `add()` and `removeAll()`, and each `Tag` (https://ai-scripting.docsforadobe.dev/jsobjref/Tag/) has `typename`, `name`, `value`, `parent` (its page @@ -5857,6 +5929,11 @@ already walks Image Trace. Short agent entry points: for new art become no fill and a 0.5 pt black stroke; with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command. +For an existing brush, approving Brush Options without changing its trimmed name or options closes the dialog +without rewriting the brush, changing the document revision or adding Undo. An empty name is ignored and counts +as unchanged. A changed name or option is saved in +one step. A brush deleted while its dialog is open still gives an error on approval. + `brush.selectionArt {ids?|id?}` (a query) replies `{art}`: the object that `brush.new` given the same `ids` or `id`, or the same selection, takes as a new scatter or art brush's art and as a new pattern brush's side tile. Several objects become one group, and `art` is `null` when nothing is selected or `ids` name no object. In the app, the @@ -8029,8 +8106,10 @@ same way for a blend's spine point; without `handle` it is refused. These rules on one path or several, by the same offset as one undo step. An anchor with one handle listed places it as `path.setHandle` does, so a smooth anchor turns its other handle in line at its own length; an anchor with both handles listed moves both and becomes a corner. `independent: true` makes the anchor of every listed handle a corner and leaves -its other handle where it is. A handle listed twice moves once, and a move by 0, 0 that makes no anchor a corner leaves -the document as it is and records no undo step. An empty or missing `handles`, a `which` other than `"in"` or `"out"`, +its other handle where it is. A handle listed twice moves once. A move by 0, 0 changes only the anchors it makes corners, so a live +shape whose listed anchors need no change stays live, and a live shape with an anchor it makes a corner becomes a plain +path; when it makes no anchor a corner it leaves the document as it is +and records no undo step. An empty or missing `handles`, a `which` other than `"in"` or `"out"`, an object that is not a path, a missing subpath or anchor, a `dx` or `dy` that is missing, not a number or 1e9 pt or more in size, and an `independent` that is not true or false are refused, and the document does not change. With Direct Selection, a click on the end of a direction handle of a path picks that handle, a Shift-click adds it to the picked @@ -8839,9 +8918,12 @@ the corners where they are records none. Image info (`image.info`) gives a disto Info (`links.info`) gives its scale and rotation there. Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.makeAndExpand`) and Place with Replace -(`file.place` with `replace`) of anything but a text file refuse a -distorted image with an error that names the distortion; Place with Replace does not refuse a clipping group that holds -a distorted image of a DCS file's plates. Create Gradient Mesh (`object.mesh.create`) converts the other objects it is +(`file.place` with `replace`) of a file that is not text, a raster image or a DCS file refuse a distorted image with an error that names the distortion; Place with Replace does not +refuse a clipping group that holds a distorted image of a DCS file's plates. Place with Replace of a distorted image by +a raster image or a DCS file puts the new image's pixels between the old image's corners, in one undo step; the new +image's transform is the old one scaled to the new pixel size, the clipping path a PSD, PSB or DCS file names is +drawn through the corners, and each slice a PSD or PSB file brings in covers the box around its part of the pixels +where the corners put it. Create Gradient Mesh (`object.mesh.create`) converts the other objects it is given and lists each distorted image it leaves as it is in `skipped`, with its `id` and the error as `reason`; with nothing else to convert, it returns that error. Update Links (`links.update`) and Relink (`links.relink`) put the file's pixels between a distorted image's corners, without applying its Placement Options or @@ -12997,6 +13079,18 @@ after it (`out`). The whole story flows into the frames before the break; the fr threaded with each other when two or more remain, and the first of them starts a paragraph. It refuses an `id` that doesn't exist, a `port` other than `in` or `out`, and a side where no frame of a thread comes before or after `id`. +`text.thread.setNeighbor {id, side: "next" | "previous", neighbor: id | null}` is what a script's `nextFrame` and +`previousFrame` assignments run, and needs no selection. With an id it links area type or type on a path `id` to +`neighbor` after it (`next`) or before it (`previous`): `id` must be the last frame of its story for `next` (the first +for `previous`) and `neighbor` the first (the last) frame of another story, and the second story's text flows on after +the first's (one undo step, Thread Text). With `null` it breaks the link on that side, and the frames on each side +form a story of their own (one undo step, Break Thread): 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. It refuses point type and +other art, a frame linked to itself, a link that would make a loop or go to a frame inside a story, and a story with a +hidden or locked frame, with nothing changed. 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. It returns `{changed, threads}`, `threads` listing the +stories of the frames involved after the change, a story of one frame as `[id]`. + `select.same.linkBlockSeries` (Select › Same › Link Block Series) selects every frame of the threads that the selected type objects, and the type inside selected groups, are in, in thread order, and returns `{count}`. Type in no thread selects itself, and other selected objects are left out. With frames of several threads selected, it selects the frames @@ -17687,6 +17781,7 @@ the error text. The interactive fallback applies only to ordinary File > Save, n | Date | Change | |---|---| | 2026-11-27 | Existing 3D effect options: unchanged validated parameters preserve the stored effect, document revision and Undo, including defaults and equivalent numeric JSON. | +| 2026-11-27 | Brush Options: untouched approval preserves the brush, document revision and Undo; changed settings save in one step. Native UI and automation covered. Scores and estimates unchanged. | | 2026-11-27 | Shape Control bar: canceled numeric edits restore future-tool settings and coupled radii along with selected artwork; retired edits cannot overwrite a different tool. Native scrub, keyboard, next-shape and Undo cases covered. Scores and estimates unchanged. | | 2026-11-27 | Anchor Inspector: Cancel restores Corner radius/kind and Shared Edge diameter/coincidence tool values; accepted settings leave document history unchanged. Native numeric and menu cases covered. Scores and estimates unchanged. | | 2026-11-18 | Production Preflight: output and artboard scope, four check summaries, clickable canvas ids, effective PPI and explicit unchecked resolution coverage. | diff --git a/docs/roadmap.md b/docs/roadmap.md index 34626c5402..158326df56 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,7 +1,7 @@ # Roadmap: milestones and what's next > Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel row context menus, #8809; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (M4: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), #8087; scores and estimates unchanged; previously: G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel row context menus, #8809; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged. @@ -195,7 +195,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); View › Snapping consolidates five existing toggles and Pixel Snapping Options…, retaining top-level entries and shortcuts (G13); Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028; Recolor with Preset asks whether to limit the colors to a swatch library first); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); the stop editor offers the five Color panel modes (#7918); native port validation pending | 4–8 | -| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | +| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934), keeping even spacing as tracking and making stacked, aligned lines one area type object; Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | @@ -206,7 +206,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines and styles and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | @@ -273,6 +273,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | 2026-11-17 | minor | Image Trace Ignore Color: sample original source pixels without changing the canvas View; outside and transparent misses keep the pick armed, while valid picks and cancellation retain the existing tool and Preview behavior (#8068). Scores, gaps and hours unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | +| 2026-11-16 | minor | M4: `.ai` import (#8087, follows #6983): type from the text document whose font record keeps no version, where installed copies of one font differ only in their widths, is set in the copy that sets the characters at the widths the file's PDF part gives them, compared on its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before; details in [file-format-parity.md](file-format-parity.md). Scores and estimates unchanged. | | 2026-11-16 | minor | M4: `.ai` and EPS import (#8200): an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; details in [file-format-parity.md](file-format-parity.md). Scores and estimates unchanged. | | 2026-11-16 | minor | M4: `.ai` and EPS import (#8128): clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups; details in [file-format-parity.md](file-format-parity.md). Scores and estimates unchanged. | | 2026-11-16 | minor | M1: an Alt-drag in the Layers panel copies a row above or below its own place (`layer.move` with `copy` and that row as the target), so the top layer dragged up, the bottom layer dragged down and a document's only layer are copied (#8237). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f997ab13a6..81eaaa5b01 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3,7 +3,7 @@ Native saves on Unix flush the destination directory after writing or replacing a file. If the directory cannot be flushed, the save returns an error stating that the file was written. > Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Document Info Selection Only counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (`.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), follows #6983; scores and estimates unchanged; previously: Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Document Info Selection Only counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged. > @@ -149,6 +149,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-17 | minor | Distort & Transform › Twist: handles follow the rotation's derivative, so a strongly twisted path is a smooth spiral instead of pieces meeting at kinks (#7069; `twist_joins_its_pieces_smoothly` in `crates/effects/src/tests.rs`). Scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | +| 2026-11-16 | minor | `.ai` import: type from the text document whose font record keeps no version, where installed copies of one PostScript name, family and style differ only in their widths, is set in the copy that sets the characters the file's PDF part draws at the widths the PDF part gives them, read from its font dictionaries without importing its pages; the pick compares the first 512 characters, and without those widths, or with no copy that sets them all, it is the one before (follows #6983; details in [file-format-parity.md](file-format-parity.md); tests in `crates/pdf/src/page_widths.rs`, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`, `records_of_one_font_share_its_page_widths_and_answer` in `crates/eps/src/import/ate.rs`, `type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in` and `type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save` in `crates/engine/src/cmd/fileio/tests_aiimport.rs`, `pdf_font_widths_never_panic` in `crates/engine/tests/import_fuzz.rs`). Scores and estimates unchanged. | | 2026-11-16 | minor | `.ai` and EPS import (#8200): an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged (details in [file-format-parity.md](file-format-parity.md)). | | 2026-11-16 | minor | `.ai` and EPS import (#8128): clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups that clip nothing or, past the document's depth limit, stop the layers from being read; scores and estimates unchanged (details in [file-format-parity.md](file-format-parity.md); test `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`). | | 2026-11-16 | minor | `.ai` and EPS import: a path or compound path whose art style fills it with a pattern comes in with that pattern fill (#8239), placed as its drawn look fills with the pattern, once per pattern, not under effects on the object (a conservative rule); type keeps taking its style's pattern as before. Tests `a_path_with_a_style_pattern_fill_comes_in_as_the_path_with_it`, `a_style_pattern_fill_the_look_doesnt_paint_keeps_the_drawn_look`, `a_stack_with_one_pattern_twice_keeps_the_drawn_look`, `a_look_placing_a_stacks_pattern_twice_keeps_the_drawn_look`, `a_path_with_a_style_pattern_fill_under_an_effect_keeps_its_drawn_look` and `type_with_a_style_pattern_fill_takes_a_stroke_only_looks_placement` in `crates/eps/src/import/ai/tests.rs`. Scores and estimates unchanged. | @@ -367,9 +368,9 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers row menu commands beyond Collect for Export and menus on blend spine rows (guide row menus are done; click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs, and blends the `.ai` reader opens with their settings and as they are drawn, the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.; PDF type filled and stroked at less than full opacity comes in as a filled object and a stroked one (#8015) | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` and EPS import: a path whose Art brush colors its art with Tints of a stroke color linked to a swatch comes in brushed, its tints linked to the swatch (#8200, `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. `.ai` and EPS import: clipping paths grouped in a compound path are the compound path's subpaths, so the compound clipping path clips its clipping group instead of coming in as nested clipping groups (#8128, `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs`); score, gaps and hours unchanged. PDF import: type filled and stroked by one text-showing operator (rendering modes 2 and 6) comes in as one type object, filled and stroked, not a stroked copy over a filled one (#8015, `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`); not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one (`translucent_fill_and_stroke_text_stays_two_objects`); score and hours unchanged. PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543, `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`); score and hours unchanged. PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300, `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked` in `crates/pdf/src/tests/textstroke.rs`); score and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658) | 4–7 | estimated (lowered from 85%: target moved); View › Snapping groups five existing toggles and Pixel Snapping Options… (G13), retaining top-level commands and shortcuts; Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | @@ -632,7 +633,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, row menu commands beyond Collect for Export (now on every layer, sublayer, group, object and guide row), menus on blend spine rows, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | | Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already; a marquee leaves locked or hidden guide paths out inside groups too, #8538) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812; distance and angle labels while drawing, #2983) | 2–4; status-bar X/Y uses the active ruler origin and General units | -| File formats | 6 | 85% | `.ai` and EPS import: an Art brush in Tints of a swatch's color comes in brushed (#8200; scores and estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group (#8128; scores and estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; scores and estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one; scores and estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; scores and estimates unchanged); PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Legacy `.ai` files that name but omit their prolog open with their layers, or with their art on one layer when the format has no layers; graph data and settings in these files still come in only as drawn art. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) | +| File formats | 6 | 85% | `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (#8087, follows #6983; scores and estimates unchanged); `.ai` and EPS import: an Art brush in Tints of a swatch's color comes in brushed (#8200; scores and estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group (#8128; scores and estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; scores and estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one; scores and estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; scores and estimates unchanged); PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Legacy `.ai` files that name but omit their prolog open with their layers, or with their art on one layer when the format has no layers; graph data and settings in these files still come in only as drawn art. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) | | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done, as are the Japanese papers in its Media list: JIS B4/B5/B6, はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判, beside the ISO B4/B5 that settings saved before them keep) | 1–2 | | Automation | 3 | 65% | scripting surface, batch (MCP drops malformed app replies without replay; Variables: text/visibility variables bound to objects, an object may carry several, dataset rows applied in one undo step, panel and Window › Variables with dialogs; image/graph kinds and dataset import/export open) | 6–10 | @@ -682,6 +683,8 @@ since 2026-10-01. ## Evidence: what ships today, by area +- **`.ai` type in the copy its PDF part sets (#8087, follows #6983):** `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs` covers two installed copies of one font that differ only in their widths: type whose font record keeps no version is set in the copy that sets the characters at the widths the PDF part gives them. `records_of_one_font_share_its_page_widths_and_answer` in `crates/eps/src/import/ate.rs` checks that records of one font share those widths and the answer. The tests in `crates/pdf/src/page_widths.rs` cover reading the widths from the font dictionaries alone (simple and composite fonts, `ToUnicode` maps, `WinAnsiEncoding`, forms) within the file's bounds; a font whose subsets give a character widths more than 1/1000 em apart, or whose `ToUnicode` map can't be read, gives none. `type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in` and `type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save` in `crates/engine/src/cmd/fileio/tests_aiimport.rs` cover opening and a save and reopen; `pdf_font_widths_never_panic` in `crates/engine/tests/import_fuzz.rs` feeds hostile font dictionaries. Synthetic files written in the tests, with the copies of a font the test installs itself; no fixtures added. Scores and hours unchanged. + - **`.ai` Art brushes in Tints of a swatch's color (#8200):** `tints_of_a_swatch_stay_linked_to_it` in `crates/brush/src/tests.rs` covers Tints of a stroke color linked to a swatch: each piece is the swatch at the stroke's tint times how dark the art is there, linked to it, showing the same color as the unlinked result. `an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it` in `crates/eps/src/import/ai/tests.rs` covers a path with an Art brush in Tints whose stroke is a custom color: it comes in brushed, its stroke linked to the swatch. Synthetic files written in the tests; no fixtures added. Scores and hours unchanged. - **`.ai` clipping paths grouped in a compound path (#8128):** `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs` covers clipping paths grouped in a compound path (`*u u W n … U *U`, also nested in other groups): they are the compound path's subpaths, and the compound clipping path, their union, clips its clipping group however many there are and wherever in the group it is written. Synthetic files written in the test; no fixtures added. Scores and hours unchanged. @@ -821,6 +824,7 @@ since 2026-10-01. - **Arcs along General › Constrain Angle:** with a Constrain Angle other than 0° or a whole turn, an arc dragged out with the Arc tool and an arc placed from the Arc Segment Tool Options click dialog are drawn along the turned x and y axes, with their bounding box turned. The drag's box and Shift's equal lengths are measured along those axes, the reference point stays at the drag's corner or at the click, and F, C and ↑/↓ keep the turn. `shape.arc` takes an optional `rotation` (degrees clockwise, about `x1`, `y1` or about the reference point `x`, `y`); a `rotation` that is not a number is an error. At 0° and whole turns arcs are drawn as before, and quarter turns are exact. The help page () describes new objects being drawn along the turned axes; how the Arc tool's keys and reference point work with them is VectorCraft's own rule (tools `draw2::family::tests::arcs_follow_the_constrain_angle`; engine `constrain_angle_draws_a_dragged_arc_along_the_turned_axes`, `constrain_angle_turns_a_click_made_arc_about_its_reference_point`, `arc_rotation_turns_it_and_must_be_a_number`). Scores and hours unchanged. - **Spirals turn as they are dragged, and along General › Constrain Angle:** a spiral dragged out with the Spiral tool turns about its center so that its outer end is at the pointer, so dragging around the center turns it, while Alt, Ctrl/Cmd, ↑/↓, Space and Escape work as before. A spiral placed from the Spiral dialog starts along the x axis turned by a Constrain Angle other than 0° or a whole turn, with its bounding box turned. `shape.spiral` takes an optional `rotation` (degrees clockwise about `cx`, `cy`); a `rotation` that is not a number is an error, and without one spirals are drawn as before. The help page () says that moving the pointer around in a curve during the drag turns the new spiral, and the help page () describes new objects being drawn along the turned axes. Putting the outer end exactly at the pointer, keeping the last direction while the pointer is within 0.01 pt of the center, and leaving a dragged spiral's direction to the pointer with Shift or a Constrain Angle are VectorCraft's own rules (tools `draw2::family::tests::spiral_drag_turns_the_spiral_to_the_pointer`; engine `a_dragged_spiral_turns_its_outer_end_to_the_pointer`, `constrain_angle_turns_a_click_made_spiral`, `spiral_rotation_turns_it_and_must_be_a_number`; UI `spiral_click_dialog_starts_along_the_constrain_angle`). Scores and hours unchanged. - **Three-Point Arc tool:** a new tool in the Line Segment tool's group, after the Arc tool, draws an open circular arc. A drag or two clicks place its ends (Shift keeps the second end at 45° steps), and a third click places a point the arc passes through. With Third Point Sets Direction on (the tool's Tool Options, or `]` while drawing), the third point gives the direction the arc leaves its first end in, or with Alt the direction at its second end. The tool previews the arc and its center, and with Measurement Labels on its radius, shows "Arc too large" where no arc fits, and draws the arc in one undo step with `shape.threePointArc {start, end, through | toward, at?}` (geom `shapes::tests::the_arc_through_a_point_passes_through_it`, `the_arc_leaving_along_a_direction_has_that_tangent`, `degenerate_points_give_no_arc`, `the_path_via_the_third_point_passes_through_it_exactly`; tools `three_point_arc::tests`; engine `tests::three_point_arc`; ui-egui `dialogs::three_point_arc_options::tests`). Scores and hours unchanged. +- **Three-Point Arc joins open paths:** with Join to Open Path Ends on (Tool Options, or J while drawing), an end of the arc placed near an end of an open path lands on it and the arc is joined to that path, which keeps its look; with both ends on open path ends the paths become one, or the path closes when both are its own ends (`shape.threePointArc {join: true}`, one undo step). In direction mode, with the direction line starting on an open path's end, Snap Where the Arc Continues a Path (on by default) snaps the third point onto the line along which the arc carries the path on, the same way or turned back (https://docs.astutegraphics.com/subscribe/arc-by-points-tool/arc-by-points-preferences; tools `three_point_arc::tests::with_join_an_end_near_an_open_path_end_lands_on_it`, `in_direction_mode_the_third_point_snaps_to_carry_the_path_on`; engine `tests::three_point_arc::join_adds_the_arc_to_the_open_path_it_starts_on`, `join_with_both_ends_on_open_paths_makes_one_path`, `join_prefers_the_selected_path_then_the_front_one`, `join_leaves_paths_it_cannot_join_alone`, `the_tool_joins_the_arc_to_the_path_end_it_starts_near`). Scores and hours unchanged. - **Shape commands refuse invalid options:** `shape.arc` refuses a `reference` that is not a whole number from 0 to 8, a `baseAlong` other than `x` or `y` (either case), null included for both, and a `slope` outside −100…100, in both of its forms; before, such a value drew the arc with reference point 0 or 8, the X axis or the nearest slope. `shape.rectangularGrid` and `shape.polarGrid` refuse a divider count that is not a whole number of at least 0; before, such a count was 5. Each error names the key, and nothing is drawn. Left-out values keep their defaults. These ranges are VectorCraft's own command rules (engine `draw2::shape_arc_rejects_an_invalid_reference_base_along_or_slope`, `draw2::shape_arc_takes_every_reference_point_and_either_base_axis`, `draw2::grid_divider_counts_reject_fractions_and_negatives`). Scores and hours unchanged. - **Roughen at Size 0 keeps the outline:** with Size 0 (relative or absolute), Effect › Distort & Transform › Roughen… moves no point: each segment is split at the Detail spacing (fewer points past the anchor limit) into pieces of equal length on the segment itself, so the path keeps its outline, with Smooth or Corner points alike. A straight segment gets corner points without handles, and a curve gets smooth points whose handles follow it. Before, the points were joined by straight lines (Corner) or a smoothed curve through them (Smooth), which changed curved outlines. Existing documents with a Roughen of Size 0 on a curved path, or with Smooth points, draw differently. This is VectorCraft's own rule; what Roughen does is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `tests::roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly`). Scores and hours unchanged. @@ -1111,12 +1115,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, 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; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. + - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. + - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`. @@ -1185,7 +1191,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Map`, `Set`, `WeakMap` and `WeakSet`, and `ArrayBuffer`, `DataView` and the nine typed arrays from `Int8Array` to `Float64Array` with `%TypedArray%.from`, `of` and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2, https://262.ecma-international.org/6.0/); a realm without it, the ExtendScript realm included, has none of these names. `Map` and `Set` compare keys with SameValueZero, keep insertion order, and a `forEach` or an iterator's `next()` skips entries deleted before it reaches them and visits entries added during the walk. A `WeakMap` entry does not keep its key alive: the collector drops the entries of unreachable keys, also when the value refers back to its key. Typed arrays store their elements little-endian and `DataView` reads and writes big-endian unless `littleEndian` is true. A numeric property name of a typed array is an element or nothing, and its elements are writable, enumerable and configurable but cannot be deleted, as later editions define them. An `ArrayBuffer` longer than 2^32 - 1 bytes or than the heap limit gives a `RangeError` before anything is allocated, and every element a method visits takes fuel. 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, and 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; these rules are VectorCraft's own. Check Script counts `new` of these constructors as the language's, not as document-model types. `cargo xtask test262` runs the suite's tests of the eight `built-ins` folders that need only these built-ins in such a realm: 1,266 of 1,514 runs pass, and the 248 others expect a configurable function `length` and a function `name` property. The `TypedArray` folder's tests include a harness file that uses `Symbol` and `Array.from`, so they are skipped. Tests: `crates/js/src/collections_tests.rs`, `crates/scriptcheck/src/tests.rs` (`collections_and_typed_arrays_are_not_type_names`), `crates/js/tests/test262.rs`. + - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Map`, `Set`, `WeakMap` and `WeakSet`, and `ArrayBuffer`, `DataView` and the nine typed arrays from `Int8Array` to `Float64Array` with `%TypedArray%.from`, `of` and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2, https://262.ecma-international.org/6.0/); a realm without it, the ExtendScript realm included, has none of these names. `Map` and `Set` compare keys with SameValueZero, keep insertion order, and a `forEach` or an iterator's `next()` skips entries deleted before it reaches them and visits entries added during the walk. A `WeakMap` entry does not keep its key alive: the collector drops the entries of unreachable keys, also when the value refers back to its key. Typed arrays store their elements little-endian and `DataView` reads and writes big-endian unless `littleEndian` is true. A numeric property name of a typed array is an element or nothing, and its elements are writable, enumerable and configurable but cannot be deleted, as later editions define them. An `ArrayBuffer` longer than 2^32 - 1 bytes or than the heap limit gives a `RangeError` before anything is allocated, and every element a method visits takes fuel. `Map`, `Set` and the typed arrays are iterable, and their iterators inherit `%IteratorPrototype%`. The collection constructors read their argument through its `@@iterator` method and close the iterator when adding an entry throws (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1), so an object without `@@iterator` is a `TypeError`, and so is a `Map` or `WeakMap` entry that is not an object. 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 to the end before mapping it, 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. Check Script counts `new` of these constructors as the language's, not as document-model types. `cargo xtask test262` runs the suite's tests of the eight `built-ins` folders that need only these built-ins in such a realm: 1,266 of 1,514 runs pass, and the 248 others expect a configurable function `length` and a function `name` property. The `TypedArray` folder's tests include a harness file that uses `Symbol` and `Array.from`, so they are skipped. Tests: `crates/js/src/collections_tests.rs`, `crates/scriptcheck/src/tests.rs` (`collections_and_typed_arrays_are_not_type_names`), `crates/js/tests/test262.rs`. - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column when known. For rejections from code compiled by `eval` or `Function`, the `script.run` report omits the file and sets the line and column to 0. `all` and `race` preserve an input rejection's known location; calling a saved reject function from script uses that call's location. `all`, `allSettled` and `race` read `Symbol.iterator`, including user-defined iterables and overridden array iterators; string iterators keep surrogate pairs together, and objects with only a whole-number `length` reject with a `TypeError`. A failure while processing a yielded value closes the iterator with `return` when present, preserving the original exception if closing throws; a step that throws or finishes is not closed. The statics always make plain `Promise` objects (VectorCraft's own rule). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. @@ -1316,8 +1322,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). - The Reflect tool sets an axis with two clicks: a click sets the first point (and the reference point), and a second click reflects the selection across the line through both points as one undo step; Alt/Option on the second click reflects a copy, and a drag after the first click draws the axis from it ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-or-flip-objects.html)). A dashed line runs from the first point to the pointer until the second click. VectorCraft's own rules: an Alt-click opens the dialog and sets no axis; a second click whose snapped point is within 3 screen pixels of the first point's snapped point does nothing and the axis keeps waiting; Shift does not constrain a plain second click; Escape, Enter, a changed selection, an edit made outside the tool or another tool drops the waiting axis. A double-click arrives as two clicks: its first click is the second point, so a double-click away from the first point reflects the selection, and the double-click then opens the dialog with no axis waiting (tools `xform::transform::tests::a_second_reflect_click_reflects_across_the_line_through_both_points` and the four tests after it; engine `xform::two_reflect_clicks_reflect_across_their_line_as_one_undo_step`). - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). + - Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles when the image is distorted alone; with other objects the handles stand for the whole selection, and the image's corners follow the same warp without necessarily landing on them. The image's pixels are drawn in perspective between its corners on the canvas, in print and in every export that holds images, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn, as the `.ai` writers do for an image nested 8 deep in opacity masks, symbols, live objects and pattern tiles, or in a legacy `.ai` in symbols and live objects, not counting ordinary groups and layers, and leave out an image nested deeper; HP-GL plots leave images out); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Gradient Mesh and Place with Replace refuse a distorted image (Place with Replace refuses only when the object it measures is the distorted image and the placed file is not text, a raster image or a DCS file, so it does not refuse when the replaced object is a DCS file's plates); Update Links, Relink and Place with Replace of a raster image or a DCS file put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::place_with_replace_keeps_a_distorted_images_corners`, `dcs::place_with_replace_draws_the_files_clipping_path_through_a_distorted_images_corners`, `cmd::fileio::tests_psdslices::slices_placed_over_a_distorted_image_follow_its_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`, `ai_editing::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`, `legacy_ai::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`). - Perspective Distort and Free Distort (`object.distort`) put the corners of a type object's box and of a symbol instance's box exactly where the warp takes them, alone or with other objects; the object stays type or a symbol instance and is drawn through the warp, after any perspective projection it had, as type and symbols in perspective are, with the images in a symbol's art and their linked masks drawn in perspective between the corners the projection gives them; and corners that would fold its box over, carry it past the warp's horizon or lie too close together for a perspective map are refused with an error that names it, as is a perspective warp of type that Edit Text shows flat. VectorCraft's own rule (engine `xform::distort_puts_the_corners_of_type_and_symbol_instances_on_the_handles`, `distort_moves_type_and_symbol_instances_with_a_path_as_one`, `distort_refuses_corners_type_and_symbol_instances_cannot_follow`, `distort_refuses_type_being_edited_flat`; effects `group::tests::a_projection_puts_the_corners_of_the_images_in_a_symbols_art_where_it_takes_them`). - - Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles when the image is distorted alone; with other objects the handles stand for the whole selection, and the image's corners follow the same warp without necessarily landing on them. The image's pixels are drawn in perspective between its corners on the canvas, in print and in every export that holds images, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn, as the `.ai` writers do for an image nested 8 deep in opacity masks, symbols, live objects and pattern tiles, or in a legacy `.ai` in symbols and live objects, not counting ordinary groups and layers, and leave out an image nested deeper; HP-GL plots leave images out); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Gradient Mesh and Place with Replace refuse a distorted image (Place with Replace refuses only when the object it measures is the distorted image, so it does not refuse when the placed file is text or the replaced object is a DCS file's plates); Update Links and Relink put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`, `ai_editing::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`, `legacy_ai::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`). - Object › Create Object Mosaic on an image changed by Perspective Distort or Free Distort places each tile's cell of pixels between the image's corners, so the tiles are four-sided shapes that follow the perspective, in one undo step; a new size scales them from the top left of the image's bounds, and the spacing and Use Ratio measure a pixel by the mean length of the image's two sides along each axis (VectorCraft's own rule; engine `object_mosaic_tiles_of_a_distorted_image_follow_its_corners`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). - With Smart Guides › Transform Tools on, a Free Transform shear (Cmd/Ctrl on a side handle) shows its angle next to the pointer, as the Shear tool does, and a handle drag that turns from a scale into a shear and back shows only the current operation's value ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)). The angle's sign and its one decimal place are VectorCraft's own rule, the same as the Shear tool's label (tools `xform::free::tests::shear_drag_shows_its_angle_with_transform_tools_guides`, `a_handle_drag_that_changes_operation_relabels_it`). @@ -1606,7 +1612,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Direct Selection (#1278):** clicking a segment picks its connection, with hollow endpoint anchors and only that curve's direction handles. Delete leaves the neighboring curves and appearance intact, opens/splits contours in one undo step, and another Delete removes the remaining selected path. A whole-path drag and deliberate anchor selection keep their existing behavior; egui frames and native control/art checked, OS mouse/visual QA pending. Where anchors of overlapping objects coincide, a click or drag takes the anchor of the selected object, also when another object lies over it (#1509, fixes #1508). Delete removes every selected anchor of a closed path (it used to remove the wrong ones), removes objects selected whole along with the selected anchors of others, and keeps the remainder selected so a second Delete removes it (#1674). In isolation mode Direct Selection and Group Selection pick only inside the isolated object (#1666). Escape cancels a Direct Selection drag (#1803, #1743). Double-clicking type (including type nested inside a group) switches to the Type tool and puts the caret at the clicked character. With Direct Selection and Group Selection, a drag that starts on an object while the selection also holds direct-selected anchors or segments moves those anchors and the objects selected whole in one undo step (`path.moveAnchors`), as a drag of a selected anchor does, and the other anchors of a partly selected path stay in place. While Alt is held during the drag, it copies the selected objects instead (`object.transform`). When direct-selected anchors are moved or transformed together with objects selected whole (such a drag, an anchor drag, an arrow key, or Move, Rotate, Scale, Reflect and Shear without a copy), a path inside a selected group is transformed once, with the group. VectorCraft's own preference General › Interpolate Control Points When Moving Anchors (`interpolateControlPoints`, off by default, fixes #7832): on, a Direct Selection drag, an arrow-key nudge, a Move or a Transform Again of selected anchors re-maps both handles of each segment with one moved end by the turn, uniform scale and move that take its old ends to its new ends, so a segment between corner anchors keeps its shape; a segment with both ends moved, or with its ends at the same place before or after the move, moves rigidly, and a smooth anchor keeps its handles in line. The commands take an `interpolate` param that defaults to the preference, and the value used joins the journal and Transform Again. Each drag or nudge is one undo step (`a_nudge_with_the_preference_on_re_maps_both_handles_of_the_segment`, `a_direct_selection_drag_with_the_preference_on_re_maps_the_handles_in_one_undo_step`, `a_smooth_anchor_keeps_its_handles_in_line`). - Picking several direction handles is VectorCraft's own behavior. With Direct Selection, a click on a path's direction handle picks it, a Shift-click adds or removes it without moving it, and Escape lets the picked handles go. Dragging one of two or more picked handles moves all of them, on one path or several, by the same offset in one undo step (`path.moveHandles`); an anchor with both handles picked becomes a corner, and Alt makes each moved handle's anchor a corner (`a_drag_of_one_of_two_picked_handles_moves_both_in_one_undo_step`, `shift_click_and_escape_let_picked_handles_go`, `both_handles_of_an_anchor_or_alt_make_a_corner` in `crates/engine/tests/it/several_handles.rs`). + Picking several direction handles is VectorCraft's own behavior. With Direct Selection, a click on a path's direction handle picks it, a Shift-click adds or removes it without moving it, and Escape lets the picked handles go. Dragging one of two or more picked handles moves all of them, on one path or several, by the same offset in one undo step (`path.moveHandles`); an anchor with both handles picked becomes a corner, and Alt makes each moved handle's anchor a corner; a move by 0, 0 leaves a live shape live when it makes none of its anchors a corner (`a_drag_of_one_of_two_picked_handles_moves_both_in_one_undo_step`, `shift_click_and_escape_let_picked_handles_go`, `both_handles_of_an_anchor_or_alt_make_a_corner`, `a_move_by_nothing_leaves_a_live_shape_that_needs_no_change_live` in `crates/engine/tests/it/several_handles.rs`). VectorCraft's own preference General › Delete Removes Anchor Points and Keeps Paths Joined (`deleteKeepsPathsJoined`, off by default, part of #8326): on, Delete, Backspace and Edit › Clear remove the direct-selected anchors of each path as Remove Anchor Points does, refitting the curve around each one, so a closed path stays closed and an open path stays in one piece; the next anchor along (the one before at an open path's end) is selected, so the next Delete goes on along the path. Paths with a selected segment are still cut there, objects selected whole are still deleted, and a path left with fewer than two anchors goes, in one undo step. `edit.clear` takes a `keepJoined` param that defaults to the preference, and the value used joins the journal (`with_the_preference_on_delete_keeps_a_closed_path_closed_and_selects_the_next_anchor`, `several_paths_and_an_object_selected_whole_change_in_one_undo_step`, `with_the_preference_on_delete_and_backspace_keep_the_path_joined`). VectorCraft's own preference General › Double-Click Adds Anchor Points (`doubleClickAddsAnchorPoints`, off by default, part of #8326): on, a double-click without modifier keys on a path segment with Direct Selection adds an anchor at the clicked point, keeping the curve's shape, with only the new anchor selected, in one undo step (`path.insertAnchor` with `selectAnchor`); on an anchor, a handle, a center point, a blend's spine point or a fill the double-click does what it did before, and a clipping path's segment gets the anchor (`with_the_preference_on_a_double_click_on_a_segment_adds_an_anchor_there`, `with_the_preference_on_a_double_click_in_a_group_adds_only_on_a_segment`, `with_the_preference_on_a_double_click_gives_way_to_spine_points_and_reaches_clipping_paths`, `with_the_preference_on_a_double_click_on_a_segment_adds_an_anchor_in_one_undo_step`, `the_double_click_and_delete_preferences_are_separate`). A path segment with a control point whose x or y is infinite or larger in size than `f64::MAX / 16` is measured by its control points, so its bounds hold the whole curve and the canvas check refuses an edit that leaves such a path selected (`path.create` included). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4c0eaa6d5a..a2adfd855e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -451,6 +451,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Interaction | Status | Evidence | |---|---|---| | Brush Options › Key Color eyedropper yields to one canvas click, then resumes the same draft and previous tool | done | #8284; the pick changes the dialog draft without painting or editing the document. OK applies the brush options; Cancel discards them. Escape ends the pick without sampling before a later Escape cancels the dialog. Six full-app input regressions in `crates/ui-egui/tests/brush_keycolor_modal_repro.rs` cover the actual pick, OK/reopen/Cancel, Escape, reentry, held clicks, stale releases and ordinary modal blocking. | +| Brush Options skip unchanged approval | done | Approving without editing preserves the brush, document revision and Undo history. | | Ordinary Save refused by filesystem permissions/read-only storage offers Save As | focused UI regressions passed; native acceptance pending | #6146; `io::tests_read_only_save`; same name/format suggested; unchanged format keeps options, changed format opens its Save options; Documents folder, UID-bound continuation; cancellation and automation isolation | | Selection artwork drag hovers a visible document tab to activate it, then drops editable artwork on its canvas | done | `tests_document_drag`, `edit.dropSelection`, lossless resource and one-step Undo regressions; a release over another document's tiled pane copies it there too (`canvas::panes` tests), and so does a release over a floating window drawn inside the main window (`doc_windows` tests); overflow-menu drag and floating OS windows remain separate | | A document tab dragged along the tab strip moves its document; a line marks where it goes, the current document and every document's view stay as they were, and a drag off the strip still floats it | done | #5663, [public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html); `document.move`; `tests::tab_reorder`, `chrome::tests` (drop index with floating and view tabs), `engine` `tests::document_move` |